Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fdbe593802 | ||
|
|
b2b3a1d218 | ||
|
|
da32044d5b | ||
|
|
b37b2265ed | ||
|
|
2200e46d98 | ||
|
|
f58d55555c | ||
|
|
6b67ab759b | ||
|
|
1048c01fd9 | ||
|
|
ae70567e63 | ||
|
|
096b6f6bfe | ||
|
|
9e5c393709 | ||
|
|
291cf176db | ||
|
|
2a05516036 | ||
|
|
8f4ff2a97d | ||
|
|
e02d0b173f | ||
|
|
a10ce2d9de | ||
|
|
5bf56fde57 | ||
|
|
64453d2a91 | ||
|
|
ded1095c39 | ||
|
|
653627b8c4 | ||
|
|
62fc7d71a3 | ||
|
|
84cb27a810 | ||
|
|
3ba70bb69f | ||
|
|
3359f1a196 | ||
|
|
049f3ee270 |
386
README.md
386
README.md
@@ -1,6 +1,6 @@
|
|||||||
# golem15.sitemap
|
# golem15.sitemap
|
||||||
|
|
||||||
The compiled sitemap plugin for SummerCMS applications: it serves `/sitemap.xml` and its stylesheet from one sitemap definition editors manage in the admin, byte for byte the way the WinterCMS Golem15.Sitemap plugin did.
|
The compiled sitemap plugin for SummerCMS applications: it serves a sitemap index at `/sitemap.xml` whose per-type files of a configurable size keep their numbers across rebuilds and carry real lastmod and hreflang alternates, built from every content type's published records, with image and Google News sitemaps, IndexNow notifications and the data of the site's HTML sitemap.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import _ "git.golem15.com/golem15/sm-sitemap-plugin"
|
import _ "git.golem15.com/golem15/sm-sitemap-plugin"
|
||||||
@@ -12,21 +12,37 @@ Module `git.golem15.com/golem15/sm-sitemap-plugin`, package `sitemap`, plugin ID
|
|||||||
|
|
||||||
The plugin is a compiled SummerCMS plugin. Its `init` registers it with the framework, so an application loads it by listing it in `summer.yaml`; `summer build` then emits the blank import above into the application's `plugins.gen.go`.
|
The plugin is a compiled SummerCMS plugin. Its `init` registers it with the framework, so an application loads it by listing it in `summer.yaml`; `summer build` then emits the blank import above into the application's `plugins.gen.go`.
|
||||||
|
|
||||||
It is a port of the WinterCMS plugin for headless sites. An application has one sitemap definition (`models.Definition`, theme key `default`), a list of items: explicit URLs and items of the menu item types other plugins register with the framework's registry (`signpost`). `Requires()` is empty: content plugins such as the Journal register their types and the sitemap reads them through the registry.
|
Content plugins describe their records to the framework's registry (`signpost` content types). The sitemap reads them through `signpost.Registry.Records`, page by page, and never imports a content plugin: `Requires()` is empty. Every listed address is a row of the slot table `golem15_sitemap_urls`, which places it in a file `sitemap-<slug>-<n>.xml` of its group. A rebuild keeps every address in its file, appends new ones to the last file with room and leaves a hole where an address left; only a changed file size renumbers the files. The routes serve from the table and never generate per request.
|
||||||
|
|
||||||
The output keeps the PHP plugin's bytes: element order, escaping, whitespace, date format, headers and the `frontend_url` rewrite are not changed. The goldens in `classes/testdata` are generated from the PHP code and pin them.
|
Other plugins narrow the sitemap through the `contract` package: the SEO plugin publishes a `contract.Filter` that leaves noindex, canonicalised and redirected addresses out, and reads the sitemap through the `contract.Listing` the plugin publishes. Without a Filter every published address is listed.
|
||||||
|
|
||||||
|
The same table feeds the image sitemap (each page's featured and body images), the Google News sitemap (articles of the last two days), IndexNow (each rebuild's added, changed and removed addresses, posted to `api.indexnow.org` in production) and the HTML sitemap API that the site's HTML sitemap page renders. Every setting can be read and changed through a management API that is also an MCP tool set.
|
||||||
|
|
||||||
|
### Breaking change from v0.1 (D-32)
|
||||||
|
|
||||||
|
v0.1 served one `/sitemap.xml` in the WinterCMS byte format from a definition of items, with priority, change frequency, priority tiers, an update manifest and the `/sitemap.xsl` stylesheet. The per-type format replaces it:
|
||||||
|
|
||||||
|
- `/sitemap.xml` is now a sitemap index; its URL is unchanged, so robots.txt `Sitemap:` lines and Search Console submissions keep working.
|
||||||
|
- The files are `/sitemap-<slug>-<n>.xml` at the site root. Go serves them at `/_sitemap/files/{file}`; the site's SEO layer (vue-seo-layer) or its proxy maps the root names there.
|
||||||
|
- `/sitemap.xsl` answers 404, and no `<priority>` or `<changefreq>` is written.
|
||||||
|
- The definitions screen and the old settings tile are one settings singleton. The url items of the definition move to the additional addresses (`models.ConvertLegacyItems`): a relative path such as `o-nas` gets its leading slash, as v0.1 resolved it against the site root, spaces and the characters `"`, `<`, `>` and `\` are percent-encoded, and a duplicate is copied once. An item that still cannot be an additional address (an absolute URL with `&`, another scheme, a malformed item) is not copied and logged at startup as `golem15.sitemap: definition url item not copied` with the item, its value and the reason; the other items are copied. `frontend_url` moves to the site address and `frontend_default_locale` to the default locale (migration `202610280002`). Reference items are dropped: the content types list their records. The `golem15_sitemap_definitions` table and the Phase 17 settings columns stay in the database, unread, so a rollback loses nothing.
|
||||||
|
- The config keys `golem15.sitemap.cache_seconds` and `golem15.sitemap.priority_tiers` and the festival events `BeforeAddItem` and `AddItem` are gone.
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Routes.** Anonymous `GET /sitemap.xml` and `GET /sitemap.xsl` at the application root, without the backend middleware. `/sitemap.xml` is throttled per client IP and its output is cached for a short time.
|
- **Index and files.** `GET /sitemap.xml` lists one `<sitemap>` per file with an address, with the newest lastmod of its addresses. `GET /_sitemap/files/{file}` serves one file: `<loc>`, `<lastmod>` and `xhtml:link` alternates per address, `X-Robots-Tag: noindex`. Both are `application/xml`, anonymous and throttled per client IP.
|
||||||
- **One definition.** Table `golem15_sitemap_definitions` keeps the PHP columns (`id`, `theme` nullable and indexed, `data` text, timestamps). The `theme` column holds the fixed key `default` (`models.DefinitionTheme`); `/sitemap.xml` serves that row. `models.Definition.Fillable` is exactly `theme` and `data`, the PHP `$fillable` with `$guarded = ['*']`.
|
- **Stable numbering.** A file holds at most the file size setting's addresses (default 1000, 1 to 50 000). Addresses keep their file number; new ones are appended oldest first; a deleted, unpublished or excluded address leaves a hole. A changed file size renumbers every file in the next rebuild.
|
||||||
- **Items.** An item is a URL (`type: url`) or a registry menu item type. Winter.Pages static pages, all static pages and the CMS page field are not ported. Stored item JSON in the PHP shape decodes tolerantly: numbers, strings and booleans are coerced, and unknown keys (`cmsPage`, `code`, `exists`, `fillable` and any other) are ignored. A save writes the PHP `toArray` key set (`changefreq`, `priority`, `nesting`, `type`, `url`, `reference`, `cmsPage` as null, `urlPattern`).
|
- **Real lastmod.** A row's lastmod starts at the record's last change and then moves only when a `pact.RecordSaved` reports a change outside `golem15.sitemap.lastmod_ignore`: a no-op save, a counter update or a rebuild leaves it as it was.
|
||||||
- **Settings.** A singleton row (`golem15_sitemap_settings`, id 1) holds the frontend URL, the frontend default locale, the updates manifest path and the priority tiers, with the PHP defaults.
|
- **hreflang.** Every address of a record with more than one listed locale carries an alternate per locale, itself included, plus `x-default` on the default locale's address. A locale without an address gets none, a single-locale record none.
|
||||||
- **Priority tiers.** Rules in config (`golem15.sitemap.priority_tiers`) map URL paths to five priority settings; the shipped defaults are the PHP plugin's rules.
|
- **Groups.** A content type's group is the last segment of its key in plural form (`journal-post`: `posts`, `journal-category`: `categories`, `seo-page`: `pages`), or the file name set in the settings. Additional addresses go to `pages`. A Filter may move an address to another group (`offers`).
|
||||||
- **Hooks.** Typed festival events `classes.BeforeAddItem` and `classes.AddItem` replace the PHP events `golem15.sitemap.beforeAddItem` and `golem15.sitemap.addItem`.
|
- **Rebuilds.** A conga job (`golem15.sitemap.rebuild`): queued after record changes, debounced to one per `golem15.sitemap.rebuild_delay_seconds`; dispatched on every settings save; run every night at 03:00 by the scheduled `sitemap:rebuild`; and by hand.
|
||||||
- **Admin.** The definition opens from the Settings page as a singleton form with a repeater of item rows; a second settings entry holds the settings form. Permission `golem15.sitemap.access_definitions`.
|
- **Image sitemap.** `sitemap-images-<n>.xml` lists every listed page with images: its `<loc>` and one `image:image`/`image:loc` per image (the featured image first, then the body's; at most 1000 per page), numbered stably like the per-type files. On by default.
|
||||||
- **Commands.** `sitemap:import` (the PHP JSON import) and `sitemap:import-winter` (a copy of a WinterCMS site's definition and settings).
|
- **Google News sitemap.** `sitemap-news.xml` lists at most 1000 articles (content kind `article`) first published in the last two days, newest first, with the publication name, the language, the publication date and the title; narrowed to chosen article types and categories. Off by default.
|
||||||
- **Phrasebooks.** `lang/en/lang.yaml` and `lang/pl/lang.yaml` keep the PHP key names.
|
- **IndexNow.** A key generated on save and served as `<key>.txt`; after each rebuild in production the added, changed and removed addresses go to `api.indexnow.org` in a queued job, and the last answer shows in the settings. Off by default.
|
||||||
|
- **HTML sitemap API.** `GET /_sitemap/api/v1/html` and `/_sitemap/api/v1/html/{group}` answer the HTML sitemap's groups and pages from the same indexable set as the XML sitemaps (D-34); the site's layer renders them.
|
||||||
|
- **Settings singleton.** One tile in the CMS settings category: Files (site address, file size, the files table), Content types (per type: include, file name, HTML sitemap heading), Additional addresses, Images and News, IndexNow and HTML sitemap.
|
||||||
|
- **Management API and MCP.** `GET`/`PUT /_sitemap/api/v1/settings` and `POST /_sitemap/api/v1/rebuild`, and the MCP tools `sitemap_get_settings`, `sitemap_update_settings` and `sitemap_rebuild` (D-10).
|
||||||
|
- **Contract.** `contract.Filter` for other plugins to implement, `contract.Listing` for other plugins to read and `contract.Rebuilder` for other plugins to ask for a rebuild (D-95).
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
@@ -40,215 +56,271 @@ plugins:
|
|||||||
|
|
||||||
The plugin's own `go.mod` and `go.work` replace the framework with `../summercms.go` for a sibling checkout.
|
The plugin's own `go.mod` and `go.work` replace the framework with `../summercms.go` for a sibling checkout.
|
||||||
|
|
||||||
### /sitemap.xml and /sitemap.xsl
|
The application needs a conga worker (`summer queue:work`) for the rebuild and IndexNow jobs, and the scheduler for the nightly rebuild. Without a worker, run `sitemap:rebuild` yourself (IndexNow then waits for a worker).
|
||||||
|
|
||||||
`GET /sitemap.xml` answers:
|
### Routes
|
||||||
|
|
||||||
- `404` when there is no definition with the theme `default`;
|
| Route | Answer |
|
||||||
- `200` with an empty body when the definition has no items;
|
|-------|--------|
|
||||||
- otherwise the sitemap, `Content-Type: application/xml`, `Cache-Control: no-cache, private`.
|
| `GET /sitemap.xml` | The index: the per-type files, then the image files (while the image sitemap is on), then `sitemap-news.xml` (while the News sitemap is on and lists an article). `404` while no site address is configured (a `<loc>` is never built from the request's Host). Before the first rebuild it is an empty `<sitemapindex>`. |
|
||||||
|
| `GET /_sitemap/files/{file}` | One file, `{file}` matching `sitemap-(news\|[a-z0-9-]+-[0-9]+)\.xml`: a per-type file, an image file `sitemap-images-<n>.xml` or the News file. `404` for an unknown file, one whose addresses all left, and the image or News file while it is off. |
|
||||||
|
| `GET /_sitemap/indexnow/{file}` | The IndexNow key file `<key>.txt` as `text/plain` while IndexNow is on; `404` for any other name, an old key or IndexNow off. |
|
||||||
|
| `GET /_sitemap/api/v1/html?locale=` | The HTML sitemap overview (JSON, below). `404` while the HTML sitemap is off or for a malformed locale. |
|
||||||
|
| `GET /_sitemap/api/v1/html/{group}?locale=&page=` | One page of a group. `404` for an unknown group, a page past the last or a malformed page, and while the HTML sitemap is off. |
|
||||||
|
| `GET /_sitemap/api/v1/settings`, `PUT /_sitemap/api/v1/settings`, `POST /_sitemap/api/v1/rebuild` | The management API (below). |
|
||||||
|
| `GET /sitemap.xsl` | Gone: `404`. |
|
||||||
|
|
||||||
Generating the sitemap resolves every registry item (all published posts, all categories, their translations), so the route is guarded:
|
The sitemap files and the key file use the surf throttle bucket `sitemap-xml` (`sitemap.BucketSitemap`): 60 requests a minute per client IP, read behind the host's trusted proxies. The HTML sitemap API uses `sitemap-html` (`sitemap.BucketHTML`, 300 a minute: the site's server calls it for every HTML sitemap page it renders, so it must be a trusted proxy forwarding `X-Forwarded-For`), the management API `sitemap-api` (`sitemap.BucketAPI`, 300 a minute). Every value is written through `encoding/xml`'s escaping; every answer but the index carries `X-Robots-Tag: noindex`.
|
||||||
|
|
||||||
- **Throttle.** The surf bucket `sitemap-xml` (`sitemap.BucketSitemap`) allows 60 requests a minute per client IP, read behind the host's trusted proxies. The 429 body is surf's `{"message":"Too Many Attempts."}`. `/sitemap.xsl` is not throttled.
|
The index lists the files at the site root, for example:
|
||||||
- **Cache.** The generated document is kept in memory for `golem15.sitemap.cache_seconds` seconds (`sitemap.CacheConfigKey`, default `60`; `0` turns it off, a negative value fails the boot). The cache key covers the root URL and the stored definition and settings, so a save of either is served at once; a change of registry content (a new or unpublished post) shows once the entry expires. One generation runs at a time; concurrent requests for a missing entry wait for it.
|
|
||||||
|
|
||||||
The document is the PHP `DOMDocument::saveXML()` format: the XML declaration and the `xml-stylesheet` processing instruction each followed by a newline, everything else on one line ending with `</urlset>` and a newline. Items that all resolve to nothing produce a self-closing `<urlset .../>`. Text is escaped like libxml (`&`, `<`, `>` and carriage return; attributes also `"`, tab and newline); single quotes and UTF-8 stay literal.
|
```xml
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||||
|
<sitemap><loc>https://www.example.com/sitemap-posts-1.xml</loc><lastmod>2026-10-28T09:00:00Z</lastmod></sitemap>
|
||||||
|
</sitemapindex>
|
||||||
|
```
|
||||||
|
|
||||||
Each URL is written in the PHP order (`classes.Generator`):
|
A site whose frontend proxies the backend maps `/sitemap-<slug>-<n>.xml` and `/sitemap-news.xml` to `/_sitemap/files/<name>`, and the IndexNow key file `/<key>.txt` to `/_sitemap/indexnow/<key>.txt`. vue-seo-layer does it from v0.2.0 (the key file name comes from `contract.ListingSettings.KeyFile` through the SEO plugin's site answer); with nginx:
|
||||||
|
|
||||||
1. The 50000th URL is written, the 50001st is not (`classes.MaxURLs`).
|
|
||||||
2. A URL item's address goes through the port of Winter's `Url::to` (`classes.URLTo`): root plus the path trimmed of slashes, `/` keeps its slash, every path segment re-encoded like `rawurlencode`, valid absolute, `mailto:`, `tel:` and fragment URLs kept.
|
|
||||||
3. `lastmod` is the record's modification time, else the updates manifest's date for the URL path, else omitted. It is written as `2006-01-02T15:04:05+00:00` in UTC.
|
|
||||||
4. `classes.BeforeAddItem` may drop the URL.
|
|
||||||
5. A URL that does not come out as an `http` or `https` URL (for example a `javascript:` URL an import or a registry type let through) is dropped, and so is such an alternate. The PHP plugin wrote any URL `Url::to` kept; the stylesheet renders `<loc>` as a link on the site's origin.
|
|
||||||
6. The priority is the first matching tier's setting when tiers are on, else the item's priority, written as stored text (`1.0` stays `1.0`).
|
|
||||||
7. `loc`, `lastmod`, `changefreq` and `priority` are written, then the alternates as `xhtml:link` elements, only when there are more than one.
|
|
||||||
8. `classes.AddItem` may append XML before `</url>`.
|
|
||||||
|
|
||||||
A registry item is resolved with its URL pattern, its nesting flag and the settings' frontend default locale as the unprefixed locale. A resolved item with a URL is written, then its sub-items once each with their own URL. A list type (a resolved item without a URL, such as all posts) writes each sub-item once per alternate, with that alternate's URL as `loc` and every alternate as `hreflang`, which is what the PHP list types returned.
|
|
||||||
|
|
||||||
When the settings hold a frontend URL, the backend URL (`app.url` when set, else the request's scheme and `Host`) is replaced literally inside every `<loc>`, every `xhtml:link href` and the stylesheet href, as the PHP `str_replace` did. The rewrite runs only for a frontend URL `models.AllowedFrontendURL` accepts, and a `<loc>` or `href` that would not stay an `http` or `https` URL keeps its value. The scheme is `https` for a TLS connection, or when the immediate peer is in `http.trusted_proxies` and its `X-Forwarded-Proto` says `https`.
|
|
||||||
|
|
||||||
`GET /sitemap.xsl` serves the PHP plugin's stylesheet byte for byte, `Content-Type: text/xsl; charset=UTF-8`.
|
|
||||||
|
|
||||||
A frontend served from another host routes both paths to the application, before its catch-all:
|
|
||||||
|
|
||||||
```nginx
|
```nginx
|
||||||
location = /sitemap.xml {
|
location ~ ^/(sitemap-[a-z0-9-]+\.xml)$ {
|
||||||
proxy_pass http://127.0.0.1:8096;
|
proxy_pass http://backend/_sitemap/files/$1;
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
|
||||||
}
|
}
|
||||||
location = /sitemap.xsl {
|
location ~ ^/([A-Za-z0-9-]{8,128}\.txt)$ {
|
||||||
proxy_pass http://127.0.0.1:8096;
|
proxy_pass http://backend/_sitemap/indexnow/$1;
|
||||||
proxy_set_header Host $host;
|
|
||||||
proxy_set_header X-Forwarded-Proto $scheme;
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Item types
|
### Site address
|
||||||
|
|
||||||
| Type | Item fields used |
|
Every `<loc>` starts with the Site address setting; when it is empty, with the config key `golem15.sitemap.site_url`; else with `app.url`. Each must be an absolute `http`/`https` URL without whitespace, quotes, `<`, `>` or `&` (`models.AllowedFrontendURL`); a value outside that form is skipped.
|
||||||
|------|------------------|
|
|
||||||
| `url` | `url`, `changefreq`, `priority` |
|
|
||||||
| A registry type (for example `journal-post`) | `reference` (when the type takes one), `urlPattern` (overrides the host and default patterns), `nesting`, `changefreq`, `priority` |
|
|
||||||
|
|
||||||
The admin's type dropdown offers `url` and every registry type in registry order with its label. The reference dropdown depends on the row's type and lists the type's references (`signpost.ReferenceOptions`); `url` and types without references take none, and a reference the type does not offer is refused on save.
|
### Lastmod
|
||||||
|
|
||||||
A save also refuses, per row, a missing `reference` for a registry type that takes one (such a row would resolve to nothing and be left out of the sitemap), a `url` that is not a path (relative or starting with a single `/`) or an absolute `http`/`https` URL (`classes.AllowedItemURL`: no other scheme, no protocol-relative `//host`, no bare fragment, no surrounding whitespace or control characters), and a `urlPattern` that is not a path starting with a single `/` (`signpost.ValidItemPattern`). The errors are keyed `data.<row>.reference`, `data.<row>.url` and `data.<row>.urlPattern`.
|
`classes.RecordSaved` handles every `pact.RecordSaved` of a model a content type declares:
|
||||||
|
|
||||||
### Settings
|
- a change of an attribute on the record's own row moves the lastmod of all its addresses to now;
|
||||||
|
- a translated change (`RecordChange.Locale` set) moves only that locale's address;
|
||||||
|
- changes of attributes in `golem15.sitemap.lastmod_ignore` (default `updated_at`, `created_at`, `views`, `sort_order`) and a save without changes move nothing.
|
||||||
|
|
||||||
| Setting | Default | Meaning |
|
A `pact.RecordDeleted` takes the record's addresses out of the files at once. Both queue a debounced rebuild. A rebuild sets the lastmod of a new address from the record's `LastMod` (or the Filter's `Decision.LastMod`) and never moves an existing one; an additional address carries the lastmod the editor gives it.
|
||||||
|---------|---------|---------|
|
|
||||||
| `frontend_url` | empty | The public frontend URL that replaces the backend URL in the XML: empty, or an absolute `http` or `https` URL with a host and without whitespace, control characters, a double quote, a less-than sign, a greater-than sign or an ampersand (`models.AllowedFrontendURL`). A stored value outside this form is not applied and the sitemap keeps the backend URL. |
|
|
||||||
| `frontend_default_locale` | empty | The locale whose URLs carry no prefix, passed to registry types; empty leaves it to the type. |
|
|
||||||
| `updates_manifest_path` | empty | A JSON file mapping a URL path to an ISO 8601 date, used as `lastmod` for items without their own date. |
|
|
||||||
| `enable_priority_tiers` | on | Tier priorities replace item priorities. |
|
|
||||||
| `priority_homepage`, `priority_services`, `priority_blog`, `priority_categories`, `priority_legal` | `1.0`, `0.8`, `0.6`, `0.4`, `0.2` | The tier values, stored as text. |
|
|
||||||
|
|
||||||
A save refuses a `frontend_url` outside the accepted form with a 422 keyed `frontend_url` (phrase `golem15.sitemap::lang.errors.frontend_url`), and `sitemap:import-winter` stops with an error. The PHP plugin stored any text and wrote it unescaped into `<loc>`, the hreflang links and the stylesheet instruction.
|
### Rebuilds
|
||||||
|
|
||||||
The updates manifest is read only when it is a regular file of at most 5 MiB (`classes.ManifestMaxBytes`) holding a JSON object; paths match with the leading slash added and the trailing slash removed (`/` stays). Any error omits `lastmod` and is logged without the file's content. The manifest is a frontend build output, for example a script that writes the git commit date of each static page's source:
|
`classes.Rebuild` walks `signpost.Registry.ContentTypes` in registration order, pages `Records` 500 at a time, keeps the published records' locales with an address, asks the Filter per page, adds the additional addresses and writes everything. The whole rebuild runs in one transaction that first takes the advisory lock `golem15.sitemap.rebuild` and then reads the settings, collects and applies holding the settings row, so a second rebuild collects only after the first has committed and an older snapshot never overwrites a newer one. A rebuild never writes the lastmod of a content row it did not create (only an additional address takes its lastmod from the settings), so a lastmod a record save moved meanwhile stays. It returns the added, changed and removed absolute URLs.
|
||||||
|
|
||||||
|
Record events set `rebuild_pending_until` with a conditional update and enqueue one rebuild with that delay only when no pending time lies in the future; the job clears it when it starts. A settings save dispatches a rebuild at once (a `summer_jobs` row labelled "Rebuild the sitemaps").
|
||||||
|
|
||||||
|
A rebuild also stores each address's page images, the type's kind (`pact.ContentDescriptor.Kind`), the record's first publication and its parents, which the image and News sitemaps and the HTML sitemap read.
|
||||||
|
|
||||||
|
### Image sitemap
|
||||||
|
|
||||||
|
`classes.PageImages` takes a locale's featured `Image`, then its `Images` in document order: a path on the site or an absolute `http`/`https` URL (a `//host/...` address is read as https), each once, at most `classes.MaxImagesPerURL` (1000). Other values (`data:`, `javascript:`, relative paths) are dropped. The rows with images are numbered into `sitemap-images-<n>.xml` (`image_file_no`) with the per-type files' rules and file size: a page that loses its images leaves a hole, a changed file size renumbers. A file has only `image:image` and `image:loc` (`classes.NSImage`), the tags Google still reads. The image sitemap is on by default (`images_enabled`).
|
||||||
|
|
||||||
|
### News sitemap
|
||||||
|
|
||||||
|
`classes.NewsEntries` lists the listed addresses of content types whose kind is `article`, first published (`ContentRecord.PublishedAt`) within the last 48 hours, newest first, at most 1000 (`classes.MaxNewsEntries`), as Google requires of a News sitemap. Each entry has the publication name (the `news_publication` setting, else `app.name`), the language (the locale's primary subtag, `classes.NewsLanguage`), the publication date and the title (`classes.NSNews`).
|
||||||
|
|
||||||
|
The News sources setting (`news_sources`) narrows the list. It takes the values `type:<type key>` (every article of a type) and `category:<type key>:<id>` (the articles under that parent, `ContentRecord.Parents`); empty means every article type. The Images and News tab lists the values the site has (`classes.NewsSources`: the article types and the parents their articles name), and `sitemap_get_settings` answers them as `news_source_options`. Turn the News sitemap on only for a site accepted in Google News.
|
||||||
|
|
||||||
|
### IndexNow
|
||||||
|
|
||||||
|
[IndexNow](https://www.indexnow.org/documentation) tells Bing, Yandex and the other participating engines about changed addresses at once; Google does not use it.
|
||||||
|
|
||||||
|
- **Key.** Saving the settings with IndexNow on generates a key of 32 hex characters from `crypto/rand` (`classes.GenerateKey`, `classes.EnsureKey`). The "Generate a new key on save" checkbox (`indexnow_new_key`, no column) replaces it, and the old key file answers 404 at once. The key file `<key>.txt` is served at `/_sitemap/indexnow/<key>.txt` and belongs at the site root, which covers every address of the host, so no `keyLocation` is sent.
|
||||||
|
- **Notifications.** After a rebuild commits, in the `production` environment only, with IndexNow on, a key and a site address, `classes.NotifyIndexNow` queues the conga job `golem15.sitemap.indexnow` (`classes.IndexNowArgs`) with the added, changed and removed addresses on the site's host, at most 10 000 per job. A record deleted in the admin (`pact.RecordDeleted`) is sent as removed and a content edit that keeps the address (`pact.RecordSaved` moving its lastmod) as changed: the listeners mark the rows (`indexnow_pending_at`) and the next rebuild sends and clears them; outside production the marks are cleared without a notification. The job (`classes.SendIndexNow`) posts `{host, key, urlList}` to `https://api.indexnow.org/indexnow` through a `fetchguard` client that may reach only that host (HTTPS, no redirects, 10 s), never an address of another host.
|
||||||
|
- **Answers.** 200 and 202 are success. Every answer is recorded (`indexnow_last_at`, `indexnow_last_count`, `indexnow_last_status`). 400, 403 and 422 are not retried; 429 and 5xx answers and network errors fail the job, which retries up to five times.
|
||||||
|
- **Status.** The IndexNow tab's status partial shows the key and its public address (or that a key is generated on save), the last notification (or that none was sent), and a callout after a 403 (the engines could not read the key file), a 422 (the addresses do not match the site address) or a 429 (with the next attempt's time while a retry is queued).
|
||||||
|
|
||||||
|
### HTML sitemap API
|
||||||
|
|
||||||
|
The site's HTML sitemap page (vue-seo-layer) reads two public JSON routes; both list exactly the listed addresses of the XML sitemaps, never an excluded one (D-24), of the locale asked for and those without a locale (`locale` empty: the default locale setting).
|
||||||
|
|
||||||
|
`GET /_sitemap/api/v1/html?locale=pl` answers the overview (`classes.HTMLOverview`):
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{"locale": "pl", "page_size": 150, "groups": [
|
||||||
"/": "2026-06-10T09:12:44+00:00",
|
{"key": "posts", "slug": "posts", "title": "Wpisy", "total": 160, "more": true,
|
||||||
"/about": "2026-05-02T14:31:00+00:00"
|
"entries": [{"title": "Lwia grzywa", "url": "https://www.example.com/blog/lwia-grzywa"}]}
|
||||||
}
|
]}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Priority tiers
|
- Groups come in the order `pages`, `offers`, `services`, `categories`, `posts`, `tags`, `authors`, then the other content types' groups in registration order, then any other group alphabetically. Empty groups are left out.
|
||||||
|
- A group's title in the locale is the content type's HTML sitemap heading, else the Filter's group title, else the type's label.
|
||||||
|
- Entries are alphabetical by title, except a group of articles (newest first) and a group of collections with parents, such as categories, which nests `children` as a tree.
|
||||||
|
- Each group lists its first `html_page_size` entries; `more` is true when it has more.
|
||||||
|
|
||||||
With `enable_priority_tiers` on, the URL's path without trailing slashes (`""` for the homepage) is matched against the rules in `golem15.sitemap.priority_tiers` in order; the first match's setting value is the priority, and a URL no rule matches keeps its item's priority. A rule names a `setting` and either `exact` (a list of paths) or `pattern` (a regular expression in RE2 syntax). The rules are compiled at boot: an unknown setting, a rule with neither or both of `exact` and `pattern`, or a pattern that does not compile fails the boot (`classes.CompileTiers`).
|
`GET /_sitemap/api/v1/html/{group}?locale=pl&page=2` answers one page of a group by its slug (`classes.HTMLGroupPage`): `group`, `key`, `title`, `locale`, `page`, `pages`, `total` and `entries`. The settings' HTML sitemap tab sets whether the routes answer (`html_enabled`, default on), the site's HTML sitemap address per locale (`html_paths`, default `/mapa-strony` for pl and `/sitemap` for en; the layer serves the page there) and the links per page (`html_page_size`, 50 to 500, default 150).
|
||||||
|
|
||||||
The plugin's `config/config.yaml` ships the rules the PHP plugin had in code, so a site configured the same way gets the same priorities. A host replaces the whole list in its own config, for example `config/golem15.yaml`:
|
### Management API and MCP
|
||||||
|
|
||||||
```yaml
|
Each management route resolves the backend administrator from a backend JWT, a personal API token covering `golem15.sitemap.*`, or the MCP dispatch, and requires `golem15.sitemap.access_definitions` (401 without an administrator, 403 without the permission):
|
||||||
sitemap:
|
|
||||||
priority_tiers:
|
|
||||||
- setting: priority_homepage
|
|
||||||
exact: ["", "/en"]
|
|
||||||
- setting: priority_blog
|
|
||||||
pattern: '^/(en/)?articles/[^/]+$'
|
|
||||||
```
|
|
||||||
|
|
||||||
### Hooks
|
| Route | MCP tool | Effect |
|
||||||
|
|-------|----------|--------|
|
||||||
|
| `GET /_sitemap/api/v1/settings` | `sitemap_get_settings` | The settings, the content types (label, include, slug, titles), the index address and files with their counts, the addresses left out by reason, the rebuild state, the IndexNow state (key, key URL, last notification, next attempt) and `news_source_options`. |
|
||||||
|
| `PUT /_sitemap/api/v1/settings` | `sitemap_update_settings` | Changes the fields sent (`api.UpdateSettingsInput`; `types` by content type key) with the settings screen's checks: a refusal is 422 `{"error":"validation_failed","errors":{field:[message]}}` and stores nothing. `html_paths` merges per locale, turning IndexNow on generates its key, `indexnow_new_key` replaces it, and a rebuild is queued. Answers like GET. |
|
||||||
|
| `POST /_sitemap/api/v1/rebuild` | `sitemap_rebuild` | Queues a rebuild now; 202 `{"data":{"queued":true}}`. |
|
||||||
|
|
||||||
`classes.BeforeAddItem` fires through `festival.Bus.UntilHandled` before a URL is counted; a listener that sets `Skip` drops it (the PHP listener returned `false`). `classes.AddItem` fires through `festival.Bus.Fire` after a URL's elements are built; a listener may append escaped child XML to `Extra`. Both carry the definition item and a `classes.ItemInfo` (URL, modification time, written `lastmod`, alternates).
|
The tools run as the backend account linked to the MCP user and are listed only when it has the permission (`sitemap.Plugin.MCP`).
|
||||||
|
|
||||||
|
### Filter
|
||||||
|
|
||||||
|
A plugin that decides which addresses are indexable implements `contract.Filter` and publishes it in its `Register`. It imports the `contract` package only:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func (p *Plugin) Boot(app *backpack.App) error {
|
import "git.golem15.com/golem15/sm-sitemap-plugin/contract"
|
||||||
app.Events.Listen("acme.seo", func(ctx context.Context, e *classes.BeforeAddItem) error {
|
|
||||||
if strings.HasSuffix(e.Info.URL, "/draft") {
|
type noindexFilter struct{}
|
||||||
e.Skip = true
|
|
||||||
|
func (noindexFilter) Decide(ctx context.Context, batch []contract.Candidate) ([]contract.Decision, error) {
|
||||||
|
out := make([]contract.Decision, len(batch))
|
||||||
|
for i, c := range batch {
|
||||||
|
if strings.HasPrefix(c.URL, "/drafts/") {
|
||||||
|
out[i] = contract.Decision{Exclude: true, Reason: contract.ReasonNoindex}
|
||||||
}
|
}
|
||||||
return nil
|
}
|
||||||
})
|
return out, nil
|
||||||
app.Events.Listen("acme.seo", func(ctx context.Context, e *classes.AddItem) error {
|
}
|
||||||
e.Extra = append(e.Extra, "<mobile>"+classes.EscapeText("yes")+"</mobile>")
|
|
||||||
return nil
|
func (noindexFilter) Groups(context.Context) ([]contract.Group, error) { return nil, nil }
|
||||||
})
|
|
||||||
return nil
|
func (p *Plugin) Register(app *backpack.App) error {
|
||||||
|
return app.Publish[contract.Filter](noindexFilter{})
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`Decide` gets one page of records of one content type (or the additional addresses, type key `extra`) and answers one decision per candidate in order. An error or a wrong number of decisions fails the rebuild, and the files stay as they were. Excluded addresses are counted by reason in the settings screen (noindex, canonical, redirect; a type switched off counts as type). An additional address that a content record already lists (the same absolute URL) is left out as `duplicate`, so the files carry it once, with the record's lastmod and alternates; it is not sent to `Decide`.
|
||||||
|
|
||||||
|
### Listing
|
||||||
|
|
||||||
|
The plugin publishes `classes.Listing` as `contract.Listing`:
|
||||||
|
|
||||||
|
- `Settings` answers the site address, the index address, the default locale and the groups with their listed addresses, their slug and their titles (the content type's HTML sitemap heading, else the Filter's group titles);
|
||||||
|
- `Entries` pages a group's listed addresses (`EntriesQuery{Group, Locale, After, Limit}`, 100 by default, at most 1000) with absolute URLs, titles and lastmod, `Next` and `Total`.
|
||||||
|
|
||||||
|
`Settings` also answers the HTML sitemap settings (`HTMLEnabled`, `HTMLPaths` by locale, `HTMLPageSize`) and the IndexNow key file name (`KeyFile`, `<key>.txt`, empty while IndexNow is off) and the content types switched off (`TypesOff`, whose addresses are left out with `ReasonType`), so the SEO plugin and the layer read them without importing the sitemap's internals.
|
||||||
|
|
||||||
|
### Rebuilder
|
||||||
|
|
||||||
|
The plugin also publishes `classes.Listing` as `contract.Rebuilder`. `RequestRebuild` queues one debounced rebuild, the same one a record event queues (a request inside the debounce window joins it), so a plugin whose `Filter` reads data of its own asks for a rebuild when that data changes; the SEO plugin does it when the frontend reports a changed set of noindex paths. A plugin that finds no `contract.Rebuilder` (an older sitemap plugin) leaves the change to the next scheduled rebuild.
|
||||||
|
|
||||||
### Admin
|
### Admin
|
||||||
|
|
||||||
Two entries on the Settings page, category CMS, both requiring `golem15.sitemap.access_definitions` (developer role):
|
The Settings page has one Sitemaps tile (icon `network`, category CMS, permission `golem15.sitemap.access_definitions`). It opens the singleton controller `golem15.sitemap.settings`:
|
||||||
|
|
||||||
- **Sitemap** links to the definitions controller (`golem15.sitemap.definitions`), a singleton form: the server opens the definition with the theme `default`, creating it when absent, and the form has no list, create or delete. Its one field is a repeater on `data` whose rows hold type, reference, URL, URL pattern, priority, change frequency and the nesting checkbox.
|
- **Files:** Site address, Addresses per file and the files table: the index and every file with its address count and newest lastmod, the addresses left out by reason, and a note naming the public index address. Before the first build it says there are no files yet; after a save and until the rebuild ran, that it is rebuilding.
|
||||||
- **Sitemap settings** is the settings form.
|
- **Content types:** per signpost content type, in registration order, a switch labelled with the type's label, the file name (`[a-z0-9-]`, unique, `images` and `news` reserved) and the HTML sitemap heading per locale. The heading loads empty until an editor sets one, so a save that does not touch it stores none and each language's HTML sitemap shows the type's label translated into that language. Stored in `golem15_sitemap_types`.
|
||||||
|
- **Additional addresses:** a repeater of paths (or absolute URLs) with an optional lastmod as `YYYY-MM-DD`. They go into the `pages` group.
|
||||||
|
- **Images and News:** the image sitemap switch, the News sitemap switch, and while it is on the publication name, the News sources (a tag list of `type:` and `category:` values) and the table of the values the site has.
|
||||||
|
- **IndexNow:** the switch, the status partial and, while it is on, "Generate a new key on save".
|
||||||
|
- **HTML sitemap:** the switch, the address per locale (stored as `html_paths` by the plugin's form extension) and the links per page.
|
||||||
|
|
||||||
The WinterCMS forms are adapted to the admin's YAML:
|
The files table lists the image and News files too. A save refuses an invalid site address, a file size outside 1 to 50 000, an address that is not a path or an `http`/`https` URL, a lastmod that is not a date, an invalid or taken file name, a publication name over 255 characters, a News source of another form, an HTML sitemap address that is not a plain path (`models.ValidHTMLPath`) and links per page outside 50 to 500; it generates the IndexNow key when needed and dispatches a rebuild.
|
||||||
|
|
||||||
- The definition form's tab is flattened, and the `SitemapItems` form widget is replaced by a `type: repeater` field on `data`.
|
|
||||||
- `span: none` and `cssClass` become `left` and `right`.
|
|
||||||
- The settings form's nginx hint and Priority Tiers section are field comments and this README; the `trigger` conditions on the tier fields are dropped, so those fields always show and their comments say when they apply.
|
|
||||||
- The tier comments no longer name one site's paths.
|
|
||||||
- The CMS page field and its messages are not ported; the editor's empty-definition action (`empty_confirm`) is not ported.
|
|
||||||
- The form's "View sitemap.xml" subtitle link (`definition.view`) waits for a form schema key in the framework; the phrase exists.
|
|
||||||
|
|
||||||
## API reference
|
## API reference
|
||||||
|
|
||||||
| Identifier | Description |
|
| Identifier | Description |
|
||||||
|------------|-------------|
|
|------------|-------------|
|
||||||
| `sitemap.Plugin` | Compiled plugin; `ID` is `golem15.sitemap`. |
|
| `sitemap.Plugin` | Compiled plugin; `ID` is `golem15.sitemap`, `Requires` is empty. |
|
||||||
| `sitemap.Plugin.Routes` | `GET /sitemap.xml` (throttled, cached) and `GET /sitemap.xsl`. |
|
| `sitemap.Plugin.Register` | Publishes `classes.Listing` as `contract.Listing`. |
|
||||||
| `sitemap.Plugin.Buckets` | Registers the `sitemap-xml` throttle bucket: 60 requests a minute per client IP. |
|
| `sitemap.Plugin.Boot` | Subscribes to `pact.RecordSaved` and `pact.RecordDeleted`. |
|
||||||
| `sitemap.BucketSitemap` | `sitemap-xml`, the throttle bucket of `/sitemap.xml`. |
|
| `sitemap.Plugin.Routes` | The sitemap, key file, HTML sitemap and management routes. |
|
||||||
| `sitemap.CacheConfigKey` | `golem15.sitemap.cache_seconds`, the seconds a generated sitemap is cached. |
|
| `sitemap.Plugin.Buckets`, `sitemap.BucketSitemap`, `sitemap.BucketHTML`, `sitemap.BucketAPI` | The throttle buckets `sitemap-xml` (60 a minute), `sitemap-html` and `sitemap-api` (300 a minute) per client IP. |
|
||||||
| `sitemap.Plugin.Boot` | Compiles the tier rules and starts an empty sitemap cache; a bad rule or a negative `cache_seconds` fails the boot. |
|
| `sitemap.Plugin.Jobs` | The rebuild job (`classes.RebuildKind`, three attempts) and the IndexNow job (`classes.IndexNowKind`, five). |
|
||||||
| `sitemap.Plugin.ConfigFS` | The default `config/config.yaml` (cache time and tier rules). |
|
| `sitemap.Plugin.MCP` | The tools `get_settings`, `update_settings` and `rebuild` (exposed with the prefix `sitemap_`). |
|
||||||
| `sitemap.Plugin.Commands` | Registers `sitemap:import` and `sitemap:import-winter`. |
|
| `sitemap.Plugin.Schedule` | `sitemap:rebuild` daily at 03:00. |
|
||||||
| `sitemap.Plugin.AdminControllers` | The definitions controller. |
|
| `sitemap.Plugin.Commands` | `sitemap:rebuild`, `sitemap:import`, `sitemap:import-winter`. |
|
||||||
| `sitemap.Plugin.Settings` | The Sitemap link and the Sitemap settings form. |
|
| `sitemap.Plugin.ConfigFS` | The default `config/config.yaml`. |
|
||||||
| `sitemap.Plugin.Permissions` | `golem15.sitemap.access_definitions`. |
|
| `sitemap.Plugin.AdminControllers`, `sitemap.Plugin.Settings`, `sitemap.Plugin.Permissions` | The settings singleton, its tile and `golem15.sitemap.access_definitions`. |
|
||||||
| `sitemap.Plugin.LangFS`, `sitemap.Plugin.AdminFS` | Embedded phrasebooks and admin YAML. |
|
| `sitemap.Plugin.AdminActionExtensions` | The Content types tab and the HTML sitemap address on the settings singleton. |
|
||||||
| `sitemap.Plugin.Migrations`, `sitemap.Plugin.Models` | The two migrations and the two models. |
|
| `sitemap.TabFiles`, `sitemap.TabTypes`, `sitemap.TabHTML` | Tab keys of the settings form. |
|
||||||
| `models.Definition` | The definition row; `Items` and `SetItems` read and write its item list. |
|
| `sitemap.Plugin.LangFS`, `sitemap.Plugin.AdminFS` | Embedded phrasebooks, admin YAML and partials. |
|
||||||
| `models.DefinitionTheme` | The fixed theme key `default`. |
|
| `sitemap.Plugin.Migrations`, `sitemap.Plugin.Models` | The migrations and models. |
|
||||||
| `models.DefinitionItem`, `models.DefinitionItems` | One item and the stored list, with the tolerant PHP-shaped decoding. |
|
| `contract.Filter`, `contract.Candidate`, `contract.Decision`, `contract.Group` | The filter other plugins implement. |
|
||||||
| `models.ItemTypeURL` | The built-in item type `url`. |
|
| `contract.ReasonNoindex`, `contract.ReasonCanonical`, `contract.ReasonRedirect`, `contract.ReasonType` | The left-out reasons. |
|
||||||
| `models.Text`, `models.DecodeText` | A text field's value; the tolerant decoding of one stored text value. |
|
| `contract.Listing`, `contract.ListingSettings`, `contract.GroupInfo`, `contract.EntriesQuery`, `contract.Entry`, `contract.EntriesPage` | What the sitemap publishes for other plugins. |
|
||||||
| `models.Settings`, `models.DefaultSettings` | The settings row and its PHP defaults; `Settings.Priority` reads a tier value, `Settings.BeforeValidate` refuses a `frontend_url` outside the accepted form on a save. |
|
| `classes.Rebuild`, `classes.RebuildResult`, `classes.WithAfterSlotRead` | One rebuild of the slot table and what it changed; the test seam called after the rebuild read the slot rows. |
|
||||||
| `models.AllowedFrontendURL` | Whether a value may be the `frontend_url` setting: empty, or an absolute `http`/`https` URL with a host and without whitespace, control characters, `"`, `<`, `>` or `&`. |
|
| `classes.RebuildArgs`, `classes.RebuildKind` | The rebuild job's arguments and kind `golem15.sitemap.rebuild`. |
|
||||||
| `models.PriorityHomepage`, `models.PriorityServices`, `models.PriorityBlog`, `models.PriorityCategories`, `models.PriorityLegal`, `models.PriorityDefaults` | The tier setting keys and their defaults. |
|
| `classes.RequestRebuild`, `classes.DispatchRebuild`, `classes.RequestDebouncedRebuild`, `classes.ClearPending`, `classes.Building` | Dispatching rebuilds and the debounce window. |
|
||||||
| `controllers.DefinitionsControllerID`, `controllers.PermissionAccessDefinitions` | `golem15.sitemap.definitions` and `golem15.sitemap.access_definitions`. |
|
| `classes.RecordSaved`, `classes.RecordDeleted`, `classes.RealChanges`, `classes.Changed` | The record event handling. |
|
||||||
| `classes.Generator` | Writes a definition's sitemap; `Generate`, `Stylesheet`. |
|
| `classes.LastmodIgnore`, `classes.RebuildDelay`, `classes.DefaultLastmodIgnore`, `classes.LastmodIgnoreConfigKey`, `classes.RebuildDelayConfigKey` | The lastmod and debounce config. |
|
||||||
| `classes.Resolver` | What the generator resolves registry items through (`*signpost.Registry`). |
|
| `classes.AssignSlots`, `classes.Slot` | Stable file numbering. |
|
||||||
| `classes.Serialize`, `classes.URLEntry`, `classes.Alternate` | The libxml-format writer and its entries. |
|
| `classes.WriteIndex`, `classes.WriteURLSet`, `classes.IndexFile`, `classes.FileEntry`, `classes.FileAlternate`, `classes.NSSitemap`, `classes.NSXHTML` | The XML writers. |
|
||||||
| `classes.EscapeText`, `classes.EscapeAttr` | libxml's text and attribute escaping. |
|
| `classes.WriteImageURLSet`, `classes.ImageEntry`, `classes.NSImage`, `classes.PageImages`, `classes.MaxImagesPerURL`, `classes.ImagesGroup` | The image sitemap. |
|
||||||
| `classes.URLTo`, `classes.BuildURL`, `classes.URLPath` | Ports of Winter `Url::to`, `Url::buildUrl` and `parse_url(..., PHP_URL_PATH)`. |
|
| `classes.WriteNewsURLSet`, `classes.NewsEntry`, `classes.NewsEntries`, `classes.NSNews`, `classes.NewsFile`, `classes.NewsWindow`, `classes.MaxNewsEntries`, `classes.NewsLanguage`, `classes.NewsPublication`, `classes.NewsSources`, `classes.NewsSource`, `classes.NewsSourceType`, `classes.NewsSourceCategory` | The News sitemap and its sources. |
|
||||||
| `classes.AllowedItemURL` | Whether a url item's address may be stored: a path or an absolute `http`/`https` URL. |
|
| `classes.GenerateKey`, `classes.EnsureKey`, `classes.ValidKey`, `classes.KeyFileName`, `classes.ActiveKey`, `classes.Production`, `classes.SiteURLs` | The IndexNow key and the host filter. |
|
||||||
| `classes.Rewrite`, `classes.BackendURL` | The `frontend_url` rewrite, applied only for a value `models.AllowedFrontendURL` accepts, and the backend URL it replaces. |
|
| `classes.NotifyIndexNow`, `classes.SendIndexNow`, `classes.IndexNowArgs`, `classes.IndexNowKind`, `classes.IndexNowHost`, `classes.IndexNowEndpoint`, `classes.MaxIndexNowURLs`, `classes.IndexNowAttempts` | The IndexNow job. |
|
||||||
| `classes.TiersConfigKey`, `classes.TierConfig`, `classes.TierRule`, `classes.Tiers`, `classes.CompileTiers`, `classes.LoadTiers` | The tier rules. |
|
| `classes.IndexNowStatus`, `classes.LoadIndexNowStatus`, `classes.IndexNowRetryAt` | The IndexNow state of the settings screen and the API. |
|
||||||
| `classes.Manifest`, `classes.LoadManifest`, `classes.ManifestMaxBytes` | The updates manifest. |
|
| `classes.HTMLSitemap`, `classes.HTMLOverview`, `classes.HTMLGroup`, `classes.HTMLGroupPage`, `classes.HTMLEntry` | The HTML sitemap API's groups, order, tree and paging. |
|
||||||
| `classes.BeforeAddItem`, `classes.AddItem`, `classes.ItemInfo` | The hooks. |
|
| `classes.MergeHTMLPaths`, `classes.StoreHTMLPaths` | The HTML sitemap addresses per locale. |
|
||||||
| `classes.MaxURLs` | 50000. |
|
| `classes.SitemapFiles`, `classes.SitemapFile`, `classes.LeftOut` | The files of the index and the left-out counts. |
|
||||||
| `console.Import`, `console.ImportFile` | `sitemap:import`. |
|
| `classes.SaveTypeSettings`, `classes.TypeFieldBase` | Writing the content type settings (the form and the API). |
|
||||||
| `console.ImportWinter`, `console.ImportWinterFiles`, `console.WinterOptions`, `console.WinterReport` | `sitemap:import-winter`. |
|
| `classes.FileName`, `classes.ParseFileName`, `classes.ValidSlug`, `classes.DefaultSlug`, `classes.ReservedSlugs` | File and group names. |
|
||||||
|
| `classes.SiteURL`, `classes.SiteURLConfigKey`, `classes.Absolute`, `classes.LoadSettings` | The site address and the settings row. |
|
||||||
|
| `classes.TypeConfig`, `classes.EffectiveType`, `classes.LoadTypeSettings` | The per-type settings. |
|
||||||
|
| `classes.Listing` | The `contract.Listing` implementation. |
|
||||||
|
| `classes.ExtraRecordID` | The record id of an additional address. |
|
||||||
|
| `models.URL`, `models.Alternate`, `models.Ref` | A row of the slot table, an hreflang alternate and a parent reference. |
|
||||||
|
| `models.ExtraTypeKey`, `models.ExtraGroup`, `models.ReasonDeleted`, `models.ReasonUnpublished`, `models.ReasonDuplicate` | Additional addresses, the holes' reasons and the reason of an additional address a content record already lists. |
|
||||||
|
| `models.Settings`, `models.DefaultSettings`, `models.ExtraURL`, `models.DefaultFileSize`, `models.MaxFileSize` | The settings row; `Validate` and `Problems` are its save checks. |
|
||||||
|
| `models.DefaultHTMLPageSize`, `models.MinHTMLPageSize`, `models.MaxHTMLPageSize`, `models.DefaultHTMLPaths`, `models.ValidHTMLPath`, `models.HTMLPathProblem` | The HTML sitemap settings and their checks. |
|
||||||
|
| `models.ValidNewsSource`, `models.NewsSourceType`, `models.NewsSourceCategory`, `models.MaxNewsPublication` | The News settings' checks. |
|
||||||
|
| `models.TypeSetting` | A row of `golem15_sitemap_types`. |
|
||||||
|
| `models.AllowedFrontendURL`, `models.AllowedAddress`, `models.ParseDate`, `models.ValidDate` | The value checks. |
|
||||||
|
| `models.LegacyItem`, `models.ParseLegacyItems`, `models.ParseLegacyItem`, `models.LegacyEntries`, `models.LegacyJSON`, `models.DecodeText`, `models.Text` | Reading Phase 17 and WinterCMS definition data. |
|
||||||
|
| `models.ConvertLegacyItems`, `models.DroppedItem` | The url items of a Phase 17 definition as additional addresses, and the items that could not be copied with their reasons. |
|
||||||
|
| `controllers.SettingsControllerID`, `controllers.PermissionAccessDefinitions` | `golem15.sitemap.settings` and `golem15.sitemap.access_definitions`. |
|
||||||
|
| `console.Rebuild`, `console.Import`, `console.ImportFile`, `console.ImportWinter`, `console.ImportWinterFiles`, `console.WinterOptions`, `console.WinterReport` | The commands. |
|
||||||
|
| `api.KeyFile`, `api.KeyFilePattern` | The IndexNow key file handler (package `controllers/api`). |
|
||||||
|
| `api.HTMLOverview`, `api.HTMLGroup`, `api.GroupPattern` | The HTML sitemap API handlers. |
|
||||||
|
| `api.ShowSettings`, `api.UpdateSettings`, `api.Rebuild`, `api.UpdateSettingsInput`, `api.TypeInput`, `api.PermissionManage`, `api.ProblemsError` | The management API. |
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
`config/config.yaml`, read as `golem15.sitemap.<key>`:
|
||||||
|
|
||||||
|
| Key | Default | Meaning |
|
||||||
|
|-----|---------|---------|
|
||||||
|
| `site_url` | unset | The site address when the setting is empty (before `app.url`). |
|
||||||
|
| `lastmod_ignore` | `[updated_at, created_at, views, sort_order]` | Attributes whose change does not move lastmod. A host replaces the whole list. |
|
||||||
|
| `rebuild_delay_seconds` | `60` | The delay of the rebuild a record event queues; events within it share one rebuild. |
|
||||||
|
|
||||||
|
IndexNow has no config key: the endpoint is fixed (`https://api.indexnow.org/indexnow`, the only host the plugin's outbound client may reach), the key lives in the settings, and requests are sent only in the `production` environment. The outbound client's limits fall back to `fetchguard`'s `http.fetch.*` keys, with a 10 s timeout set by the plugin.
|
||||||
|
|
||||||
## CLI commands
|
## CLI commands
|
||||||
|
|
||||||
| Command | Arguments and flags | Effect |
|
| Command | Arguments and flags | Effect |
|
||||||
|---------|---------------------|--------|
|
|---------|---------------------|--------|
|
||||||
| `sitemap:import` | `FILE`, `--theme`, `--append` | The PHP `ImportCommand`: reads a JSON array of `{url, changefreq, priority}` entries (`monthly` and `0.5` by default). Without `--append` the definition keeps its non-URL items first and the imported URLs replace its URL items; with it the URLs follow every existing item. The definition is always `default`; a `--theme` other than `default` is reported. An entry whose URL `classes.AllowedItemURL` refuses stops the import. Ends with `Imported N URLs into sitemap definition for theme 'default'.` |
|
| `sitemap:rebuild` | `--queue` | Rebuilds the files in the process and prints `Rebuilt the sitemaps: N addresses in N files (N added, N changed, N removed).`; with `--queue` dispatches the rebuild job instead. Scheduled daily at 03:00. |
|
||||||
| `sitemap:import-winter` | `--definitions FILE`, `--settings FILE`, `--theme`, `--map old=new` (repeatable), `--page-url reference=/path` (repeatable), `--force`, `--dry-run` | Copies a WinterCMS export into the definition and the settings row. URL items are kept; static and CMS page items are dropped unless `--page-url` names the URL of their reference (for example `--page-url blog=/blog` copies the CMS page item `blog` as a url item `/blog`); `--map` renames types first (for example `--map blog-post=journal-post`); an item of an unknown type, or whose reference is not among its type's current references, is dropped; a url item whose URL `classes.AllowedItemURL` refuses is dropped, and so is a page item whose `--page-url` it refuses; a `urlPattern` that is not a path is cleared. Every dropped, remapped or cleared item and every dropped `cmsPage` is printed. A definition that already has items is refused without `--force`; `--dry-run` writes nothing. Settings missing from the export take the defaults; a `frontend_url` which `models.AllowedFrontendURL` refuses stops the import before anything is written, also with `--dry-run`. `--theme` picks a definition when the export holds several. Ends with `Definition copied: …` and `Settings copied.` for the parts it wrote. |
|
| `sitemap:import` | `FILE`, `--append`, `--theme` | Reads a JSON array of `{url, lastmod}` entries into the additional addresses (replacing them; `--append` adds and skips listed ones). `changefreq` and `priority` are ignored, `--theme` is accepted and does nothing. One bad entry stops the import. |
|
||||||
|
| `sitemap:import-winter` | `--definitions FILE`, `--settings FILE`, `--theme`, `--map old=new` (repeatable), `--page-url reference=/path` (repeatable), `--force`, `--dry-run` | Copies a WinterCMS export: url items become additional addresses (`--page-url` turns a static or CMS page item into one, `--map` renames types first), every other item is dropped and listed; `frontend_url` becomes the site address and `frontend_default_locale` the default locale, the PHP-parity keys are reported as ignored. Stored addresses are replaced only with `--force`; `--dry-run` writes nothing; an unsafe `frontend_url` stops the import. |
|
||||||
|
|
||||||
Both commands open the database themselves when the application has not published one. `./bin/acme help <command>` shows each command's long help and examples. The plugin logs through the component `sitemap` (`log.components.sitemap` in `config/log.yaml`).
|
The commands open the database themselves when the application has not published one. `./bin/acme help <command>` shows each command's long help and examples. The plugin logs through the component `sitemap` (`log.components.sitemap` in `config/log.yaml`).
|
||||||
|
|
||||||
```sh
|
The WinterCMS export runs on the WinterCMS database with the read-only scripts in `scripts/`:
|
||||||
./bin/acme sitemap:import urls.json --append
|
|
||||||
```
|
|
||||||
|
|
||||||
The export runs on the WinterCMS database with the read-only scripts in `scripts/`:
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
mysql -N -B --raw <database> < scripts/winter-export-definitions.sql > sitemap-definitions.jsonl
|
mysql -N -B --raw <database> < scripts/winter-export-definitions.sql > sitemap-definitions.jsonl
|
||||||
mysql -N -B --raw <database> < scripts/winter-export-settings.sql > sitemap-settings.json
|
mysql -N -B --raw <database> < scripts/winter-export-settings.sql > sitemap-settings.json
|
||||||
./bin/acme sitemap:import-winter --definitions sitemap-definitions.jsonl --settings sitemap-settings.json --dry-run
|
./bin/acme sitemap:import-winter --definitions sitemap-definitions.jsonl --settings sitemap-settings.json --dry-run
|
||||||
./bin/acme sitemap:import-winter --definitions sitemap-definitions.jsonl --settings sitemap-settings.json
|
./bin/acme sitemap:import-winter --definitions sitemap-definitions.jsonl --settings sitemap-settings.json
|
||||||
|
./bin/acme sitemap:rebuild
|
||||||
```
|
```
|
||||||
|
|
||||||
## Dependencies
|
## Dependencies
|
||||||
|
|
||||||
- SummerCMS v0.4.0 modules: backpack, bonfire, cabana, compass, diary, festival, lagoon, pact, party, signpost, surf; bouncer in tests. cabana is a regular dependency: `models` and `controllers` return its validation error.
|
- SummerCMS v0.6.1 modules: backpack, bonfire, cabana, compass, conga, diary, fetchguard, lagoon, pact, party, phrasebook, signpost, surf, towel, wire; bouncer, kiosk and pier in tests.
|
||||||
- Third-party: `gorm.io/gorm`, `github.com/go-gormigrate/gormigrate/v2`. Test-only: `github.com/testcontainers/testcontainers-go`, `github.com/jackc/pgx/v5`.
|
- Third-party: `gorm.io/gorm`, `github.com/go-gormigrate/gormigrate/v2`, `github.com/goccy/go-yaml`. Test-only: `github.com/testcontainers/testcontainers-go`, `github.com/jackc/pgx/v5`.
|
||||||
|
|
||||||
## Testing
|
## Testing
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
go test -short ./... # goldens and config checks, no Docker
|
go test -short ./... # unit tests, no Docker
|
||||||
go test ./... # also the Postgres smoke tests
|
go test ./... # also the Postgres tests
|
||||||
```
|
```
|
||||||
|
|
||||||
`TestSitemapGolden` (`classes`) feeds `testdata/tracer.json`, `urlto.json` and `full.json` through the Go port and compares bytes with the goldens; it also checks the 50000 URL cap. `TestSitemapTiersConfig` checks the tier rule refusals, a host's replacement of the rule list and the manifest's fail-safe reads. `TestRewriteUnsafeFrontendURL` (`classes`), `TestAllowedFrontendURL` and `TestSettingsBeforeValidate` (`models`) and `TestWinterSettingsFrontendURL` (`console`) are the Docker-free checks of the `frontend_url` rules: the accepted form, the rewrite that is not applied for any other value, the save hook and the import refusal. The Postgres smokes (`TestSitemapTracer`, `TestSitemapImportSmoke`, `TestSitemapAdminSmoke`, `TestImportWinter`, `TestSitemapCacheAndThrottle`) boot the plugin with a test content plugin and drive the routes, the import commands and the admin API; they cover the 422 of a refused `frontend_url` save and a value stored straight in the row, which the sitemap does not apply. `TestCommandsDocumented` (root package, Docker-free) logs, without failing, each command whose help lacks a description, long help, examples or an option description (`bonfire.CheckDocs`).
|
Docker-free: `TestAssignSlots` and `TestRealChanges` (`classes`), `TestAllowedFrontendURL` and `TestSettingsValidate` (`models`), `TestWinterSettingsFrontendURL` (`console`), `TestSiteURLPrecedence`, `TestFileNames`, `TestScheduleAndJobs`, `TestCommandsDocumented` and `TestPluginManifest` (root).
|
||||||
|
|
||||||
The goldens are generated from the PHP plugin's generation code and the vendored Winter URL generator of any WinterCMS application, and committed, so CI needs no PHP:
|
The Postgres tests boot the plugin with a fake content plugin (two content types over an in-memory store), a fake blog plugin (an article type and a collection type) and, for the Filter, a fake plugin that publishes one: `TestSitemapIndex` (the index and files after a rebuild job, drafts absent, escaping, 404s), `TestStableNumbering`, `TestLastmod`, `TestDebouncedRebuild`, `TestHreflangAlternates`, `TestFilterExcludes`, `TestNoFilter`, `TestListing`, `TestSettingsSingleton` (the admin API, its refusals and the files partial), `TestMigrateDefinitions`, `TestImportWinter`, `TestImportFile`, `TestRebuildCommand`, `TestImageSitemap`, `TestNewsSitemap`, `TestIndexNow` (in production, against a fake engine through `fetchguard.WithTransport`), `TestIndexNowStaging`, `TestHTMLGroups` and `TestSitemapTools` (the management API, an MCP dispatch and pier compiling the tools).
|
||||||
|
|
||||||
```sh
|
|
||||||
WINTER_VENDOR=/path/to/winter-app/vendor php tests/php/gen-goldens.php classes/testdata/full.json classes/testdata/full.golden
|
|
||||||
```
|
|
||||||
|
|||||||
51
admin.go
51
admin.go
@@ -5,29 +5,28 @@ import (
|
|||||||
"io/fs"
|
"io/fs"
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/controllers"
|
"git.golem15.com/golem15/sm-sitemap-plugin/controllers"
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
"git.golem15.com/golem15/summercms/modules/pact"
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
)
|
)
|
||||||
|
|
||||||
// adminFS holds the admin YAML file by file: the controllers directory also
|
// adminFS holds the admin YAML and partial templates by pattern (the
|
||||||
// holds Go sources.
|
// controllers directory also holds Go sources), so a new screen or partial
|
||||||
|
// needs no edit here.
|
||||||
//
|
//
|
||||||
//go:embed controllers/definitions/config_form.yaml models/definition/fields.yaml models/settings/fields.yaml
|
//go:embed controllers/*/*.yaml controllers/*/_*.htm models/*/*.yaml
|
||||||
var adminFS embed.FS
|
var adminFS embed.FS
|
||||||
|
|
||||||
//go:embed lang
|
//go:embed lang
|
||||||
var langFS embed.FS
|
var langFS embed.FS
|
||||||
|
|
||||||
// AdminFS serves the admin YAML.
|
// AdminFS serves the admin YAML and partials.
|
||||||
func (p *Plugin) AdminFS() fs.FS { return adminFS }
|
func (p *Plugin) AdminFS() fs.FS { return adminFS }
|
||||||
|
|
||||||
// LangFS is the embedded English and Polish phrasebooks.
|
// LangFS is the embedded English and Polish phrasebooks.
|
||||||
func (p *Plugin) LangFS() fs.FS { return langFS }
|
func (p *Plugin) LangFS() fs.FS { return langFS }
|
||||||
|
|
||||||
// AdminControllers hands the controllers a lazy accessor of the booted app,
|
// AdminControllers hands the controllers a lazy accessor of the booted app,
|
||||||
// so they read the database and the menu item type registry at request
|
// so they read the database and the content type registry at request time.
|
||||||
// time.
|
|
||||||
func (p *Plugin) AdminControllers() []pact.AdminController {
|
func (p *Plugin) AdminControllers() []pact.AdminController {
|
||||||
return controllers.AdminControllers(func() *backpack.App {
|
return controllers.AdminControllers(func() *backpack.App {
|
||||||
if p == nil {
|
if p == nil {
|
||||||
@@ -37,31 +36,21 @@ func (p *Plugin) AdminControllers() []pact.AdminController {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Settings registers the two PHP settings entries in the CMS category: the
|
// Settings registers the one sitemap settings tile (UI-SPEC C26): a link to
|
||||||
// sitemap definition (a link to the singleton definitions controller) and
|
// the settings singleton controller in the CMS category, behind
|
||||||
// the sitemap settings form. Both require golem15.sitemap.access_definitions.
|
// golem15.sitemap.access_definitions. It replaces the Phase 17 definitions
|
||||||
|
// and settings tiles (D-32).
|
||||||
func (p *Plugin) Settings() []pact.SettingsItem {
|
func (p *Plugin) Settings() []pact.SettingsItem {
|
||||||
return []pact.SettingsItem{
|
return []pact.SettingsItem{{
|
||||||
{
|
Code: "sitemap",
|
||||||
Code: "sitemap",
|
Label: "golem15.sitemap::lang.settings.label",
|
||||||
Label: "golem15.sitemap::lang.plugin.name",
|
Description: "golem15.sitemap::lang.settings.description",
|
||||||
Description: "golem15.sitemap::lang.plugin.description",
|
Category: "golem15.sitemap::lang.settings.category",
|
||||||
Category: "golem15.sitemap::lang.settings.category",
|
Icon: "network",
|
||||||
Icon: "network",
|
Keywords: []string{"sitemap", "sitemap.xml", "lastmod", "hreflang"},
|
||||||
Permissions: []string{controllers.PermissionAccessDefinitions},
|
Permissions: []string{controllers.PermissionAccessDefinitions},
|
||||||
Controller: controllers.DefinitionsControllerID,
|
Controller: controllers.SettingsControllerID,
|
||||||
},
|
}}
|
||||||
{
|
|
||||||
Code: "sitemap_settings",
|
|
||||||
Label: "golem15.sitemap::lang.settings.label",
|
|
||||||
Description: "golem15.sitemap::lang.settings.description",
|
|
||||||
Category: "golem15.sitemap::lang.settings.category",
|
|
||||||
Icon: "settings",
|
|
||||||
Permissions: []string{controllers.PermissionAccessDefinitions},
|
|
||||||
Form: "models/settings/fields.yaml",
|
|
||||||
NewModel: func() any { return &models.Settings{} },
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|||||||
@@ -1,261 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<xsl:stylesheet
|
|
||||||
version="2.0"
|
|
||||||
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
|
|
||||||
xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9"
|
|
||||||
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
|
|
||||||
xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"
|
|
||||||
xmlns:xhtml="http://www.w3.org/1999/xhtml">
|
|
||||||
|
|
||||||
<xsl:output method="html" indent="yes" encoding="UTF-8"/>
|
|
||||||
|
|
||||||
<xsl:template match="/">
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<title>
|
|
||||||
Sitemap
|
|
||||||
<xsl:if test="sitemap:sitemapindex">Index</xsl:if>
|
|
||||||
</title>
|
|
||||||
<link rel="stylesheet" href="https://unpkg.com/tachyons@4.6.1/css/tachyons.min.css"/>
|
|
||||||
</head>
|
|
||||||
<body class="ph3 pb3 mid-gray">
|
|
||||||
<header class="pv4 center">
|
|
||||||
<div class="flex items-center">
|
|
||||||
<h1 class="ma0 mr2 f2 blue">Sitemap</h1>
|
|
||||||
<xsl:if test="sitemap:sitemapindex">
|
|
||||||
<span class="dib mr2 ph3 pv1 f6 normal mid-gray bg-light-blue br-pill">Index</span>
|
|
||||||
</xsl:if>
|
|
||||||
<xsl:if test="sitemap:urlset/sitemap:url/image:image">
|
|
||||||
<span class="dib mr2 ph3 pv1 f6 normal mid-gray bg-light-blue br-pill">Images</span>
|
|
||||||
</xsl:if>
|
|
||||||
<xsl:if test="sitemap:urlset/sitemap:url/video:video">
|
|
||||||
<span class="dib mr2 ph3 pv1 f6 normal mid-gray bg-light-blue br-pill">Video</span>
|
|
||||||
</xsl:if>
|
|
||||||
<xsl:if test="sitemap:urlset/sitemap:url/xhtml:link">
|
|
||||||
<span class="dib mr2 ph3 pv1 f6 normal mid-gray bg-light-blue br-pill">Xhtml</span>
|
|
||||||
</xsl:if>
|
|
||||||
</div>
|
|
||||||
<h2 class="ma0 mt4 f4 normal">
|
|
||||||
<xsl:choose>
|
|
||||||
<xsl:when test="sitemap:sitemapindex">
|
|
||||||
This index contains
|
|
||||||
<strong class="blue"><xsl:value-of select="count(sitemap:sitemapindex/sitemap:sitemap)"/></strong>
|
|
||||||
sitemaps.
|
|
||||||
</xsl:when>
|
|
||||||
<xsl:otherwise>
|
|
||||||
This index contains
|
|
||||||
<strong class="blue"><xsl:value-of select="count(sitemap:urlset/sitemap:url)"/></strong>
|
|
||||||
URLs.
|
|
||||||
</xsl:otherwise>
|
|
||||||
</xsl:choose>
|
|
||||||
</h2>
|
|
||||||
<p>
|
|
||||||
This is an XML sitemap, meant for consumption by search engines.
|
|
||||||
You can find more information about XML sitemaps on <a href="https://sitemaps.org" class="link blue">sitemaps.org</a>.
|
|
||||||
</p>
|
|
||||||
</header>
|
|
||||||
|
|
||||||
<xsl:apply-templates/>
|
|
||||||
|
|
||||||
<footer class="center pv4 tc">
|
|
||||||
</footer>
|
|
||||||
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
</xsl:template>
|
|
||||||
|
|
||||||
|
|
||||||
<xsl:template match="sitemap:sitemapindex">
|
|
||||||
<div class="center">
|
|
||||||
<div class="overflow-auto">
|
|
||||||
<table class="w-100 f6 b--silver ba bw1" cellspacing="0">
|
|
||||||
<thead class="bg-silver">
|
|
||||||
<tr>
|
|
||||||
<th class="pa3 fw6 tl dark-gray" style="width:60px"></th>
|
|
||||||
<th class="pa3 fw6 tl dark-gray">URL</th>
|
|
||||||
<th class="pa3 fw6 tr dark-gray" style="width:200px">Last Modified</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody class="lh-copy bg-near-white">
|
|
||||||
<xsl:for-each select="sitemap:sitemap">
|
|
||||||
<tr class="hover-bg-white">
|
|
||||||
<xsl:variable name="loc">
|
|
||||||
<xsl:value-of select="sitemap:loc"/>
|
|
||||||
</xsl:variable>
|
|
||||||
<xsl:variable name="pno">
|
|
||||||
<xsl:value-of select="position()"/>
|
|
||||||
</xsl:variable>
|
|
||||||
<td class="pa3 tc b bb b--silver">
|
|
||||||
<xsl:value-of select="$pno"/>
|
|
||||||
</td>
|
|
||||||
<td class="pa3 b bb b--silver">
|
|
||||||
<a href="{$loc}" class="link blue">
|
|
||||||
<xsl:value-of select="sitemap:loc"/>
|
|
||||||
</a>
|
|
||||||
</td>
|
|
||||||
<xsl:if test="sitemap:lastmod">
|
|
||||||
<td class="pa3 tr bb b--silver">
|
|
||||||
<xsl:value-of select="concat(substring(sitemap:lastmod, 0, 11), concat(' ', substring(sitemap:lastmod, 12, 5)), concat(' ', substring(sitemap:lastmod, 20, 6)))"/>
|
|
||||||
</td>
|
|
||||||
</xsl:if>
|
|
||||||
<xsl:apply-templates/>
|
|
||||||
</tr>
|
|
||||||
</xsl:for-each>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</xsl:template>
|
|
||||||
|
|
||||||
<xsl:template match="sitemap:urlset">
|
|
||||||
<div class="center">
|
|
||||||
<div class="overflow-auto">
|
|
||||||
<table class="w-100 f6 b--silver ba bw1" cellspacing="0">
|
|
||||||
<thead class="bg-silver">
|
|
||||||
<tr>
|
|
||||||
<th class="pa3 fw6 tl dark-gray" style="width:60px"></th>
|
|
||||||
<th class="pa3 fw6 tl dark-gray">URL</th>
|
|
||||||
<xsl:if test="sitemap:url/sitemap:changefreq">
|
|
||||||
<th class="pa3 fw6 tr dark-gray" style="width:130px">Change Freq.</th>
|
|
||||||
</xsl:if>
|
|
||||||
<xsl:if test="sitemap:url/sitemap:priority">
|
|
||||||
<th class="pa3 fw6 tr dark-gray" style="width:90px">Priority</th>
|
|
||||||
</xsl:if>
|
|
||||||
<xsl:if test="sitemap:url/sitemap:lastmod">
|
|
||||||
<th class="pa3 fw6 tr dark-gray" style="width:200px">Last Modified</th>
|
|
||||||
</xsl:if>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody class="lh-copy bg-near-white">
|
|
||||||
<xsl:for-each select="sitemap:url">
|
|
||||||
<tr class="hover-bg-white">
|
|
||||||
<xsl:variable name="loc">
|
|
||||||
<xsl:value-of select="sitemap:loc"/>
|
|
||||||
</xsl:variable>
|
|
||||||
<xsl:variable name="pno">
|
|
||||||
<xsl:value-of select="position()"/>
|
|
||||||
</xsl:variable>
|
|
||||||
<td class="pa3 tc b bb b--silver">
|
|
||||||
<xsl:value-of select="$pno"/>
|
|
||||||
</td>
|
|
||||||
<td class="pa3 bb b--silver">
|
|
||||||
<p>
|
|
||||||
<a href="{$loc}" class="link blue">
|
|
||||||
<xsl:value-of select="sitemap:loc"/>
|
|
||||||
</a>
|
|
||||||
</p>
|
|
||||||
<xsl:apply-templates select="xhtml:*"/>
|
|
||||||
<xsl:apply-templates select="image:*"/>
|
|
||||||
<xsl:apply-templates select="video:*"/>
|
|
||||||
</td>
|
|
||||||
<xsl:apply-templates select="sitemap:changefreq"/>
|
|
||||||
<xsl:apply-templates select="sitemap:priority"/>
|
|
||||||
<xsl:if test="sitemap:lastmod">
|
|
||||||
<td class="pa3 tr bb b--silver">
|
|
||||||
<xsl:value-of select="concat(substring(sitemap:lastmod, 0, 11), concat(' ', substring(sitemap:lastmod, 12, 5)), concat(' ', substring(sitemap:lastmod, 20, 6)))"/>
|
|
||||||
</td>
|
|
||||||
</xsl:if>
|
|
||||||
</tr>
|
|
||||||
</xsl:for-each>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</xsl:template>
|
|
||||||
|
|
||||||
<xsl:template match="sitemap:loc|sitemap:lastmod|image:loc|image:caption|video:*">
|
|
||||||
</xsl:template>
|
|
||||||
|
|
||||||
<xsl:template match="sitemap:changefreq|sitemap:priority">
|
|
||||||
<td class="pa3 tr bb b--silver">
|
|
||||||
<xsl:apply-templates/>
|
|
||||||
</td>
|
|
||||||
</xsl:template>
|
|
||||||
|
|
||||||
<xsl:template match="xhtml:link">
|
|
||||||
<xsl:variable name="altloc">
|
|
||||||
<xsl:value-of select="@href"/>
|
|
||||||
</xsl:variable>
|
|
||||||
<p>
|
|
||||||
<xsl:if test="@rel">
|
|
||||||
<small class="dib mr2 ph2 pv1 tracked lh-solid white bg-silver br-pill">
|
|
||||||
<xsl:value-of select="@rel"/>
|
|
||||||
</small>
|
|
||||||
</xsl:if>
|
|
||||||
|
|
||||||
<xsl:if test="@hreflang">
|
|
||||||
<small class="dib mr2 ph1 pv1 tracked lh-solid white bg-silver br-pill">
|
|
||||||
<xsl:value-of select="@hreflang"/>
|
|
||||||
</small>
|
|
||||||
</xsl:if>
|
|
||||||
|
|
||||||
<a href="{$altloc}" class="mr2 link blue">
|
|
||||||
<xsl:value-of select="@href"/>
|
|
||||||
</a>
|
|
||||||
|
|
||||||
<xsl:if test="@media">
|
|
||||||
<small class="dib mr2 ph2 pv1 tracked lh-solid white bg-silver br-pill">
|
|
||||||
<xsl:value-of select="@media"/>
|
|
||||||
</small>
|
|
||||||
</xsl:if>
|
|
||||||
</p>
|
|
||||||
<xsl:apply-templates/>
|
|
||||||
</xsl:template>
|
|
||||||
|
|
||||||
<xsl:template match="image:image">
|
|
||||||
<xsl:variable name="loc">
|
|
||||||
<xsl:value-of select="image:loc"/>
|
|
||||||
</xsl:variable>
|
|
||||||
<p>
|
|
||||||
<strong>Image: </strong>
|
|
||||||
<a href="{$loc}" class="mr2 link blue">
|
|
||||||
<xsl:value-of select="image:loc"/>
|
|
||||||
</a>
|
|
||||||
<xsl:if test="image:caption">
|
|
||||||
<span class="i gray">
|
|
||||||
<xsl:value-of select="image:caption"/>
|
|
||||||
</span>
|
|
||||||
</xsl:if>
|
|
||||||
<xsl:apply-templates/>
|
|
||||||
</p>
|
|
||||||
</xsl:template>
|
|
||||||
|
|
||||||
<xsl:template match="video:video">
|
|
||||||
<xsl:variable name="loc">
|
|
||||||
<xsl:choose>
|
|
||||||
<xsl:when test="video:player_loc != ''">
|
|
||||||
<xsl:value-of select="video:player_loc"/>
|
|
||||||
</xsl:when>
|
|
||||||
<xsl:otherwise>
|
|
||||||
<xsl:value-of select="video:content_loc"/>
|
|
||||||
</xsl:otherwise>
|
|
||||||
</xsl:choose>
|
|
||||||
</xsl:variable>
|
|
||||||
<xsl:variable name="thumb_loc">
|
|
||||||
<xsl:value-of select="video:thumbnail_loc"/>
|
|
||||||
</xsl:variable>
|
|
||||||
<p>
|
|
||||||
<strong>Video: </strong>
|
|
||||||
<a href="{$loc}" class="mr2 link blue">
|
|
||||||
<xsl:choose>
|
|
||||||
<xsl:when test="video:player_loc != ''">
|
|
||||||
<xsl:value-of select="video:player_loc"/>
|
|
||||||
</xsl:when>
|
|
||||||
<xsl:otherwise>
|
|
||||||
<xsl:value-of select="video:content_loc"/>
|
|
||||||
</xsl:otherwise>
|
|
||||||
</xsl:choose>
|
|
||||||
</a>
|
|
||||||
<a href="{$thumb_loc}" class="dib mr2 ph2 pv1 tracked lh-solid link white bg-silver hover-bg-blue br-pill">
|
|
||||||
thumb
|
|
||||||
</a>
|
|
||||||
<xsl:if test="video:title">
|
|
||||||
<span class="i gray">
|
|
||||||
<xsl:value-of select="video:title"/>
|
|
||||||
</span>
|
|
||||||
</xsl:if>
|
|
||||||
<xsl:apply-templates/>
|
|
||||||
</p>
|
|
||||||
</xsl:template>
|
|
||||||
|
|
||||||
</xsl:stylesheet>
|
|
||||||
66
classes/dispatch.go
Normal file
66
classes/dispatch.go
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/conga"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RebuildLabelKey is the phrase key of the rebuild job's label.
|
||||||
|
const RebuildLabelKey = "golem15.sitemap::lang.jobs.rebuild"
|
||||||
|
|
||||||
|
// buildingWindow bounds the "rebuilding now" state of the settings screen:
|
||||||
|
// a request older than this without a finished rebuild (no worker runs)
|
||||||
|
// is no longer shown as running.
|
||||||
|
const buildingWindow = time.Hour
|
||||||
|
|
||||||
|
// RequestRebuild records that a rebuild was asked for (the settings
|
||||||
|
// screen's files.building state) and dispatches the rebuild job once db's
|
||||||
|
// transaction commits, so the job reads what the transaction wrote. A
|
||||||
|
// queue error is logged and never fails the caller.
|
||||||
|
func RequestRebuild(ctx context.Context, app *backpack.App, db *gorm.DB) error {
|
||||||
|
if app == nil || db == nil {
|
||||||
|
return ErrNoDatabase
|
||||||
|
}
|
||||||
|
if err := db.Exec(`UPDATE golem15_sitemap_settings SET rebuild_requested_at = ? WHERE id = 1`, time.Now().UTC()).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
lagoon.AfterCommit(ctx, db, func(ctx context.Context, _ *gorm.DB) {
|
||||||
|
if _, err := DispatchRebuild(ctx, app); err != nil {
|
||||||
|
pluginLog.Warn("golem15.sitemap: queue rebuild", "error", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DispatchRebuild dispatches the rebuild job now, with a summer_jobs row
|
||||||
|
// labelled in the request locale, and returns the row id.
|
||||||
|
func DispatchRebuild(ctx context.Context, app *backpack.App) (uint, error) {
|
||||||
|
db, ok := app.Lookup[*gorm.DB]()
|
||||||
|
if !ok || db == nil {
|
||||||
|
return 0, ErrNoDatabase
|
||||||
|
}
|
||||||
|
m, err := conga.From(app)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
label := RebuildLabelKey
|
||||||
|
if tr, ok := app.Lookup[*phrasebook.Translator](); ok && tr != nil {
|
||||||
|
label = tr.Get(ctx, RebuildLabelKey, nil)
|
||||||
|
}
|
||||||
|
return m.Dispatch(ctx, db.WithContext(ctx), RebuildArgs{}, conga.DispatchOpts{Label: label})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Building reports whether a rebuild asked for from the admin has not
|
||||||
|
// finished yet (within buildingWindow).
|
||||||
|
func Building(requested, built *time.Time, now time.Time) bool {
|
||||||
|
if requested == nil || now.Sub(*requested) > buildingWindow {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return built == nil || built.Before(*requested)
|
||||||
|
}
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
package classes
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ItemInfo is what the sitemap knows about one URL it is about to write, the
|
|
||||||
// PHP $itemInfo array: URL (before the final Url::to in BeforeAddItem, the
|
|
||||||
// written loc in AddItem), MTime, the record's modification time when the
|
|
||||||
// item has one, Lastmod, the written lastmod ("" when omitted), and the
|
|
||||||
// hreflang Alternates.
|
|
||||||
type ItemInfo struct {
|
|
||||||
URL string
|
|
||||||
MTime *time.Time
|
|
||||||
Lastmod string
|
|
||||||
Alternates []Alternate
|
|
||||||
}
|
|
||||||
|
|
||||||
// BeforeAddItem is the typed successor of the PHP event
|
|
||||||
// golem15.sitemap.beforeAddItem. The generator fires it with
|
|
||||||
// festival.Bus.UntilHandled for every URL before it is counted and written;
|
|
||||||
// a listener that sets Skip drops the URL (PHP: a listener returned false).
|
|
||||||
//
|
|
||||||
// app.Events.Listen("acme.seo", func(ctx context.Context, e *classes.BeforeAddItem) error {
|
|
||||||
// if strings.HasSuffix(e.Info.URL, "/draft") {
|
|
||||||
// e.Skip = true
|
|
||||||
// }
|
|
||||||
// return nil
|
|
||||||
// })
|
|
||||||
type BeforeAddItem struct {
|
|
||||||
Item models.DefinitionItem
|
|
||||||
Info ItemInfo
|
|
||||||
Skip bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsHandled reports Skip, so UntilHandled stops at the first listener that
|
|
||||||
// drops the URL (festival.Handleable).
|
|
||||||
func (e *BeforeAddItem) IsHandled() bool { return e != nil && e.Skip }
|
|
||||||
|
|
||||||
// AddItem is the typed successor of the PHP event golem15.sitemap.addItem.
|
|
||||||
// The generator fires it with festival.Bus.Fire after a URL's elements are
|
|
||||||
// built; listeners may append child XML to Extra, which is written as it is,
|
|
||||||
// before the url closing tag, so it must be escaped already (EscapeText,
|
|
||||||
// EscapeAttr).
|
|
||||||
//
|
|
||||||
// app.Events.Listen("acme.images", func(ctx context.Context, e *classes.AddItem) error {
|
|
||||||
// e.Extra = append(e.Extra, "<image:image><image:loc>"+classes.EscapeText(img)+"</image:loc></image:image>")
|
|
||||||
// return nil
|
|
||||||
// })
|
|
||||||
type AddItem struct {
|
|
||||||
Item models.DefinitionItem
|
|
||||||
Info ItemInfo
|
|
||||||
Extra []string
|
|
||||||
}
|
|
||||||
82
classes/files.go
Normal file
82
classes/files.go
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SitemapFile is one file of the sitemap index: its name, the number of
|
||||||
|
// addresses (pages for an image file, articles for the News file) and the
|
||||||
|
// newest lastmod of its addresses.
|
||||||
|
type SitemapFile struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Count int `json:"count"`
|
||||||
|
LastMod *time.Time `json:"lastmod"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// SitemapFiles lists the files the index links, in its order: the
|
||||||
|
// per-group files, the image files while images_enabled is on, then
|
||||||
|
// sitemap-news.xml while news_enabled is on and it lists an article.
|
||||||
|
func SitemapFiles(db *gorm.DB, app *backpack.App, s models.Settings, now time.Time) ([]SitemapFile, error) {
|
||||||
|
type fileRow struct {
|
||||||
|
Grp string `gorm:"column:grp"`
|
||||||
|
FileNo int `gorm:"column:file_no"`
|
||||||
|
N int `gorm:"column:n"`
|
||||||
|
LastMod *time.Time `gorm:"column:lastmod"`
|
||||||
|
}
|
||||||
|
var rows []fileRow
|
||||||
|
if err := db.Raw(`SELECT grp, file_no, COUNT(*) AS n, MAX(lastmod) AS lastmod FROM golem15_sitemap_urls
|
||||||
|
WHERE excluded_reason = '' AND file_no IS NOT NULL
|
||||||
|
GROUP BY grp, file_no ORDER BY grp, file_no`).Scan(&rows).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if s.ImagesEnabled {
|
||||||
|
var images []fileRow
|
||||||
|
if err := db.Raw(`SELECT image_file_no AS file_no, COUNT(*) AS n, MAX(lastmod) AS lastmod FROM golem15_sitemap_urls
|
||||||
|
WHERE excluded_reason = '' AND image_file_no IS NOT NULL AND jsonb_array_length(images) > 0
|
||||||
|
GROUP BY image_file_no ORDER BY image_file_no`).Scan(&images).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for i := range images {
|
||||||
|
images[i].Grp = ImagesGroup
|
||||||
|
}
|
||||||
|
rows = append(rows, images...)
|
||||||
|
}
|
||||||
|
out := make([]SitemapFile, 0, len(rows)+1)
|
||||||
|
for _, r := range rows {
|
||||||
|
out = append(out, SitemapFile{Name: FileName(r.Grp, r.FileNo), Count: r.N, LastMod: r.LastMod})
|
||||||
|
}
|
||||||
|
if s.NewsEnabled {
|
||||||
|
news, err := NewsEntries(db, app, s, now)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(news) > 0 {
|
||||||
|
newest := news[0].Published
|
||||||
|
out = append(out, SitemapFile{Name: NewsFile, Count: len(news), LastMod: &newest})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LeftOut counts the addresses left out of the sitemaps by reason (a
|
||||||
|
// Filter's or the type switch's; deleted and unpublished rows are holes,
|
||||||
|
// not left out).
|
||||||
|
func LeftOut(db *gorm.DB) (map[string]int, error) {
|
||||||
|
var rows []struct {
|
||||||
|
Reason string `gorm:"column:excluded_reason"`
|
||||||
|
N int `gorm:"column:n"`
|
||||||
|
}
|
||||||
|
if err := db.Raw(`SELECT excluded_reason, COUNT(*) AS n FROM golem15_sitemap_urls
|
||||||
|
WHERE excluded_reason NOT IN ('', ?, ?) GROUP BY excluded_reason`, models.ReasonDeleted, models.ReasonUnpublished).Scan(&rows).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := make(map[string]int, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
out[r.Reason] = r.N
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
@@ -1,268 +0,0 @@
|
|||||||
// Package classes generates the sitemap: it walks the definition items,
|
|
||||||
// resolves registry items through the framework's menu item type registry
|
|
||||||
// and writes the PHP-identical XML.
|
|
||||||
package classes
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/festival"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/pact"
|
|
||||||
)
|
|
||||||
|
|
||||||
// MaxURLs is the sitemap protocol's URL limit (PHP Definition::MAX_URLS):
|
|
||||||
// the 50000th URL is written, the 50001st is not.
|
|
||||||
const MaxURLs = 50000
|
|
||||||
|
|
||||||
// lastmodLayout is PHP date('c') in UTC: "+00:00", never "Z".
|
|
||||||
const lastmodLayout = "2006-01-02T15:04:05-07:00"
|
|
||||||
|
|
||||||
// Resolver resolves a registry item; *signpost.Registry implements it.
|
|
||||||
type Resolver interface {
|
|
||||||
Resolve(ctx context.Context, key, reference, itemPattern string, nesting bool, unprefixedLocale string) (*pact.ResolvedMenuItem, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generator writes the sitemap of a definition, following PHP
|
|
||||||
// Definition::generateSitemap and addItemToSet.
|
|
||||||
//
|
|
||||||
// Root is the backend root URL (scheme and host without a trailing slash)
|
|
||||||
// that Url::to builds absolute URLs from. Resolver resolves registry items;
|
|
||||||
// nil skips them. Settings are the sitemap settings (tiers, priorities,
|
|
||||||
// frontend default locale, manifest path), Tiers the compiled tier rules,
|
|
||||||
// and Events the bus BeforeAddItem and AddItem are fired on (nil fires
|
|
||||||
// nothing). Manifest, when set, is used instead of reading the settings'
|
|
||||||
// updates_manifest_path.
|
|
||||||
type Generator struct {
|
|
||||||
Root string
|
|
||||||
Resolver Resolver
|
|
||||||
Settings models.Settings
|
|
||||||
Tiers Tiers
|
|
||||||
Events *festival.Bus
|
|
||||||
Manifest Manifest
|
|
||||||
|
|
||||||
manifestLoaded bool
|
|
||||||
entries []URLEntry
|
|
||||||
count int
|
|
||||||
}
|
|
||||||
|
|
||||||
// itemInfo is PHP's $itemInfo: the URL (set marks it present), the record's
|
|
||||||
// modification time and the hreflang alternates.
|
|
||||||
type itemInfo struct {
|
|
||||||
url string
|
|
||||||
set bool
|
|
||||||
mtime *time.Time
|
|
||||||
alternates []Alternate
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generate returns the sitemap XML of items, or "" when there are none (PHP
|
|
||||||
// generateSitemap). A url item is added with its URL. A registry item is
|
|
||||||
// resolved with its URL pattern, its nesting and the settings' frontend
|
|
||||||
// default locale as the unprefixed locale; its URL is added when it has one,
|
|
||||||
// then its sub-items: when the item has no URL of its own (a list type),
|
|
||||||
// each sub-item is added once per alternate, with that alternate's URL as
|
|
||||||
// loc and every alternate as hreflang, as the PHP list types returned them;
|
|
||||||
// otherwise each sub-item is added once with its own URL. A type the
|
|
||||||
// registry does not know, or a Resolve that finds nothing, adds nothing.
|
|
||||||
//
|
|
||||||
// Generate does not apply the frontend_url rewrite; the route does
|
|
||||||
// (Rewrite).
|
|
||||||
func (g *Generator) Generate(ctx context.Context, items []models.DefinitionItem) (string, error) {
|
|
||||||
if len(items) == 0 {
|
|
||||||
return "", nil
|
|
||||||
}
|
|
||||||
if ctx == nil {
|
|
||||||
ctx = context.Background()
|
|
||||||
}
|
|
||||||
g.entries, g.count = nil, 0
|
|
||||||
for i := range items {
|
|
||||||
item := &items[i]
|
|
||||||
if item.Type == models.ItemTypeURL {
|
|
||||||
if err := g.addItem(ctx, item, itemInfo{}); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
resolved, err := g.resolve(ctx, item)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if resolved == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if resolved.URL != "" {
|
|
||||||
if err := g.addItem(ctx, item, infoOf(*resolved)); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if err := g.addChildren(ctx, item, resolved.Items); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if err := g.addPerLocale(ctx, item, resolved.Items); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Serialize(g.Stylesheet(), g.entries), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stylesheet is the stylesheet href PHP built:
|
|
||||||
// Url::buildUrl(Url::current(), ['path' => 'sitemap.xsl']).
|
|
||||||
func (g *Generator) Stylesheet() string {
|
|
||||||
return replacePath(URLTo(g.Root, "/sitemap.xml"), "sitemap.xsl")
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *Generator) resolve(ctx context.Context, item *models.DefinitionItem) (*pact.ResolvedMenuItem, error) {
|
|
||||||
if g.Resolver == nil || item.Type == "" {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
if reg, ok := g.Resolver.(interface {
|
|
||||||
Type(string) (pact.MenuItemType, bool)
|
|
||||||
}); ok {
|
|
||||||
if _, known := reg.Type(item.Type); !known {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return g.Resolver.Resolve(ctx, item.Type, models.Text(item.Reference), models.Text(item.URLPattern), item.Nesting, models.Text(g.Settings.FrontendDefaultLocale))
|
|
||||||
}
|
|
||||||
|
|
||||||
// addChildren adds every child with a URL, then its own children.
|
|
||||||
func (g *Generator) addChildren(ctx context.Context, item *models.DefinitionItem, children []pact.ResolvedMenuItem) error {
|
|
||||||
for _, child := range children {
|
|
||||||
if child.URL != "" {
|
|
||||||
if err := g.addItem(ctx, item, infoOf(child)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := g.addChildren(ctx, item, child.Items); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// addPerLocale adds the children of a list type: each once per alternate
|
|
||||||
// (once with its URL when it has no alternates), then its own children.
|
|
||||||
func (g *Generator) addPerLocale(ctx context.Context, item *models.DefinitionItem, children []pact.ResolvedMenuItem) error {
|
|
||||||
for _, child := range children {
|
|
||||||
info := infoOf(child)
|
|
||||||
if len(child.Alternates) == 0 {
|
|
||||||
if child.URL != "" {
|
|
||||||
if err := g.addItem(ctx, item, info); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := g.addChildren(ctx, item, child.Items); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
for _, alt := range child.Alternates {
|
|
||||||
perLocale := info
|
|
||||||
perLocale.url = alt.URL
|
|
||||||
if perLocale.url != "" {
|
|
||||||
if err := g.addItem(ctx, item, perLocale); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := g.addChildren(ctx, item, child.Items); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func infoOf(r pact.ResolvedMenuItem) itemInfo {
|
|
||||||
info := itemInfo{url: r.URL, set: true, mtime: r.MTime}
|
|
||||||
for _, a := range r.Alternates {
|
|
||||||
info.alternates = append(info.alternates, Alternate{Hreflang: a.Locale, Href: a.URL})
|
|
||||||
}
|
|
||||||
return info
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g *Generator) manifest() Manifest {
|
|
||||||
if !g.manifestLoaded {
|
|
||||||
if g.Manifest == nil {
|
|
||||||
g.Manifest = LoadManifest(models.Text(g.Settings.UpdatesManifestPath))
|
|
||||||
}
|
|
||||||
g.manifestLoaded = true
|
|
||||||
}
|
|
||||||
return g.Manifest
|
|
||||||
}
|
|
||||||
|
|
||||||
// addItem is PHP Definition::addItemToSet, in its order: the URL cap, a
|
|
||||||
// missing URL filled through Url::to, lastmod from the record or the
|
|
||||||
// manifest, BeforeAddItem, an empty URL dropped and the URL passed through
|
|
||||||
// Url::to again, the count, the tier or item priority, the elements and
|
|
||||||
// AddItem. Unlike PHP, a URL or alternate that does not come out as an
|
|
||||||
// http or https URL is dropped.
|
|
||||||
func (g *Generator) addItem(ctx context.Context, item *models.DefinitionItem, info itemInfo) error {
|
|
||||||
if g.count >= MaxURLs {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if !info.set {
|
|
||||||
info.url = URLTo(g.Root, models.Text(item.URL))
|
|
||||||
}
|
|
||||||
var lastmod time.Time
|
|
||||||
hasLastmod := false
|
|
||||||
if info.mtime != nil {
|
|
||||||
lastmod, hasLastmod = *info.mtime, true
|
|
||||||
} else if t, ok := g.manifest().Lastmod(info.url); ok {
|
|
||||||
lastmod, hasLastmod = t, true
|
|
||||||
}
|
|
||||||
lastmodText := ""
|
|
||||||
if hasLastmod && lastmod.Unix() != 0 {
|
|
||||||
lastmodText = lastmod.UTC().Format(lastmodLayout)
|
|
||||||
}
|
|
||||||
if g.Events != nil {
|
|
||||||
before := &BeforeAddItem{Item: *item, Info: ItemInfo{URL: info.url, MTime: info.mtime, Lastmod: lastmodText, Alternates: append([]Alternate(nil), info.alternates...)}}
|
|
||||||
skipped, err := g.Events.UntilHandled(ctx, before)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if skipped {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if info.url == "" || info.url == "0" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
loc := URLTo(g.Root, info.url)
|
|
||||||
if !httpURL(loc) {
|
|
||||||
// Only http and https URLs are written: a javascript: or other
|
|
||||||
// scheme that an import, a registry type or a pattern let through
|
|
||||||
// would be a clickable link in sitemap.xsl.
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
g.count++
|
|
||||||
priority, ok := g.Tiers.Priority(loc, g.Settings)
|
|
||||||
if !ok {
|
|
||||||
priority = models.Text(item.Priority)
|
|
||||||
}
|
|
||||||
entry := URLEntry{
|
|
||||||
Loc: loc,
|
|
||||||
Lastmod: lastmodText,
|
|
||||||
Changefreq: models.Text(item.Changefreq),
|
|
||||||
Priority: priority,
|
|
||||||
}
|
|
||||||
if len(info.alternates) > 1 {
|
|
||||||
for _, a := range info.alternates {
|
|
||||||
href := URLTo(g.Root, a.Href)
|
|
||||||
if !httpURL(href) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
entry.Alternates = append(entry.Alternates, Alternate{Hreflang: a.Hreflang, Href: href})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if g.Events != nil {
|
|
||||||
added := &AddItem{Item: *item, Info: ItemInfo{URL: loc, MTime: info.mtime, Lastmod: lastmodText, Alternates: append([]Alternate(nil), entry.Alternates...)}}
|
|
||||||
if err := g.Events.Fire(ctx, added); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
entry.Extra = added.Extra
|
|
||||||
}
|
|
||||||
g.entries = append(g.entries, entry)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,183 +0,0 @@
|
|||||||
package classes_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/festival"
|
|
||||||
)
|
|
||||||
|
|
||||||
func urlItems(paths ...string) []models.DefinitionItem {
|
|
||||||
out := make([]models.DefinitionItem, 0, len(paths))
|
|
||||||
for _, p := range paths {
|
|
||||||
out = append(out, models.DefinitionItem{Type: models.ItemTypeURL, URL: text(p), Changefreq: text("daily"), Priority: text("0.5")})
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestHooks pins the typed successors of the PHP events (D-14): a
|
|
||||||
// BeforeAddItem listener that sets Skip drops the URL before it is counted,
|
|
||||||
// the first skipping listener stops the rest, AddItem listeners see the
|
|
||||||
// written loc and their Extra is written before the url closing tag in
|
|
||||||
// order, and a listener error stops the generation.
|
|
||||||
func TestHooks(t *testing.T) {
|
|
||||||
bus := festival.New()
|
|
||||||
var seenBefore, seenAdd, afterSkip []string
|
|
||||||
bus.Listen("acme.first", func(_ context.Context, e *classes.BeforeAddItem) error {
|
|
||||||
seenBefore = append(seenBefore, e.Info.URL)
|
|
||||||
if strings.HasSuffix(e.Info.URL, "/skip") {
|
|
||||||
e.Skip = true
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
bus.Listen("acme.second", func(_ context.Context, e *classes.BeforeAddItem) error {
|
|
||||||
afterSkip = append(afterSkip, e.Info.URL)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
bus.Listen("acme.extra", func(_ context.Context, e *classes.AddItem) error {
|
|
||||||
seenAdd = append(seenAdd, e.Info.URL)
|
|
||||||
e.Extra = append(e.Extra, "<image:image><image:loc>"+classes.EscapeText(e.Info.URL+"?a&b")+"</image:loc></image:image>")
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
bus.Listen("acme.more", func(_ context.Context, e *classes.AddItem) error {
|
|
||||||
e.Extra = append(e.Extra, "<x/>")
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
gen := &classes.Generator{Root: "https://h.test", Events: bus}
|
|
||||||
xml, err := gen.Generate(context.Background(), urlItems("/a", "/skip", "/b"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if strings.Join(seenBefore, ",") != "https://h.test/a,https://h.test/skip,https://h.test/b" {
|
|
||||||
// The url item's URL is filled through Url::to before the event.
|
|
||||||
t.Fatalf("BeforeAddItem saw %v", seenBefore)
|
|
||||||
}
|
|
||||||
if strings.Join(afterSkip, ",") != "https://h.test/a,https://h.test/b" {
|
|
||||||
t.Fatalf("a listener after the skipping one ran for the skipped URL: %v", afterSkip)
|
|
||||||
}
|
|
||||||
if strings.Contains(xml, "/skip") {
|
|
||||||
t.Fatalf("the skipped URL is written:\n%s", xml)
|
|
||||||
}
|
|
||||||
if strings.Join(seenAdd, ",") != "https://h.test/a,https://h.test/b" {
|
|
||||||
t.Fatalf("AddItem saw %v", seenAdd)
|
|
||||||
}
|
|
||||||
want := "<url><loc>https://h.test/a</loc><changefreq>daily</changefreq><priority>0.5</priority><image:image><image:loc>https://h.test/a?a&b</image:loc></image:image><x/></url>"
|
|
||||||
if !strings.Contains(xml, want) {
|
|
||||||
t.Fatalf("extra not written before the closing tag:\n%s", xml)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A skip on the exact URL the event carries.
|
|
||||||
bus2 := festival.New()
|
|
||||||
var second []string
|
|
||||||
bus2.Listen("acme.skip", func(_ context.Context, e *classes.BeforeAddItem) error {
|
|
||||||
e.Skip = strings.HasSuffix(e.Info.URL, "/skip")
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
bus2.Listen("acme.later", func(_ context.Context, e *classes.BeforeAddItem) error {
|
|
||||||
second = append(second, e.Info.URL)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
gen = &classes.Generator{Root: "https://h.test", Events: bus2}
|
|
||||||
xml, err = gen.Generate(context.Background(), urlItems("/a", "/skip"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if strings.Contains(xml, "/skip<") || strings.Join(second, ",") != "https://h.test/a" {
|
|
||||||
t.Fatalf("UntilHandled did not stop at the skipping listener: %v\n%s", second, xml)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Without listeners or a bus nothing changes.
|
|
||||||
gen = &classes.Generator{Root: "https://h.test"}
|
|
||||||
if xml, err := gen.Generate(context.Background(), urlItems("/a")); err != nil || !strings.Contains(xml, "<loc>https://h.test/a</loc>") {
|
|
||||||
t.Fatalf("no bus: %v\n%s", err, xml)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A listener error stops the generation.
|
|
||||||
failing := festival.New()
|
|
||||||
failing.Listen("acme.fail", func(_ context.Context, e *classes.AddItem) error { return errors.New("listener failed") })
|
|
||||||
gen = &classes.Generator{Root: "https://h.test", Events: failing}
|
|
||||||
if _, err := gen.Generate(context.Background(), urlItems("/a")); err == nil || !strings.Contains(err.Error(), "listener failed") {
|
|
||||||
t.Fatalf("listener error = %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestURLCap pins the protocol limit: of 50,001 URLs the 50,000th is
|
|
||||||
// written and the 50,001st is not; skipped and empty URLs are not counted;
|
|
||||||
// no items is an empty document.
|
|
||||||
func TestURLCap(t *testing.T) {
|
|
||||||
paths := make([]string, classes.MaxURLs+1)
|
|
||||||
for i := range paths {
|
|
||||||
paths[i] = "/u/" + strconv.Itoa(i+1)
|
|
||||||
}
|
|
||||||
gen := &classes.Generator{Root: "https://api.example.test"}
|
|
||||||
xml, err := gen.Generate(context.Background(), urlItems(paths...))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if n := strings.Count(xml, "<url>"); n != classes.MaxURLs {
|
|
||||||
t.Fatalf("%d url elements, want %d", n, classes.MaxURLs)
|
|
||||||
}
|
|
||||||
if !strings.Contains(xml, "<loc>https://api.example.test/u/50000</loc>") || strings.Contains(xml, "<loc>https://api.example.test/u/50001</loc>") {
|
|
||||||
t.Fatal("the 50000th URL must be written and the 50001st must not")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Skipped URLs do not count toward the cap.
|
|
||||||
bus := festival.New()
|
|
||||||
bus.Listen("acme.skip", func(_ context.Context, e *classes.BeforeAddItem) error {
|
|
||||||
e.Skip = strings.HasSuffix(e.Info.URL, "/u/1")
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
gen = &classes.Generator{Root: "https://api.example.test", Events: bus}
|
|
||||||
xml, err = gen.Generate(context.Background(), urlItems(paths...))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if strings.Count(xml, "<url>") != classes.MaxURLs || !strings.Contains(xml, "/u/50001</loc>") {
|
|
||||||
t.Fatal("a skipped URL took a place under the cap")
|
|
||||||
}
|
|
||||||
|
|
||||||
// A generator is reusable: a second run starts its count again.
|
|
||||||
if again, err := gen.Generate(context.Background(), urlItems("/x")); err != nil || strings.Count(again, "<url>") != 1 {
|
|
||||||
t.Fatalf("second run = %v, %d urls", err, strings.Count(again, "<url>"))
|
|
||||||
}
|
|
||||||
if empty, err := (&classes.Generator{Root: "https://h"}).Generate(context.Background(), nil); err != nil || empty != "" {
|
|
||||||
t.Fatalf("no items = %q %v", empty, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestOnlyHTTPLocs pins the CR-01 output filter: a URL that Url::to keeps
|
|
||||||
// but that is not http or https (a javascript: URL FILTER_VALIDATE_URL
|
|
||||||
// accepts, mailto:, a bare fragment) is not written and not counted. A
|
|
||||||
// protocol-relative URL comes out of Url::to on the root host.
|
|
||||||
func TestOnlyHTTPLocs(t *testing.T) {
|
|
||||||
gen := &classes.Generator{Root: "https://api.example.test"}
|
|
||||||
xml, err := gen.Generate(context.Background(), urlItems(
|
|
||||||
"javascript://%0aalert(1)%0a//x",
|
|
||||||
"JavaScript://example.test/%0aalert(1)",
|
|
||||||
"//evil.test/x",
|
|
||||||
"mailto:a@example.test",
|
|
||||||
"#top",
|
|
||||||
"/ok",
|
|
||||||
"https://other.example.test/page",
|
|
||||||
))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if n := strings.Count(xml, "<url>"); n != 3 {
|
|
||||||
t.Fatalf("%d url elements, want 3:\n%s", n, xml)
|
|
||||||
}
|
|
||||||
if !strings.Contains(xml, "<loc>https://api.example.test/evil.test/x</loc>") {
|
|
||||||
t.Fatalf("the protocol-relative URL did not stay on the root host:\n%s", xml)
|
|
||||||
}
|
|
||||||
if strings.Contains(strings.ToLower(xml), "javascript") || strings.Contains(xml, "mailto:") || strings.Contains(xml, "#top") {
|
|
||||||
t.Fatalf("a non-http URL was written:\n%s", xml)
|
|
||||||
}
|
|
||||||
if !strings.Contains(xml, "<loc>https://api.example.test/ok</loc>") || !strings.Contains(xml, "<loc>https://other.example.test/page</loc>") {
|
|
||||||
t.Fatalf("an http(s) URL is missing:\n%s", xml)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,343 +0,0 @@
|
|||||||
package classes_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"slices"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
sitemap "git.golem15.com/golem15/sm-sitemap-plugin"
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/compass"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/festival"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/pact"
|
|
||||||
)
|
|
||||||
|
|
||||||
// The goldens in testdata are written by tests/php/gen-goldens.php from the
|
|
||||||
// same JSON inputs with the PHP plugin's generation code and the vendored
|
|
||||||
// Winter URL generator; these tests feed the inputs through the Go port and
|
|
||||||
// compare bytes.
|
|
||||||
|
|
||||||
// goldenResolved is a registry item's resolve result in a golden input.
|
|
||||||
type goldenResolved struct {
|
|
||||||
URL string `json:"url"`
|
|
||||||
MTime *string `json:"mtime"`
|
|
||||||
Alternates [][2]string `json:"alternates"`
|
|
||||||
Items []goldenResolved `json:"items"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (g goldenResolved) toPact(t *testing.T) pact.ResolvedMenuItem {
|
|
||||||
t.Helper()
|
|
||||||
out := pact.ResolvedMenuItem{URL: g.URL}
|
|
||||||
if g.MTime != nil {
|
|
||||||
at, err := time.Parse(time.RFC3339, *g.MTime)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("mtime %q: %v", *g.MTime, err)
|
|
||||||
}
|
|
||||||
out.MTime = &at
|
|
||||||
}
|
|
||||||
for _, a := range g.Alternates {
|
|
||||||
out.Alternates = append(out.Alternates, pact.MenuItemAlternate{Locale: a[0], URL: a[1]})
|
|
||||||
}
|
|
||||||
for _, child := range g.Items {
|
|
||||||
out.Items = append(out.Items, child.toPact(t))
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// goldenCase is one sitemap case of a golden input: the stored items, the
|
|
||||||
// registry types' resolve results, the settings (PHP keys), the updates
|
|
||||||
// manifest, the URLs a BeforeAddItem listener skips and the text of the
|
|
||||||
// extra element an AddItem listener appends per URL.
|
|
||||||
type goldenCase struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Root string `json:"root"`
|
|
||||||
Items models.DefinitionItems `json:"items"`
|
|
||||||
Types map[string]map[string]goldenResolved `json:"types"`
|
|
||||||
Settings map[string]json.RawMessage `json:"settings"`
|
|
||||||
Manifest map[string]any `json:"manifest"`
|
|
||||||
Skip []string `json:"skip"`
|
|
||||||
Extra map[string]string `json:"extra"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// fakeResolver answers Resolve from a golden case's types.
|
|
||||||
type fakeResolver struct {
|
|
||||||
t *testing.T
|
|
||||||
types map[string]map[string]goldenResolved
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeResolver) Type(key string) (pact.MenuItemType, bool) {
|
|
||||||
_, ok := f.types[key]
|
|
||||||
return pact.MenuItemType{Key: key}, ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f fakeResolver) Resolve(_ context.Context, key, reference, _ string, _ bool, _ string) (*pact.ResolvedMenuItem, error) {
|
|
||||||
r, ok := f.types[key][reference]
|
|
||||||
if !ok {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
out := r.toPact(f.t)
|
|
||||||
return &out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// pluginTiers compiles the tier rules the plugin's own config/config.yaml
|
|
||||||
// ships.
|
|
||||||
func pluginTiers(t *testing.T) classes.Tiers {
|
|
||||||
t.Helper()
|
|
||||||
cfg, err := compass.Open(compass.Options{Dir: t.TempDir(), Environ: []string{}})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := cfg.MergePlugin("golem15.sitemap", (&sitemap.Plugin{}).ConfigFS()); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
tiers, err := classes.LoadTiers(cfg)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return tiers
|
|
||||||
}
|
|
||||||
|
|
||||||
// caseSettings builds the settings of a case from its PHP keys.
|
|
||||||
func caseSettings(t *testing.T, c goldenCase) models.Settings {
|
|
||||||
t.Helper()
|
|
||||||
s := models.DefaultSettings()
|
|
||||||
texts := map[string]**string{
|
|
||||||
"frontend_url": &s.FrontendURL,
|
|
||||||
"frontend_default_locale": &s.FrontendDefaultLocale,
|
|
||||||
"priority_homepage": &s.PriorityHomepage,
|
|
||||||
"priority_services": &s.PriorityServices,
|
|
||||||
"priority_blog": &s.PriorityBlog,
|
|
||||||
"priority_categories": &s.PriorityCategories,
|
|
||||||
"priority_legal": &s.PriorityLegal,
|
|
||||||
}
|
|
||||||
for key, raw := range c.Settings {
|
|
||||||
if key == "enable_priority_tiers" {
|
|
||||||
if err := json.Unmarshal(raw, &s.EnablePriorityTiers); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
dest, ok := texts[key]
|
|
||||||
if !ok {
|
|
||||||
t.Fatalf("case %s: unknown setting %s", c.Name, key)
|
|
||||||
}
|
|
||||||
v, err := models.DecodeText(raw)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
*dest = v
|
|
||||||
}
|
|
||||||
if c.Manifest != nil {
|
|
||||||
raw, err := json.Marshal(c.Manifest)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
path := filepath.Join(t.TempDir(), "updates.json")
|
|
||||||
if err := os.WriteFile(path, raw, 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
s.UpdatesManifestPath = &path
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
// renderCase runs a case through the generator and the route's rewrite.
|
|
||||||
func renderCase(t *testing.T, c goldenCase) string {
|
|
||||||
t.Helper()
|
|
||||||
bus := festival.New()
|
|
||||||
bus.Listen("test.skip", func(_ context.Context, e *classes.BeforeAddItem) error {
|
|
||||||
if slices.Contains(c.Skip, e.Info.URL) {
|
|
||||||
e.Skip = true
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
bus.Listen("test.extra", func(_ context.Context, e *classes.AddItem) error {
|
|
||||||
if text, ok := c.Extra[e.Info.URL]; ok {
|
|
||||||
e.Extra = append(e.Extra, "<extra>"+classes.EscapeText(text)+"</extra>")
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
settings := caseSettings(t, c)
|
|
||||||
gen := &classes.Generator{
|
|
||||||
Root: c.Root,
|
|
||||||
Resolver: fakeResolver{t: t, types: c.Types},
|
|
||||||
Settings: settings,
|
|
||||||
Tiers: pluginTiers(t),
|
|
||||||
Events: bus,
|
|
||||||
}
|
|
||||||
xml, err := gen.Generate(context.Background(), c.Items)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("generate %s: %v", c.Name, err)
|
|
||||||
}
|
|
||||||
return classes.Rewrite(xml, classes.BackendURL(c.Root), models.Text(settings.FrontendURL))
|
|
||||||
}
|
|
||||||
|
|
||||||
func readTestdata(t *testing.T, name string) []byte {
|
|
||||||
t.Helper()
|
|
||||||
raw, err := os.ReadFile(filepath.Join("testdata", name))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return raw
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestSitemapGolden compares the Go sitemap with the PHP goldens.
|
|
||||||
func TestSitemapGolden(t *testing.T) {
|
|
||||||
t.Run("urlto", func(t *testing.T) {
|
|
||||||
var in struct {
|
|
||||||
Root string `json:"root"`
|
|
||||||
URLs []*string `json:"urls"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(readTestdata(t, "urlto.json"), &in); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
want := strings.Split(strings.TrimSuffix(string(readTestdata(t, "urlto.golden")), "\n"), "\n")
|
|
||||||
if len(want) != len(in.URLs) {
|
|
||||||
t.Fatalf("urlto.golden has %d lines for %d inputs", len(want), len(in.URLs))
|
|
||||||
}
|
|
||||||
var got strings.Builder
|
|
||||||
for i, u := range in.URLs {
|
|
||||||
path := ""
|
|
||||||
if u != nil {
|
|
||||||
path = *u
|
|
||||||
}
|
|
||||||
out := classes.URLTo(in.Root, path)
|
|
||||||
if out != want[i] {
|
|
||||||
t.Errorf("URLTo(%q) = %q, PHP %q", path, out, want[i])
|
|
||||||
}
|
|
||||||
got.WriteString(out + "\n")
|
|
||||||
}
|
|
||||||
if got.String() != string(readTestdata(t, "urlto.golden")) {
|
|
||||||
t.Error("urlto output differs from the golden file")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("tracer", func(t *testing.T) {
|
|
||||||
var in struct {
|
|
||||||
Case goldenCase `json:"case"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(readTestdata(t, "tracer.json"), &in); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
got := renderCase(t, in.Case)
|
|
||||||
if want := string(readTestdata(t, "tracer.golden")); got != want {
|
|
||||||
t.Fatalf("tracer sitemap differs from the PHP golden\n got: %q\nwant: %q", got, want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("full", func(t *testing.T) {
|
|
||||||
var in struct {
|
|
||||||
Cases []goldenCase `json:"cases"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(readTestdata(t, "full.json"), &in); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
golden := string(readTestdata(t, "full.golden"))
|
|
||||||
var all strings.Builder
|
|
||||||
for i, c := range in.Cases {
|
|
||||||
got := renderCase(t, c)
|
|
||||||
all.WriteString("=== " + c.Name + "\n" + got)
|
|
||||||
header := "=== " + c.Name + "\n"
|
|
||||||
start := strings.Index(golden, header)
|
|
||||||
if start < 0 {
|
|
||||||
t.Errorf("case %s is missing from full.golden", c.Name)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
want := golden[start+len(header):]
|
|
||||||
if i+1 < len(in.Cases) {
|
|
||||||
if end := strings.Index(want, "=== "+in.Cases[i+1].Name+"\n"); end >= 0 {
|
|
||||||
want = want[:end]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if got != want {
|
|
||||||
t.Errorf("case %s differs from the PHP golden\n got: %q\nwant: %q", c.Name, got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if all.String() != golden {
|
|
||||||
t.Error("full output differs from full.golden")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("cap", func(t *testing.T) {
|
|
||||||
items := make([]models.DefinitionItem, classes.MaxURLs+1)
|
|
||||||
for i := range items {
|
|
||||||
u := "/u/" + strconv.Itoa(i+1)
|
|
||||||
items[i] = models.DefinitionItem{Type: models.ItemTypeURL, URL: &u}
|
|
||||||
}
|
|
||||||
gen := &classes.Generator{Root: "https://api.example.test"}
|
|
||||||
xml, err := gen.Generate(context.Background(), items)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if n := strings.Count(xml, "<url>"); n != classes.MaxURLs {
|
|
||||||
t.Fatalf("%d urls written, want %d", n, classes.MaxURLs)
|
|
||||||
}
|
|
||||||
if !strings.Contains(xml, "<loc>https://api.example.test/u/50000</loc>") || strings.Contains(xml, "/u/50001<") {
|
|
||||||
t.Fatal("the 50000th URL must be written and the 50001st must not")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestSitemapTiersConfig checks the boot-time tier rule checks, a host's
|
|
||||||
// replacement of the default list and the manifest's fail-safe reads.
|
|
||||||
func TestSitemapTiersConfig(t *testing.T) {
|
|
||||||
for name, rules := range map[string][]classes.TierConfig{
|
|
||||||
"unknown setting": {{Setting: "priority_other", Exact: []string{""}}},
|
|
||||||
"neither": {{Setting: models.PriorityHomepage}},
|
|
||||||
"both": {{Setting: models.PriorityHomepage, Exact: []string{""}, Pattern: "^/$"}},
|
|
||||||
"bad pattern": {{Setting: models.PriorityBlog, Pattern: "^/(blog"}},
|
|
||||||
} {
|
|
||||||
if _, err := classes.CompileTiers(rules); err == nil {
|
|
||||||
t.Errorf("%s: compiled, want an error", name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
dir := t.TempDir()
|
|
||||||
host := "sitemap:\n priority_tiers:\n - setting: priority_legal\n pattern: '^/legal(/.*)?$'\n"
|
|
||||||
if err := os.WriteFile(filepath.Join(dir, "golem15.yaml"), []byte(host), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{}})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := cfg.MergePlugin("golem15.sitemap", (&sitemap.Plugin{}).ConfigFS()); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
tiers, err := classes.LoadTiers(cfg)
|
|
||||||
if err != nil || len(tiers) != 1 {
|
|
||||||
t.Fatalf("host tiers = %+v, %v", tiers, err)
|
|
||||||
}
|
|
||||||
s := models.DefaultSettings()
|
|
||||||
if p, ok := tiers.Priority("https://h/legal/terms/", s); !ok || p != "0.2" {
|
|
||||||
t.Fatalf("host rule priority = %q %v", p, ok)
|
|
||||||
}
|
|
||||||
if _, ok := tiers.Priority("https://h/", s); ok {
|
|
||||||
t.Fatal("the host list must replace the default homepage rule")
|
|
||||||
}
|
|
||||||
|
|
||||||
if m := classes.LoadManifest(dir); m != nil {
|
|
||||||
t.Fatal("a directory is not a manifest")
|
|
||||||
}
|
|
||||||
list := filepath.Join(dir, "list.json")
|
|
||||||
if err := os.WriteFile(list, []byte(`["/a"]`), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if m := classes.LoadManifest(list); m != nil {
|
|
||||||
t.Fatal("a JSON list is not a manifest")
|
|
||||||
}
|
|
||||||
big := filepath.Join(dir, "big.json")
|
|
||||||
if err := os.WriteFile(big, append([]byte(`{"/a":"2026-01-01","x":"`), append(make([]byte, classes.ManifestMaxBytes), '"', '}')...), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if m := classes.LoadManifest(big); m != nil {
|
|
||||||
t.Fatal("a manifest over the size cap must be ignored")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
456
classes/htmlgroups.go
Normal file
456
classes/htmlgroups.go
Normal file
@@ -0,0 +1,456 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/contract"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/signpost"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/towel"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HTMLEntry is one link of the HTML sitemap: the address's title (its
|
||||||
|
// path when it has none) and absolute URL; Children nest a category tree.
|
||||||
|
type HTMLEntry struct {
|
||||||
|
Title string `json:"title"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
Children []HTMLEntry `json:"children,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTMLGroup is one group of the HTML sitemap overview: Key and Slug name
|
||||||
|
// the file group (the group page is addressed by Slug), Title is its
|
||||||
|
// heading in the requested locale, Total its addresses, Entries the first
|
||||||
|
// page of them and More is true when the group has more than one page.
|
||||||
|
type HTMLGroup struct {
|
||||||
|
Key string `json:"key"`
|
||||||
|
Slug string `json:"slug"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
More bool `json:"more"`
|
||||||
|
Entries []HTMLEntry `json:"entries"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTMLOverview is the answer of GET /_sitemap/api/v1/html: the locale and
|
||||||
|
// the non-empty groups in the HTML sitemap order.
|
||||||
|
type HTMLOverview struct {
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
PageSize int `json:"page_size"`
|
||||||
|
Groups []HTMLGroup `json:"groups"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTMLGroupPage is the answer of GET /_sitemap/api/v1/html/{group}: one
|
||||||
|
// page (from 1) of a group's links out of Pages.
|
||||||
|
type HTMLGroupPage struct {
|
||||||
|
Group string `json:"group"`
|
||||||
|
Key string `json:"key"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Locale string `json:"locale"`
|
||||||
|
Page int `json:"page"`
|
||||||
|
Pages int `json:"pages"`
|
||||||
|
Total int `json:"total"`
|
||||||
|
Entries []HTMLEntry `json:"entries"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// htmlGroupOrder is the order of the groups the HTML sitemap knows by
|
||||||
|
// name (UI-SPEC L3): pages, offers and services, categories, posts, tags,
|
||||||
|
// authors. The groups of other content types follow in registration order,
|
||||||
|
// then any other group (a Filter's) alphabetically.
|
||||||
|
var htmlGroupOrder = []string{"pages", "offers", "services", "categories", "posts", "tags", "authors"}
|
||||||
|
|
||||||
|
// maxTreeRows bounds the rows a category tree is built from; a larger
|
||||||
|
// group is listed alphabetically.
|
||||||
|
const maxTreeRows = 10000
|
||||||
|
|
||||||
|
// The orders of a group's links.
|
||||||
|
const (
|
||||||
|
orderTitle = "title" // alphabetical by title
|
||||||
|
orderNewest = "newest" // newest first (articles)
|
||||||
|
orderTree = "tree" // tree order (collections with parents)
|
||||||
|
)
|
||||||
|
|
||||||
|
// htmlRow is what the HTML sitemap reads of a slot table row.
|
||||||
|
type htmlRow struct {
|
||||||
|
ID uint64 `gorm:"column:id"`
|
||||||
|
Grp string `gorm:"column:grp"`
|
||||||
|
TypeKey string `gorm:"column:type_key"`
|
||||||
|
RecordID string `gorm:"column:record_id"`
|
||||||
|
URL string `gorm:"column:url"`
|
||||||
|
Title string `gorm:"column:title"`
|
||||||
|
PublishedAt *time.Time `gorm:"column:published_at"`
|
||||||
|
ParentRefs string `gorm:"column:parent_refs"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// htmlGroupInfo is one group of the HTML sitemap before its links are
|
||||||
|
// read: its slug, title, total and order.
|
||||||
|
type htmlGroupInfo struct {
|
||||||
|
slug string
|
||||||
|
title string
|
||||||
|
total int
|
||||||
|
order string
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTMLSitemap reads the HTML sitemap (D-34): the listed addresses of the
|
||||||
|
// XML sitemaps (never an excluded one, D-24) of locale and those without
|
||||||
|
// one, by group. locale "" means the default_locale setting (no locale
|
||||||
|
// filter when that is empty too).
|
||||||
|
type HTMLSitemap struct {
|
||||||
|
App *backpack.App
|
||||||
|
DB *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
// scope is the listed rows of locale.
|
||||||
|
func (h HTMLSitemap) scope(locale string) *gorm.DB {
|
||||||
|
q := h.DB.Table("golem15_sitemap_urls").Where("excluded_reason = ''")
|
||||||
|
if locale != "" {
|
||||||
|
q = q.Where("locale = ? OR locale = ''", locale)
|
||||||
|
}
|
||||||
|
return q
|
||||||
|
}
|
||||||
|
|
||||||
|
// locale is the locale the HTML sitemap filters by.
|
||||||
|
func (h HTMLSitemap) locale(s models.Settings, locale string) string {
|
||||||
|
if locale = strings.TrimSpace(locale); locale != "" {
|
||||||
|
return locale
|
||||||
|
}
|
||||||
|
return models.Text(s.DefaultLocale)
|
||||||
|
}
|
||||||
|
|
||||||
|
// groups lists the groups with listed rows of locale in the HTML sitemap
|
||||||
|
// order, with their titles in locale and their orders.
|
||||||
|
func (h HTMLSitemap) groups(ctx context.Context, s models.Settings, locale string) ([]htmlGroupInfo, error) {
|
||||||
|
var counts []struct {
|
||||||
|
Grp string `gorm:"column:grp"`
|
||||||
|
N int `gorm:"column:n"`
|
||||||
|
Articles int `gorm:"column:articles"`
|
||||||
|
Nested int `gorm:"column:nested"`
|
||||||
|
}
|
||||||
|
if err := h.scope(locale).Select(`grp, COUNT(*) AS n,
|
||||||
|
COUNT(*) FILTER (WHERE kind = ?) AS articles,
|
||||||
|
COUNT(*) FILTER (WHERE kind = ? AND jsonb_array_length(parent_refs) > 0) AS nested`, pact.ContentKindArticle, pact.ContentKindCollection).
|
||||||
|
Group("grp").Scan(&counts).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
titles, labels, typeOrder, err := groupTitles(ctx, h.App, h.DB)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
def := models.Text(s.DefaultLocale)
|
||||||
|
out := make([]htmlGroupInfo, 0, len(counts))
|
||||||
|
for _, c := range counts {
|
||||||
|
if c.N == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
g := htmlGroupInfo{slug: c.Grp, total: c.N, order: orderTitle}
|
||||||
|
switch {
|
||||||
|
case c.Articles == c.N:
|
||||||
|
g.order = orderNewest
|
||||||
|
case c.Nested > 0 && c.N <= maxTreeRows:
|
||||||
|
g.order = orderTree
|
||||||
|
}
|
||||||
|
g.title = pickTitle(titles[c.Grp], locale, def)
|
||||||
|
if g.title == "" {
|
||||||
|
if label := labels[c.Grp]; label != "" {
|
||||||
|
g.title = translateIn(ctx, h.App, locale, label)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if g.title == "" {
|
||||||
|
g.title = c.Grp
|
||||||
|
}
|
||||||
|
out = append(out, g)
|
||||||
|
}
|
||||||
|
rank := func(slug string) (int, int) {
|
||||||
|
if i := slices.Index(htmlGroupOrder, slug); i >= 0 {
|
||||||
|
return 0, i
|
||||||
|
}
|
||||||
|
if i, ok := typeOrder[slug]; ok {
|
||||||
|
return 1, i
|
||||||
|
}
|
||||||
|
return 2, 0
|
||||||
|
}
|
||||||
|
slices.SortStableFunc(out, func(a, b htmlGroupInfo) int {
|
||||||
|
ta, ia := rank(a.slug)
|
||||||
|
tb, ib := rank(b.slug)
|
||||||
|
if ta != tb {
|
||||||
|
return ta - tb
|
||||||
|
}
|
||||||
|
if ia != ib {
|
||||||
|
return ia - ib
|
||||||
|
}
|
||||||
|
return strings.Compare(a.slug, b.slug)
|
||||||
|
})
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// pickTitle is the title of locale, else of the default locale, else "".
|
||||||
|
func pickTitle(titles map[string]string, locale, def string) string {
|
||||||
|
if t := strings.TrimSpace(titles[locale]); t != "" {
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
if t := strings.TrimSpace(titles[def]); t != "" {
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// translateIn translates a phrase key (a content type label) in locale;
|
||||||
|
// without a translator, or for a plain label, it is returned as is.
|
||||||
|
func translateIn(ctx context.Context, app *backpack.App, locale, key string) string {
|
||||||
|
if app == nil {
|
||||||
|
return key
|
||||||
|
}
|
||||||
|
tr, ok := app.Lookup[*phrasebook.Translator]()
|
||||||
|
if !ok || tr == nil {
|
||||||
|
return key
|
||||||
|
}
|
||||||
|
if locale != "" {
|
||||||
|
ctx = towel.WithLocale(ctx, locale)
|
||||||
|
}
|
||||||
|
return tr.Get(ctx, key, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// groupTitles collects the group headings (by group slug, per locale):
|
||||||
|
// the published Filter's group titles, overridden by the content types'
|
||||||
|
// saved HTML sitemap headings; the content types' labels by slug; and the
|
||||||
|
// content types' registration order by slug.
|
||||||
|
func groupTitles(ctx context.Context, app *backpack.App, db *gorm.DB) (titles map[string]map[string]string, labels map[string]string, order map[string]int, err error) {
|
||||||
|
titles, labels, order = map[string]map[string]string{}, map[string]string{}, map[string]int{}
|
||||||
|
if app == nil {
|
||||||
|
return titles, labels, order, nil
|
||||||
|
}
|
||||||
|
if filter, ok := app.Lookup[contract.Filter](); ok && filter != nil {
|
||||||
|
groups, err := filter.Groups(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, nil, err
|
||||||
|
}
|
||||||
|
for _, g := range groups {
|
||||||
|
if len(g.Titles) > 0 {
|
||||||
|
titles[g.Key] = g.Titles
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if reg, ok := app.Lookup[*signpost.Registry](); ok && reg != nil {
|
||||||
|
rows, err := LoadTypeSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, nil, err
|
||||||
|
}
|
||||||
|
for i, typ := range reg.ContentTypes() {
|
||||||
|
cfg := EffectiveType(typ, rows)
|
||||||
|
if len(cfg.Titles) > 0 {
|
||||||
|
titles[cfg.Slug] = cfg.Titles
|
||||||
|
}
|
||||||
|
if _, seen := labels[cfg.Slug]; !seen {
|
||||||
|
labels[cfg.Slug] = typ.Label
|
||||||
|
order[cfg.Slug] = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return titles, labels, order, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// entry is one link with what ordering and the tree need.
|
||||||
|
type entry struct {
|
||||||
|
HTMLEntry
|
||||||
|
node models.Ref
|
||||||
|
parent *models.Ref
|
||||||
|
}
|
||||||
|
|
||||||
|
// rows reads the rows of one group in its order: newest first for
|
||||||
|
// articles, alphabetical by title otherwise (a tree is ordered later).
|
||||||
|
// offset and limit page the read; limit < 0 reads every row.
|
||||||
|
func (h HTMLSitemap) rows(g htmlGroupInfo, locale string, offset, limit int) ([]htmlRow, error) {
|
||||||
|
q := h.scope(locale).Select("id, grp, type_key, record_id, url, title, published_at, parent_refs::text AS parent_refs").Where("grp = ?", g.slug)
|
||||||
|
switch g.order {
|
||||||
|
case orderNewest:
|
||||||
|
q = q.Order("published_at DESC NULLS LAST, first_seen DESC, id DESC")
|
||||||
|
default:
|
||||||
|
q = q.Order("lower(COALESCE(NULLIF(title, ''), url)) ASC, id ASC")
|
||||||
|
}
|
||||||
|
if limit >= 0 {
|
||||||
|
q = q.Offset(offset).Limit(limit)
|
||||||
|
}
|
||||||
|
var out []htmlRow
|
||||||
|
return out, q.Scan(&out).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// toEntries turns rows into links on site; a row whose address cannot be
|
||||||
|
// made absolute is skipped.
|
||||||
|
func toEntries(rows []htmlRow, site string) []entry {
|
||||||
|
out := make([]entry, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
u := Absolute(site, r.URL)
|
||||||
|
if u == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
title := strings.TrimSpace(r.Title)
|
||||||
|
if title == "" {
|
||||||
|
title = r.URL
|
||||||
|
}
|
||||||
|
e := entry{HTMLEntry: HTMLEntry{Title: title, URL: u}, node: models.Ref{Type: r.TypeKey, ID: r.RecordID}}
|
||||||
|
var parents []models.Ref
|
||||||
|
if r.ParentRefs != "" {
|
||||||
|
_ = json.Unmarshal([]byte(r.ParentRefs), &parents)
|
||||||
|
}
|
||||||
|
if len(parents) > 0 {
|
||||||
|
e.parent = &parents[0]
|
||||||
|
}
|
||||||
|
out = append(out, e)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// treeOrder orders entries as a tree (alphabetical siblings, depth first)
|
||||||
|
// and returns them flat with each entry's parent index in the result (-1
|
||||||
|
// for a root). An entry whose first parent is not in the group, or that
|
||||||
|
// would close a cycle, is a root.
|
||||||
|
func treeOrder(entries []entry) ([]entry, []int) {
|
||||||
|
index := make(map[models.Ref]int, len(entries))
|
||||||
|
for i, e := range entries {
|
||||||
|
index[e.node] = i
|
||||||
|
}
|
||||||
|
children := map[int][]int{}
|
||||||
|
var roots []int
|
||||||
|
for i, e := range entries {
|
||||||
|
if e.parent != nil {
|
||||||
|
if p, ok := index[*e.parent]; ok && p != i {
|
||||||
|
children[p] = append(children[p], i)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
roots = append(roots, i)
|
||||||
|
}
|
||||||
|
flat := make([]entry, 0, len(entries))
|
||||||
|
parents := make([]int, 0, len(entries))
|
||||||
|
visited := make([]bool, len(entries))
|
||||||
|
var walk func(i, parent int)
|
||||||
|
walk = func(i, parent int) {
|
||||||
|
if visited[i] {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
visited[i] = true
|
||||||
|
at := len(flat)
|
||||||
|
flat = append(flat, entries[i])
|
||||||
|
parents = append(parents, parent)
|
||||||
|
for _, c := range children[i] {
|
||||||
|
walk(c, at)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, r := range roots {
|
||||||
|
walk(r, -1)
|
||||||
|
}
|
||||||
|
// Entries only reachable through a cycle are roots.
|
||||||
|
for i := range entries {
|
||||||
|
walk(i, -1)
|
||||||
|
}
|
||||||
|
return flat, parents
|
||||||
|
}
|
||||||
|
|
||||||
|
// nest builds the links of flat[start:end] (tree order, parents indices
|
||||||
|
// into flat): an entry whose parent is on the same page is its child,
|
||||||
|
// every other is a top-level link.
|
||||||
|
func nest(flat []entry, parents []int, start, end int) []HTMLEntry {
|
||||||
|
nodes := make([]*HTMLEntry, end-start)
|
||||||
|
for i := start; i < end; i++ {
|
||||||
|
e := flat[i].HTMLEntry
|
||||||
|
e.Children = nil
|
||||||
|
nodes[i-start] = &e
|
||||||
|
}
|
||||||
|
// Children are attached deepest first so a parent copies its finished
|
||||||
|
// children.
|
||||||
|
for i := end - 1; i >= start; i-- {
|
||||||
|
p := parents[i]
|
||||||
|
if p >= start && p < end {
|
||||||
|
parent := nodes[p-start]
|
||||||
|
parent.Children = append([]HTMLEntry{*nodes[i-start]}, parent.Children...)
|
||||||
|
nodes[i-start] = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := []HTMLEntry{}
|
||||||
|
for _, n := range nodes {
|
||||||
|
if n != nil {
|
||||||
|
out = append(out, *n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// page reads page n (from 1) of group g: its links and the number of
|
||||||
|
// pages.
|
||||||
|
func (h HTMLSitemap) page(g htmlGroupInfo, locale, site string, size, n int) ([]HTMLEntry, int, error) {
|
||||||
|
pages := (g.total + size - 1) / size
|
||||||
|
if g.order == orderTree {
|
||||||
|
rows, err := h.rows(g, locale, 0, -1)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
flat, parents := treeOrder(toEntries(rows, site))
|
||||||
|
pages = (len(flat) + size - 1) / size
|
||||||
|
start := (n - 1) * size
|
||||||
|
if start >= len(flat) {
|
||||||
|
return []HTMLEntry{}, pages, nil
|
||||||
|
}
|
||||||
|
return nest(flat, parents, start, min(start+size, len(flat))), pages, nil
|
||||||
|
}
|
||||||
|
rows, err := h.rows(g, locale, (n-1)*size, size)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
entries := toEntries(rows, site)
|
||||||
|
out := make([]HTMLEntry, 0, len(entries))
|
||||||
|
for _, e := range entries {
|
||||||
|
out = append(out, e.HTMLEntry)
|
||||||
|
}
|
||||||
|
return out, pages, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Overview answers the HTML sitemap overview of locale: every non-empty
|
||||||
|
// group in order with its first html_page_size links and more set when it
|
||||||
|
// has more.
|
||||||
|
func (h HTMLSitemap) Overview(ctx context.Context, s models.Settings, locale string) (HTMLOverview, error) {
|
||||||
|
locale = h.locale(s, locale)
|
||||||
|
size := s.EffectiveHTMLPageSize()
|
||||||
|
out := HTMLOverview{Locale: locale, PageSize: size, Groups: []HTMLGroup{}}
|
||||||
|
groups, err := h.groups(ctx, s, locale)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
site := SiteURL(h.App, s)
|
||||||
|
for _, g := range groups {
|
||||||
|
entries, pages, err := h.page(g, locale, site, size, 1)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if len(entries) == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out.Groups = append(out.Groups, HTMLGroup{Key: g.slug, Slug: g.slug, Title: g.title, Total: g.total, More: pages > 1, Entries: entries})
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group answers page n of the group addressed by slug in locale; ok is
|
||||||
|
// false for an unknown or empty group and a page past the last.
|
||||||
|
func (h HTMLSitemap) Group(ctx context.Context, s models.Settings, locale, slug string, n int) (HTMLGroupPage, bool, error) {
|
||||||
|
locale = h.locale(s, locale)
|
||||||
|
groups, err := h.groups(ctx, s, locale)
|
||||||
|
if err != nil || n < 1 {
|
||||||
|
return HTMLGroupPage{}, false, err
|
||||||
|
}
|
||||||
|
i := slices.IndexFunc(groups, func(g htmlGroupInfo) bool { return g.slug == slug })
|
||||||
|
if i < 0 {
|
||||||
|
return HTMLGroupPage{}, false, nil
|
||||||
|
}
|
||||||
|
g := groups[i]
|
||||||
|
entries, pages, err := h.page(g, locale, SiteURL(h.App, s), s.EffectiveHTMLPageSize(), n)
|
||||||
|
if err != nil || n > pages || len(entries) == 0 {
|
||||||
|
return HTMLGroupPage{}, false, err
|
||||||
|
}
|
||||||
|
return HTMLGroupPage{Group: g.slug, Key: g.slug, Title: g.title, Locale: locale, Page: n, Pages: pages, Total: g.total, Entries: entries}, true, nil
|
||||||
|
}
|
||||||
129
classes/htmlgroups_test.go
Normal file
129
classes/htmlgroups_test.go
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestHTMLGroupOrder pins UI-SPEC L3's order of the named groups.
|
||||||
|
func TestHTMLGroupOrder(t *testing.T) {
|
||||||
|
if got := strings.Join(htmlGroupOrder, " "); got != "pages offers services categories posts tags authors" {
|
||||||
|
t.Fatalf("htmlGroupOrder = %s", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestToEntries pins the links of rows: absolute on the site, the path as
|
||||||
|
// the title when there is none, the first parent kept, and a row that
|
||||||
|
// cannot be made absolute skipped.
|
||||||
|
func TestToEntries(t *testing.T) {
|
||||||
|
refs, _ := json.Marshal([]models.Ref{{Type: "cat", ID: "1"}, {Type: "cat", ID: "9"}})
|
||||||
|
got := toEntries([]htmlRow{
|
||||||
|
{TypeKey: "cat", RecordID: "2", URL: "/kategoria/b", Title: " Bee ", ParentRefs: string(refs)},
|
||||||
|
{TypeKey: "cat", RecordID: "3", URL: "/kategoria/c"},
|
||||||
|
{TypeKey: "cat", RecordID: "4", URL: "javascript:alert(1)", Title: "x"},
|
||||||
|
{TypeKey: "cat", RecordID: "5", URL: "https://example.test/abs", Title: "Abs", ParentRefs: "[]"},
|
||||||
|
}, "https://example.test")
|
||||||
|
if len(got) != 3 {
|
||||||
|
t.Fatalf("entries = %+v, want 3 (the javascript: row skipped)", got)
|
||||||
|
}
|
||||||
|
if got[0].Title != "Bee" || got[0].URL != "https://example.test/kategoria/b" || got[0].parent == nil || *got[0].parent != (models.Ref{Type: "cat", ID: "1"}) || got[0].node != (models.Ref{Type: "cat", ID: "2"}) {
|
||||||
|
t.Fatalf("entry 0 = %+v", got[0])
|
||||||
|
}
|
||||||
|
if got[1].Title != "/kategoria/c" || got[1].parent != nil || got[2].parent != nil || got[2].URL != "https://example.test/abs" {
|
||||||
|
t.Fatalf("entries 1 and 2 = %+v %+v", got[1], got[2])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func treeEntry(id, title string, parent string) entry {
|
||||||
|
e := entry{HTMLEntry: HTMLEntry{Title: title, URL: "/" + id}, node: models.Ref{Type: "cat", ID: id}}
|
||||||
|
if parent != "" {
|
||||||
|
e.parent = &models.Ref{Type: "cat", ID: parent}
|
||||||
|
}
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestTreeOrder pins the tree order: depth first with siblings in the
|
||||||
|
// input order (alphabetical from the query), the parent indices into the
|
||||||
|
// flat result, an entry whose parent is not in the group a root, and a
|
||||||
|
// cycle broken into a root.
|
||||||
|
func TestTreeOrder(t *testing.T) {
|
||||||
|
in := []entry{
|
||||||
|
treeEntry("1", "A", ""),
|
||||||
|
treeEntry("2", "A1", "1"),
|
||||||
|
treeEntry("3", "B", ""),
|
||||||
|
treeEntry("4", "A2", "1"),
|
||||||
|
treeEntry("5", "A1a", "2"),
|
||||||
|
treeEntry("6", "Orphan", "99"),
|
||||||
|
treeEntry("7", "Self", "7"),
|
||||||
|
treeEntry("8", "Cy1", "9"),
|
||||||
|
treeEntry("9", "Cy2", "8"),
|
||||||
|
}
|
||||||
|
flat, parents := treeOrder(in)
|
||||||
|
var titles []string
|
||||||
|
for _, e := range flat {
|
||||||
|
titles = append(titles, e.Title)
|
||||||
|
}
|
||||||
|
if got := strings.Join(titles, " "); got != "A A1 A1a A2 B Orphan Self Cy1 Cy2" {
|
||||||
|
t.Fatalf("order = %s", got)
|
||||||
|
}
|
||||||
|
if fmt.Sprint(parents) != "[-1 0 1 0 -1 -1 -1 -1 7]" {
|
||||||
|
t.Fatalf("parents = %v", parents)
|
||||||
|
}
|
||||||
|
if len(flat) != len(in) {
|
||||||
|
t.Fatalf("%d entries out of %d", len(flat), len(in))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNestPaging pins the nesting of one page of the tree: a child whose
|
||||||
|
// parent is on the same page nests under it (children in order), a child
|
||||||
|
// whose parent is on an earlier page is a top-level link of its page, and
|
||||||
|
// pages cover every entry once.
|
||||||
|
func TestNestPaging(t *testing.T) {
|
||||||
|
flat, parents := treeOrder([]entry{
|
||||||
|
treeEntry("1", "A", ""),
|
||||||
|
treeEntry("2", "A1", "1"),
|
||||||
|
treeEntry("3", "A2", "1"),
|
||||||
|
treeEntry("4", "A2x", "3"),
|
||||||
|
treeEntry("5", "B", ""),
|
||||||
|
})
|
||||||
|
whole := nest(flat, parents, 0, len(flat))
|
||||||
|
if len(whole) != 2 || whole[0].Title != "A" || len(whole[0].Children) != 2 || whole[0].Children[1].Title != "A2" ||
|
||||||
|
len(whole[0].Children[1].Children) != 1 || whole[0].Children[1].Children[0].Title != "A2x" || whole[1].Title != "B" || whole[1].Children != nil {
|
||||||
|
t.Fatalf("whole tree = %+v", whole)
|
||||||
|
}
|
||||||
|
first := nest(flat, parents, 0, 2)
|
||||||
|
second := nest(flat, parents, 2, 4)
|
||||||
|
third := nest(flat, parents, 4, 5)
|
||||||
|
if len(first) != 1 || first[0].Title != "A" || len(first[0].Children) != 1 {
|
||||||
|
t.Fatalf("page 1 = %+v", first)
|
||||||
|
}
|
||||||
|
if len(second) != 1 || second[0].Title != "A2" || len(second[0].Children) != 1 || second[0].Children[0].Title != "A2x" {
|
||||||
|
t.Fatalf("page 2 = %+v, want A2 as a top-level link with its child", second)
|
||||||
|
}
|
||||||
|
if len(third) != 1 || third[0].Title != "B" {
|
||||||
|
t.Fatalf("page 3 = %+v", third)
|
||||||
|
}
|
||||||
|
if got := nest(flat, parents, 5, 5); got == nil || len(got) != 0 {
|
||||||
|
t.Fatalf("an empty page = %v, want []", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestPickTitle pins the heading per locale: the locale's, else the
|
||||||
|
// default locale's, else "".
|
||||||
|
func TestPickTitle(t *testing.T) {
|
||||||
|
titles := map[string]string{"en": "Posts", "pl": " ", "de": "Beiträge"}
|
||||||
|
for _, tc := range []struct{ locale, def, want string }{
|
||||||
|
{"de", "en", "Beiträge"}, {"pl", "en", "Posts"}, {"fr", "en", "Posts"}, {"fr", "it", ""}, {"en", "", "Posts"},
|
||||||
|
} {
|
||||||
|
if got := pickTitle(titles, tc.locale, tc.def); got != tc.want {
|
||||||
|
t.Errorf("pickTitle(%s, %s) = %q, want %q", tc.locale, tc.def, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if pickTitle(nil, "en", "en") != "" {
|
||||||
|
t.Fatal("no titles must give \"\"")
|
||||||
|
}
|
||||||
|
}
|
||||||
50
classes/images.go
Normal file
50
classes/images.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MaxImagesPerURL is the most images one <url> of an image sitemap lists
|
||||||
|
// (Google's limit).
|
||||||
|
const MaxImagesPerURL = 1000
|
||||||
|
|
||||||
|
// ImagesGroup is the file group of the image sitemaps:
|
||||||
|
// sitemap-images-<n>.xml. No content type may use it (ReservedSlugs).
|
||||||
|
const ImagesGroup = "images"
|
||||||
|
|
||||||
|
// PageImages lists the images of one locale of a record for the image
|
||||||
|
// sitemap (D-31): the featured Image first, then Images in document order,
|
||||||
|
// each a path on the site or an absolute http(s) URL (a protocol-relative
|
||||||
|
// //host/... address is read as https). Another value (a data: or
|
||||||
|
// javascript: URL, a relative path) is skipped, and an address is listed
|
||||||
|
// once, compared as absolute on site. At most MaxImagesPerURL are kept.
|
||||||
|
func PageImages(l pact.ContentLocale, site string) []string {
|
||||||
|
out := []string{}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
add := func(u string) {
|
||||||
|
u = strings.TrimSpace(u)
|
||||||
|
if strings.HasPrefix(u, "//") {
|
||||||
|
u = "https:" + u
|
||||||
|
}
|
||||||
|
if u == "" || !models.AllowedAddress(u) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
key := u
|
||||||
|
if abs := Absolute(site, u); abs != "" {
|
||||||
|
key = abs
|
||||||
|
}
|
||||||
|
if seen[key] || len(out) >= MaxImagesPerURL {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
seen[key] = true
|
||||||
|
out = append(out, u)
|
||||||
|
}
|
||||||
|
add(l.Image)
|
||||||
|
for _, img := range l.Images {
|
||||||
|
add(img.URL)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
323
classes/indexnow.go
Normal file
323
classes/indexnow.go
Normal file
@@ -0,0 +1,323 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/conga"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/fetchguard"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IndexNow (D-31, P33-14): after a rebuild the added, changed and removed
|
||||||
|
// addresses are posted to the shared IndexNow endpoint, which hands them to
|
||||||
|
// every participating engine. The endpoint is fixed, not configurable: the
|
||||||
|
// outbound client may reach that one host only (T-33-13).
|
||||||
|
const (
|
||||||
|
IndexNowKind = "golem15.sitemap.indexnow"
|
||||||
|
IndexNowHost = "api.indexnow.org"
|
||||||
|
IndexNowEndpoint = "https://" + IndexNowHost + "/indexnow"
|
||||||
|
// MaxIndexNowURLs is the most addresses one request carries.
|
||||||
|
MaxIndexNowURLs = 10000
|
||||||
|
// indexNowTimeout bounds one request.
|
||||||
|
indexNowTimeout = 10 * time.Second
|
||||||
|
// IndexNowAttempts is the attempt limit of the job: an answer of 429 or
|
||||||
|
// 5xx, or a network error, is retried by the queue up to this many times.
|
||||||
|
IndexNowAttempts = 5
|
||||||
|
)
|
||||||
|
|
||||||
|
// IndexNowArgs are the arguments of the IndexNow job: the absolute
|
||||||
|
// addresses of one request (at most MaxIndexNowURLs).
|
||||||
|
type IndexNowArgs struct {
|
||||||
|
URLs []string `json:"urls"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Kind is IndexNowKind.
|
||||||
|
func (IndexNowArgs) Kind() string { return IndexNowKind }
|
||||||
|
|
||||||
|
// keyPattern is the form of an IndexNow key: 8 to 128 letters, digits and
|
||||||
|
// hyphens (indexnow.org documentation).
|
||||||
|
var keyPattern = regexp.MustCompile(`^[A-Za-z0-9-]{8,128}$`)
|
||||||
|
|
||||||
|
// ValidKey reports whether k may be an IndexNow key.
|
||||||
|
func ValidKey(k string) bool { return keyPattern.MatchString(k) }
|
||||||
|
|
||||||
|
// GenerateKey returns a new IndexNow key: 32 lowercase hex characters from
|
||||||
|
// the system random source.
|
||||||
|
func GenerateKey() (string, error) {
|
||||||
|
var b [16]byte
|
||||||
|
if _, err := rand.Read(b[:]); err != nil {
|
||||||
|
return "", fmt.Errorf("golem15.sitemap: indexnow key: %w", err)
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(b[:]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// KeyFileName is the name of the key file of key: <key>.txt, served at the
|
||||||
|
// site root by the SEO layer (from GET /_sitemap/indexnow/<key>.txt); ""
|
||||||
|
// when key is not a ValidKey.
|
||||||
|
func KeyFileName(key string) string {
|
||||||
|
if !ValidKey(key) {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return key + ".txt"
|
||||||
|
}
|
||||||
|
|
||||||
|
// ActiveKey is the key of settings while IndexNow is on, "" otherwise.
|
||||||
|
func ActiveKey(s models.Settings) string {
|
||||||
|
if !s.IndexNowEnabled {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
if k := strings.TrimSpace(models.Text(s.IndexNowKey)); ValidKey(k) {
|
||||||
|
return k
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Production reports whether app runs in the production environment; no
|
||||||
|
// IndexNow request is sent anywhere else (T-33-15).
|
||||||
|
func Production(app *backpack.App) bool {
|
||||||
|
return app != nil && app.Config != nil && app.Config.Environment() == "production"
|
||||||
|
}
|
||||||
|
|
||||||
|
// hostOf is the lowercase host of an absolute http(s) URL, "" otherwise.
|
||||||
|
func hostOf(u string) string {
|
||||||
|
parsed, err := url.Parse(u)
|
||||||
|
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.ToLower(parsed.Hostname())
|
||||||
|
}
|
||||||
|
|
||||||
|
// SiteURLs keeps the addresses on the host of site, each once, in order:
|
||||||
|
// IndexNow refuses (422) a request with an address of another host.
|
||||||
|
func SiteURLs(site string, urls []string) []string {
|
||||||
|
host := hostOf(site)
|
||||||
|
if host == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
out := []string{}
|
||||||
|
for _, u := range urls {
|
||||||
|
if u == "" || seen[u] || hostOf(u) != host {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[u] = true
|
||||||
|
out = append(out, u)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// NotifyIndexNow queues the IndexNow job for what a rebuild changed: its
|
||||||
|
// added, changed and removed addresses on the site's host, in requests of
|
||||||
|
// at most MaxIndexNowURLs. Nothing is queued outside production, while
|
||||||
|
// IndexNow is off or has no key, without a site address or when nothing
|
||||||
|
// changed.
|
||||||
|
func NotifyIndexNow(ctx context.Context, app *backpack.App, db *gorm.DB, res RebuildResult) error {
|
||||||
|
if !Production(app) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if ActiveKey(settings) == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
all := make([]string, 0, len(res.Added)+len(res.Changed)+len(res.Removed))
|
||||||
|
all = append(append(append(all, res.Added...), res.Changed...), res.Removed...)
|
||||||
|
urls := SiteURLs(SiteURL(app, settings), all)
|
||||||
|
if len(urls) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
m, err := conga.From(app)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for _, batch := range indexNowBatches(urls) {
|
||||||
|
if err := m.Enqueue(ctx, db, IndexNowArgs{URLs: batch}, conga.EnqueueOpts{}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// indexNowBatches splits urls into requests of at most MaxIndexNowURLs, in
|
||||||
|
// order.
|
||||||
|
func indexNowBatches(urls []string) [][]string {
|
||||||
|
var out [][]string
|
||||||
|
for start := 0; start < len(urls); start += MaxIndexNowURLs {
|
||||||
|
out = append(out, urls[start:min(start+MaxIndexNowURLs, len(urls))])
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// indexNowBody is the JSON of an IndexNow request. keyLocation is not sent:
|
||||||
|
// the key file is served at the site root, which covers every address of
|
||||||
|
// the host (P33-14).
|
||||||
|
type indexNowBody struct {
|
||||||
|
Host string `json:"host"`
|
||||||
|
Key string `json:"key"`
|
||||||
|
URLList []string `json:"urlList"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// errIndexNowRetry is a retryable IndexNow answer.
|
||||||
|
type errIndexNowRetry struct{ status int }
|
||||||
|
|
||||||
|
func (e errIndexNowRetry) Error() string {
|
||||||
|
return fmt.Sprintf("golem15.sitemap: indexnow answered %d; retrying", e.status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendIndexNow runs one IndexNow job: it posts {host, key, urlList} to
|
||||||
|
// IndexNowEndpoint through a fetchguard client that reaches that host only
|
||||||
|
// (HTTPS, no redirects) and records the answer (indexnow_last_at, _count,
|
||||||
|
// _status). 200 and 202 are success; 400, 403 and 422 are recorded and not
|
||||||
|
// retried; 429 and 5xx are recorded and returned as an error, so the queue
|
||||||
|
// retries the job. Outside production, while IndexNow is off or without a
|
||||||
|
// site address nothing is sent; addresses of another host never are.
|
||||||
|
func SendIndexNow(ctx context.Context, app *backpack.App, args IndexNowArgs) error {
|
||||||
|
if !Production(app) {
|
||||||
|
pluginLog.Info("golem15.sitemap: indexnow skipped outside production", "urls", len(args.URLs))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
db, ok := app.Lookup[*gorm.DB]()
|
||||||
|
if !ok || db == nil {
|
||||||
|
return ErrNoDatabase
|
||||||
|
}
|
||||||
|
db = db.WithContext(ctx)
|
||||||
|
settings, err := LoadSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
key := ActiveKey(settings)
|
||||||
|
site := SiteURL(app, settings)
|
||||||
|
urls := SiteURLs(site, args.URLs)
|
||||||
|
if key == "" || len(urls) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if len(urls) > MaxIndexNowURLs {
|
||||||
|
urls = urls[:MaxIndexNowURLs]
|
||||||
|
}
|
||||||
|
client, err := fetchguard.NewClient(fetchguard.Policy{
|
||||||
|
Mode: fetchguard.AllowHostsMode,
|
||||||
|
AllowHosts: []string{IndexNowHost},
|
||||||
|
Timeout: indexNowTimeout,
|
||||||
|
}, app.Config)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
res, err := client.PostJSON(ctx, IndexNowEndpoint, nil, indexNowBody{Host: hostOf(site), Key: key, URLList: urls})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
status := res.StatusCode
|
||||||
|
if err := db.Exec(`UPDATE golem15_sitemap_settings SET indexnow_last_at = ?, indexnow_last_count = ?, indexnow_last_status = ? WHERE id = 1`,
|
||||||
|
time.Now().UTC(), len(urls), status).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch indexNowOutcome(status) {
|
||||||
|
case indexNowSent:
|
||||||
|
pluginLog.Info("golem15.sitemap: indexnow notified", "urls", len(urls), "status", status)
|
||||||
|
return nil
|
||||||
|
case indexNowRetry:
|
||||||
|
pluginLog.Warn("golem15.sitemap: indexnow will retry", "urls", len(urls), "status", status)
|
||||||
|
return errIndexNowRetry{status: status}
|
||||||
|
default:
|
||||||
|
pluginLog.Warn("golem15.sitemap: indexnow refused", "urls", len(urls), "status", status)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The outcomes of an IndexNow answer.
|
||||||
|
const (
|
||||||
|
indexNowSent = iota
|
||||||
|
indexNowRetry
|
||||||
|
indexNowRefused
|
||||||
|
)
|
||||||
|
|
||||||
|
// indexNowOutcome maps an IndexNow answer's status: 200 and 202 are sent,
|
||||||
|
// 429 and 5xx are retried, everything else (400, 403, 422) is refused and
|
||||||
|
// not retried.
|
||||||
|
func indexNowOutcome(status int) int {
|
||||||
|
switch {
|
||||||
|
case status == http.StatusOK || status == http.StatusAccepted:
|
||||||
|
return indexNowSent
|
||||||
|
case status == http.StatusTooManyRequests || status >= 500:
|
||||||
|
return indexNowRetry
|
||||||
|
}
|
||||||
|
return indexNowRefused
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnsureKey gives settings row 1 an IndexNow key on save: while enabled,
|
||||||
|
// a new key is generated when none is stored or rotate is set (the
|
||||||
|
// indexnow_new_key checkbox), so the old key file answers 404 at once. It
|
||||||
|
// returns the stored key ("" while disabled without one).
|
||||||
|
func EnsureKey(db *gorm.DB, enabled, rotate bool) (string, error) {
|
||||||
|
settings, err := LoadSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
current := strings.TrimSpace(models.Text(settings.IndexNowKey))
|
||||||
|
if !enabled || (ValidKey(current) && !rotate) {
|
||||||
|
return current, nil
|
||||||
|
}
|
||||||
|
key, err := GenerateKey()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := db.Exec(`UPDATE golem15_sitemap_settings SET indexnow_key = ? WHERE id = 1`, key).Error; err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return key, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IndexNowRetryAt is when the queue next tries a pending IndexNow job
|
||||||
|
// (after a 429 or 5xx answer), nil when none is pending.
|
||||||
|
func IndexNowRetryAt(db *gorm.DB) *time.Time {
|
||||||
|
var at []time.Time
|
||||||
|
if err := db.Raw(`SELECT scheduled_at FROM river_job WHERE kind = ? AND state IN ('retryable', 'scheduled', 'available') ORDER BY scheduled_at ASC LIMIT 1`, IndexNowKind).Scan(&at).Error; err != nil || len(at) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
t := at[0].UTC()
|
||||||
|
return &t
|
||||||
|
}
|
||||||
|
|
||||||
|
// IndexNowStatus is the state the S2 partial and the management API show:
|
||||||
|
// the key and its public URL (empty before a key exists), the last
|
||||||
|
// notification (nil before the first) and, after a 429, the next attempt.
|
||||||
|
type IndexNowStatus struct {
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
Key string `json:"key"`
|
||||||
|
KeyURL string `json:"key_url"`
|
||||||
|
LastAt *time.Time `json:"last_at"`
|
||||||
|
LastCount int `json:"last_count"`
|
||||||
|
LastStatus int `json:"last_status"`
|
||||||
|
RetryAt *time.Time `json:"retry_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadIndexNowStatus reads the IndexNow state of settings.
|
||||||
|
func LoadIndexNowStatus(db *gorm.DB, app *backpack.App, s models.Settings) IndexNowStatus {
|
||||||
|
out := IndexNowStatus{Enabled: s.IndexNowEnabled, LastAt: s.IndexNowLastAt}
|
||||||
|
if k := strings.TrimSpace(models.Text(s.IndexNowKey)); ValidKey(k) {
|
||||||
|
out.Key = k
|
||||||
|
out.KeyURL = SiteURL(app, s) + "/" + KeyFileName(k)
|
||||||
|
}
|
||||||
|
if s.IndexNowLastCount != nil {
|
||||||
|
out.LastCount = *s.IndexNowLastCount
|
||||||
|
}
|
||||||
|
if s.IndexNowLastStatus != nil {
|
||||||
|
out.LastStatus = *s.IndexNowLastStatus
|
||||||
|
}
|
||||||
|
if out.LastStatus == http.StatusTooManyRequests {
|
||||||
|
out.RetryAt = IndexNowRetryAt(db)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
112
classes/indexnow_test.go
Normal file
112
classes/indexnow_test.go
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestIndexNowBatches pins the requests of at most 10 000 addresses, in
|
||||||
|
// order, with nothing for no addresses.
|
||||||
|
func TestIndexNowBatches(t *testing.T) {
|
||||||
|
if MaxIndexNowURLs != 10000 {
|
||||||
|
t.Fatalf("MaxIndexNowURLs = %d", MaxIndexNowURLs)
|
||||||
|
}
|
||||||
|
urls := func(n int) []string {
|
||||||
|
out := make([]string, n)
|
||||||
|
for i := range out {
|
||||||
|
out[i] = fmt.Sprintf("https://example.test/%d", i)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
n int
|
||||||
|
want []int
|
||||||
|
}{{0, nil}, {1, []int{1}}, {10000, []int{10000}}, {10001, []int{10000, 1}}, {25000, []int{10000, 10000, 5000}}} {
|
||||||
|
got := indexNowBatches(urls(tc.n))
|
||||||
|
var sizes []int
|
||||||
|
next := 0
|
||||||
|
for _, b := range got {
|
||||||
|
sizes = append(sizes, len(b))
|
||||||
|
if len(b) > 0 && b[0] != fmt.Sprintf("https://example.test/%d", next) {
|
||||||
|
t.Fatalf("%d addresses: a batch starts at %s, want %d", tc.n, b[0], next)
|
||||||
|
}
|
||||||
|
next += len(b)
|
||||||
|
}
|
||||||
|
if fmt.Sprint(sizes) != fmt.Sprint(tc.want) {
|
||||||
|
t.Errorf("%d addresses: batches %v, want %v", tc.n, sizes, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestIndexNowOutcome pins the answer mapping: 200 and 202 sent, 429 and
|
||||||
|
// 5xx retried, 400, 403 and 422 (and any other status) refused.
|
||||||
|
func TestIndexNowOutcome(t *testing.T) {
|
||||||
|
for status, want := range map[int]int{
|
||||||
|
http.StatusOK: indexNowSent, http.StatusAccepted: indexNowSent,
|
||||||
|
http.StatusTooManyRequests: indexNowRetry, 500: indexNowRetry, 502: indexNowRetry, 503: indexNowRetry,
|
||||||
|
http.StatusBadRequest: indexNowRefused, http.StatusForbidden: indexNowRefused, http.StatusUnprocessableEntity: indexNowRefused,
|
||||||
|
http.StatusNoContent: indexNowRefused, http.StatusNotFound: indexNowRefused,
|
||||||
|
} {
|
||||||
|
if got := indexNowOutcome(status); got != want {
|
||||||
|
t.Errorf("status %d: outcome %d, want %d", status, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestIndexNowKeys pins the key format (8 to 128 letters, digits and
|
||||||
|
// hyphens), the generated key (32 lowercase hex characters, a new one each
|
||||||
|
// time), the key file name and the active key only while IndexNow is on.
|
||||||
|
func TestIndexNowKeys(t *testing.T) {
|
||||||
|
for k, want := range map[string]bool{
|
||||||
|
"abcd1234": true, "ABCD-1234-efgh": true, strings.Repeat("a", 128): true,
|
||||||
|
"abc1234": false, strings.Repeat("a", 129): false, "abcd_1234": false, "abcd 1234": false, "../abcd1234": false, "": false,
|
||||||
|
} {
|
||||||
|
if ValidKey(k) != want {
|
||||||
|
t.Errorf("ValidKey(%q) = %v, want %v", k, !want, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a, err := GenerateKey()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
b, _ := GenerateKey()
|
||||||
|
if !regexp.MustCompile(`^[0-9a-f]{32}$`).MatchString(a) || a == b || !ValidKey(a) {
|
||||||
|
t.Fatalf("GenerateKey = %q, %q", a, b)
|
||||||
|
}
|
||||||
|
if KeyFileName(a) != a+".txt" || KeyFileName("short") != "" || KeyFileName("x/../y12345") != "" {
|
||||||
|
t.Fatal("KeyFileName is wrong")
|
||||||
|
}
|
||||||
|
key := " " + a + " "
|
||||||
|
bad := "bad key"
|
||||||
|
if ActiveKey(models.Settings{IndexNowEnabled: true, IndexNowKey: &key}) != a ||
|
||||||
|
ActiveKey(models.Settings{IndexNowEnabled: false, IndexNowKey: &key}) != "" ||
|
||||||
|
ActiveKey(models.Settings{IndexNowEnabled: true, IndexNowKey: &bad}) != "" ||
|
||||||
|
ActiveKey(models.Settings{IndexNowEnabled: true}) != "" {
|
||||||
|
t.Fatal("ActiveKey is wrong")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSiteURLs pins the host filter: only http(s) addresses on the site's
|
||||||
|
// host (case-insensitive, any port or scheme), each once, in order;
|
||||||
|
// nothing without a site address.
|
||||||
|
func TestSiteURLs(t *testing.T) {
|
||||||
|
got := SiteURLs("https://Example.test", []string{
|
||||||
|
"https://example.test/a", "https://EXAMPLE.test/b", "http://example.test/c", "https://example.test:8443/d",
|
||||||
|
"https://example.test/a", "https://www.example.test/e", "https://other.test/f", "/g", "ftp://example.test/h", "",
|
||||||
|
})
|
||||||
|
want := "https://example.test/a https://EXAMPLE.test/b http://example.test/c https://example.test:8443/d"
|
||||||
|
if strings.Join(got, " ") != want {
|
||||||
|
t.Fatalf("SiteURLs = %v, want %s", got, want)
|
||||||
|
}
|
||||||
|
if SiteURLs("", []string{"https://example.test/a"}) != nil || SiteURLs("/relative", []string{"/a"}) != nil {
|
||||||
|
t.Fatal("without a site address nothing is kept")
|
||||||
|
}
|
||||||
|
if got := SiteURLs("https://example.test", nil); got == nil || len(got) != 0 {
|
||||||
|
t.Fatalf("no addresses: %v, want an empty list", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
219
classes/lastmod.go
Normal file
219
classes/lastmod.go
Normal file
@@ -0,0 +1,219 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/conga"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/signpost"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The config keys of the event-driven lastmod and the debounced rebuild.
|
||||||
|
const (
|
||||||
|
// LastmodIgnoreConfigKey lists the attributes whose change does not
|
||||||
|
// move lastmod.
|
||||||
|
LastmodIgnoreConfigKey = "golem15.sitemap.lastmod_ignore"
|
||||||
|
// RebuildDelayConfigKey is the delay of the rebuild a record event
|
||||||
|
// queues, in seconds.
|
||||||
|
RebuildDelayConfigKey = "golem15.sitemap.rebuild_delay_seconds"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultLastmodIgnore is the ignore list when the config has none.
|
||||||
|
var DefaultLastmodIgnore = []string{"updated_at", "created_at", "views", "sort_order"}
|
||||||
|
|
||||||
|
// defaultRebuildDelay is the rebuild delay when the config has none.
|
||||||
|
const defaultRebuildDelay = 60 * time.Second
|
||||||
|
|
||||||
|
// LastmodIgnore reads golem15.sitemap.lastmod_ignore: a list of attribute
|
||||||
|
// names (or one comma-separated string); DefaultLastmodIgnore when unset.
|
||||||
|
func LastmodIgnore(cfg *compass.Config) map[string]bool {
|
||||||
|
names := DefaultLastmodIgnore
|
||||||
|
if cfg != nil {
|
||||||
|
if v, ok := cfg.Lookup(LastmodIgnoreConfigKey); ok && v != nil {
|
||||||
|
names = nil
|
||||||
|
switch list := v.(type) {
|
||||||
|
case []any:
|
||||||
|
for _, item := range list {
|
||||||
|
names = append(names, fmt.Sprint(item))
|
||||||
|
}
|
||||||
|
case []string:
|
||||||
|
names = list
|
||||||
|
case string:
|
||||||
|
names = strings.Split(list, ",")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := make(map[string]bool, len(names))
|
||||||
|
for _, n := range names {
|
||||||
|
if n = strings.TrimSpace(n); n != "" {
|
||||||
|
out[n] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// RebuildDelay reads golem15.sitemap.rebuild_delay_seconds; 60 seconds when
|
||||||
|
// unset, 0 or more when set.
|
||||||
|
func RebuildDelay(cfg *compass.Config) time.Duration {
|
||||||
|
if cfg == nil || !cfg.Has(RebuildDelayConfigKey) {
|
||||||
|
return defaultRebuildDelay
|
||||||
|
}
|
||||||
|
if n := cfg.Int(RebuildDelayConfigKey); n > 0 {
|
||||||
|
return time.Duration(n) * time.Second
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Changed is what a save changed for lastmod: Any when a change outside the
|
||||||
|
// ignore list exists, All when one of them is on the record's own row
|
||||||
|
// (every locale's address moves), else Locales names the translated
|
||||||
|
// locales that changed.
|
||||||
|
type Changed struct {
|
||||||
|
Any bool
|
||||||
|
All bool
|
||||||
|
Locales map[string]bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// RealChanges filters a save's changes through the ignore list. A no-op
|
||||||
|
// save (no changes) and one that changes only ignored attributes change
|
||||||
|
// nothing (RESEARCH Pitfall 4).
|
||||||
|
func RealChanges(changes []pact.RecordChange, ignore map[string]bool) Changed {
|
||||||
|
out := Changed{Locales: map[string]bool{}}
|
||||||
|
for _, c := range changes {
|
||||||
|
if ignore[c.Attribute] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out.Any = true
|
||||||
|
if c.Locale == "" {
|
||||||
|
out.All = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out.Locales[c.Locale] = true
|
||||||
|
}
|
||||||
|
if out.All {
|
||||||
|
out.Locales = map[string]bool{}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecordSaved handles a saved record of a content type (D-30): when the
|
||||||
|
// save changed an attribute outside golem15.sitemap.lastmod_ignore, the
|
||||||
|
// lastmod of the record's rows moves to now (every locale's for a change
|
||||||
|
// on the record's own row, else only the changed locales'), the same rows
|
||||||
|
// are marked for IndexNow (indexnow_pending_at, D-31: the next rebuild
|
||||||
|
// sends the listed ones as changed), and a debounced rebuild is queued. A
|
||||||
|
// model no content type declares, or a nil event, is ignored.
|
||||||
|
func RecordSaved(ctx context.Context, app *backpack.App, ev *pact.RecordSaved) error {
|
||||||
|
if ev == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
typ, db, ok := contentTypeOf(app, ev.Model)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
changed := RealChanges(ev.Changes, LastmodIgnore(app.Config))
|
||||||
|
if !changed.Any {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
db = db.WithContext(ctx)
|
||||||
|
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||||
|
q := db.Model(&models.URL{}).Where("type_key = ? AND record_id = ?", typ, ev.ID)
|
||||||
|
if !changed.All {
|
||||||
|
locales := make([]string, 0, len(changed.Locales))
|
||||||
|
for l := range changed.Locales {
|
||||||
|
locales = append(locales, l)
|
||||||
|
}
|
||||||
|
q = q.Where("locale IN ?", locales)
|
||||||
|
}
|
||||||
|
if err := q.Updates(map[string]any{"lastmod": now, "updated_at": now, "indexnow_pending_at": now}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return RequestDebouncedRebuild(ctx, app, db)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecordDeleted handles a deleted record of a content type: its rows leave
|
||||||
|
// the files at once (reason deleted, their file numbers kept as holes),
|
||||||
|
// those that were listed are marked for IndexNow in the same update
|
||||||
|
// (indexnow_pending_at, D-31: the next rebuild sends them as removed), and
|
||||||
|
// a debounced rebuild is queued.
|
||||||
|
func RecordDeleted(ctx context.Context, app *backpack.App, ev *pact.RecordDeleted) error {
|
||||||
|
if ev == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
typ, db, ok := contentTypeOf(app, ev.Model)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
db = db.WithContext(ctx)
|
||||||
|
now := time.Now().UTC()
|
||||||
|
if err := db.Model(&models.URL{}).
|
||||||
|
Where("type_key = ? AND record_id = ? AND excluded_reason <> ?", typ, ev.ID, models.ReasonDeleted).
|
||||||
|
Updates(map[string]any{
|
||||||
|
"excluded_reason": models.ReasonDeleted,
|
||||||
|
"updated_at": now,
|
||||||
|
"indexnow_pending_at": gorm.Expr("CASE WHEN excluded_reason = '' THEN ?::timestamptz ELSE indexnow_pending_at END", now),
|
||||||
|
}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return RequestDebouncedRebuild(ctx, app, db)
|
||||||
|
}
|
||||||
|
|
||||||
|
// contentTypeOf finds the content type key of a record event's model and
|
||||||
|
// the application database.
|
||||||
|
func contentTypeOf(app *backpack.App, model string) (string, *gorm.DB, bool) {
|
||||||
|
if app == nil {
|
||||||
|
return "", nil, false
|
||||||
|
}
|
||||||
|
reg, ok := app.Lookup[*signpost.Registry]()
|
||||||
|
if !ok || reg == nil {
|
||||||
|
return "", nil, false
|
||||||
|
}
|
||||||
|
typ, ok := reg.ContentTypeForModel(model)
|
||||||
|
if !ok || typ.Content == nil {
|
||||||
|
return "", nil, false
|
||||||
|
}
|
||||||
|
db, ok := app.Lookup[*gorm.DB]()
|
||||||
|
if !ok || db == nil {
|
||||||
|
return "", nil, false
|
||||||
|
}
|
||||||
|
return typ.Key, db, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequestDebouncedRebuild queues one rebuild golem15.sitemap.rebuild_delay_seconds
|
||||||
|
// from now unless one is already pending (P33-12): a conditional UPDATE of
|
||||||
|
// rebuild_pending_until decides, and the job is enqueued in the same
|
||||||
|
// transaction, so events within the delay share one rebuild. The job
|
||||||
|
// clears the pending time when it starts.
|
||||||
|
func RequestDebouncedRebuild(ctx context.Context, app *backpack.App, db *gorm.DB) error {
|
||||||
|
delay := RebuildDelay(app.Config)
|
||||||
|
m, err := conga.From(app)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
|
res := tx.Exec(`UPDATE golem15_sitemap_settings
|
||||||
|
SET rebuild_pending_until = NOW() + make_interval(secs => ?)
|
||||||
|
WHERE id = 1 AND (rebuild_pending_until IS NULL OR rebuild_pending_until <= NOW())`, delay.Seconds())
|
||||||
|
if res.Error != nil || res.RowsAffected == 0 {
|
||||||
|
return res.Error
|
||||||
|
}
|
||||||
|
return m.Enqueue(ctx, tx, RebuildArgs{}, conga.EnqueueOpts{Delay: delay})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClearPending ends the debounce window; the rebuild job calls it when it
|
||||||
|
// starts, so events during the rebuild queue the next one.
|
||||||
|
func ClearPending(ctx context.Context, app *backpack.App) error {
|
||||||
|
db, ok := app.Lookup[*gorm.DB]()
|
||||||
|
if !ok || db == nil {
|
||||||
|
return ErrNoDatabase
|
||||||
|
}
|
||||||
|
return db.WithContext(ctx).Exec(`UPDATE golem15_sitemap_settings SET rebuild_pending_until = NULL WHERE id = 1`).Error
|
||||||
|
}
|
||||||
113
classes/lastmod_test.go
Normal file
113
classes/lastmod_test.go
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestRealChanges pins which saves move lastmod (D-30, RESEARCH Pitfall
|
||||||
|
// 4): nothing for an empty or ignored-only change list; every locale for a
|
||||||
|
// change on the record's own row; only the named locales for translated
|
||||||
|
// changes.
|
||||||
|
func TestRealChanges(t *testing.T) {
|
||||||
|
ignore := map[string]bool{"updated_at": true, "views": true}
|
||||||
|
for name, c := range map[string]struct {
|
||||||
|
changes []pact.RecordChange
|
||||||
|
any bool
|
||||||
|
all bool
|
||||||
|
locales []string
|
||||||
|
}{
|
||||||
|
"no-op save": {nil, false, false, nil},
|
||||||
|
"ignored only": {[]pact.RecordChange{{Attribute: "updated_at"}, {Attribute: "views"}}, false, false, nil},
|
||||||
|
"own row": {[]pact.RecordChange{{Attribute: "updated_at"}, {Attribute: "title"}}, true, true, nil},
|
||||||
|
"translated": {[]pact.RecordChange{{Attribute: "title", Locale: "pl"}, {Attribute: "slug", Locale: "de"}}, true, false, []string{"de", "pl"}},
|
||||||
|
"both": {[]pact.RecordChange{{Attribute: "title", Locale: "pl"}, {Attribute: "content"}}, true, true, nil},
|
||||||
|
} {
|
||||||
|
got := RealChanges(c.changes, ignore)
|
||||||
|
if got.Any != c.any || got.All != c.all || len(got.Locales) != len(c.locales) {
|
||||||
|
t.Errorf("%s: %+v", name, got)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, l := range c.locales {
|
||||||
|
if !got.Locales[l] {
|
||||||
|
t.Errorf("%s: locale %s missing in %+v", name, l, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLastmodIgnore pins golem15.sitemap.lastmod_ignore: the default list
|
||||||
|
// when unset, a YAML list or a comma-separated string replacing it (names
|
||||||
|
// trimmed, blanks dropped), and an empty list ignoring nothing.
|
||||||
|
func TestLastmodIgnore(t *testing.T) {
|
||||||
|
keys := func(m map[string]bool) string {
|
||||||
|
out := make([]string, 0, len(m))
|
||||||
|
for k := range m {
|
||||||
|
out = append(out, k)
|
||||||
|
}
|
||||||
|
slices.Sort(out)
|
||||||
|
return strings.Join(out, ",")
|
||||||
|
}
|
||||||
|
if got := keys(LastmodIgnore(nil)); got != "created_at,sort_order,updated_at,views" {
|
||||||
|
t.Fatalf("default = %s", got)
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
value any
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{[]any{"updated_at", " hits ", ""}, "hits,updated_at"},
|
||||||
|
{[]string{"a", "b"}, "a,b"},
|
||||||
|
{" views , rank,,", "rank,views"},
|
||||||
|
{[]any{}, ""},
|
||||||
|
} {
|
||||||
|
cfg := testConfig(t)
|
||||||
|
if err := cfg.Set(LastmodIgnoreConfigKey, tc.value); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := keys(LastmodIgnore(cfg)); got != tc.want {
|
||||||
|
t.Errorf("LastmodIgnore(%#v) = %s, want %s", tc.value, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRebuildDelay pins golem15.sitemap.rebuild_delay_seconds: 60 s when
|
||||||
|
// unset, the value in seconds, and 0 for 0 or a negative value.
|
||||||
|
func TestRebuildDelay(t *testing.T) {
|
||||||
|
if RebuildDelay(nil) != time.Minute || RebuildDelay(testConfig(t)) != time.Minute {
|
||||||
|
t.Fatal("default delay is not 60 s")
|
||||||
|
}
|
||||||
|
for value, want := range map[int]time.Duration{5: 5 * time.Second, 0: 0, -3: 0} {
|
||||||
|
cfg := testConfig(t)
|
||||||
|
if err := cfg.Set(RebuildDelayConfigKey, value); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := RebuildDelay(cfg); got != want {
|
||||||
|
t.Errorf("RebuildDelay(%d) = %s, want %s", value, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testConfig(t *testing.T) *compass.Config {
|
||||||
|
t.Helper()
|
||||||
|
cfg, err := compass.Open(compass.Options{Dir: t.TempDir()})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRecordSavedNilEvent pins L2 IN-01: a nil event is ignored before it
|
||||||
|
// is read.
|
||||||
|
func TestRecordSavedNilEvent(t *testing.T) {
|
||||||
|
if err := RecordSaved(t.Context(), nil, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := RecordDeleted(t.Context(), nil, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
166
classes/listing.go
Normal file
166
classes/listing.go
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/contract"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/signpost"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Listing implements contract.Listing over the slot table and the
|
||||||
|
// settings (D-95): other plugins read the site address, the index address,
|
||||||
|
// the file groups and each group's listed addresses without importing the
|
||||||
|
// sitemap plugin.
|
||||||
|
type Listing struct {
|
||||||
|
App *backpack.App
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
_ contract.Listing = Listing{}
|
||||||
|
_ contract.Rebuilder = Listing{}
|
||||||
|
)
|
||||||
|
|
||||||
|
// The page sizes of Entries.
|
||||||
|
const (
|
||||||
|
defaultEntriesLimit = 100
|
||||||
|
maxEntriesLimit = 1000
|
||||||
|
)
|
||||||
|
|
||||||
|
func (l Listing) db(ctx context.Context) (*gorm.DB, error) {
|
||||||
|
if l.App == nil {
|
||||||
|
return nil, ErrNoDatabase
|
||||||
|
}
|
||||||
|
db, ok := l.App.Lookup[*gorm.DB]()
|
||||||
|
if !ok || db == nil {
|
||||||
|
return nil, ErrNoDatabase
|
||||||
|
}
|
||||||
|
return db.WithContext(ctx), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RequestRebuild queues one debounced rebuild through
|
||||||
|
// RequestDebouncedRebuild, the same one a record event queues
|
||||||
|
// (contract.Rebuilder).
|
||||||
|
func (l Listing) RequestRebuild(ctx context.Context) error {
|
||||||
|
db, err := l.db(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return RequestDebouncedRebuild(ctx, l.App, db)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Settings answers the site address, the index address, the default
|
||||||
|
// locale and the groups with listed addresses (by key), with their titles
|
||||||
|
// (a content type's saved HTML sitemap headings, else the titles of the
|
||||||
|
// published Filter's group of that key), the HTML sitemap settings and the
|
||||||
|
// IndexNow key file name (while IndexNow is on with a key), and the
|
||||||
|
// content types switched off.
|
||||||
|
func (l Listing) Settings(ctx context.Context) (contract.ListingSettings, error) {
|
||||||
|
var out contract.ListingSettings
|
||||||
|
db, err := l.db(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.SiteURL = SiteURL(l.App, settings)
|
||||||
|
if out.SiteURL != "" {
|
||||||
|
out.IndexURL = out.SiteURL + "/sitemap.xml"
|
||||||
|
}
|
||||||
|
out.DefaultLocale = models.Text(settings.DefaultLocale)
|
||||||
|
var counts []struct {
|
||||||
|
Grp string `gorm:"column:grp"`
|
||||||
|
N int `gorm:"column:n"`
|
||||||
|
}
|
||||||
|
if err := db.Raw(`SELECT grp, COUNT(*) AS n FROM golem15_sitemap_urls WHERE excluded_reason = '' GROUP BY grp ORDER BY grp`).Scan(&counts).Error; err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
titles, _, _, err := groupTitles(ctx, l.App, db)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
out.Groups = make([]contract.GroupInfo, 0, len(counts))
|
||||||
|
for _, c := range counts {
|
||||||
|
out.Groups = append(out.Groups, contract.GroupInfo{Key: c.Grp, Slug: c.Grp, Titles: titles[c.Grp], Count: c.N})
|
||||||
|
}
|
||||||
|
out.HTMLEnabled = settings.HTMLEnabled
|
||||||
|
out.HTMLPaths = settings.EffectiveHTMLPaths()
|
||||||
|
out.HTMLPageSize = settings.EffectiveHTMLPageSize()
|
||||||
|
out.KeyFile = KeyFileName(ActiveKey(settings))
|
||||||
|
out.TypesOff = []string{}
|
||||||
|
if reg, ok := l.App.Lookup[*signpost.Registry](); ok && reg != nil {
|
||||||
|
rows, err := LoadTypeSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
for _, typ := range reg.ContentTypes() {
|
||||||
|
if !EffectiveType(typ, rows).Include {
|
||||||
|
out.TypesOff = append(out.TypesOff, typ.Key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entries pages a group's listed addresses in the order they were stored
|
||||||
|
// (row id); Next is the last row id of a page that has a successor. A
|
||||||
|
// Locale keeps the addresses of that locale and those without one.
|
||||||
|
func (l Listing) Entries(ctx context.Context, q contract.EntriesQuery) (contract.EntriesPage, error) {
|
||||||
|
page := contract.EntriesPage{Entries: []contract.Entry{}}
|
||||||
|
db, err := l.db(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return page, err
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return page, err
|
||||||
|
}
|
||||||
|
site := SiteURL(l.App, settings)
|
||||||
|
limit := q.Limit
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = defaultEntriesLimit
|
||||||
|
}
|
||||||
|
limit = min(limit, maxEntriesLimit)
|
||||||
|
scope := func() *gorm.DB {
|
||||||
|
s := db.Model(&models.URL{}).Where("grp = ? AND excluded_reason = ''", q.Group)
|
||||||
|
if loc := strings.TrimSpace(q.Locale); loc != "" {
|
||||||
|
s = s.Where("locale = ? OR locale = ''", loc)
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
var total int64
|
||||||
|
if err := scope().Count(&total).Error; err != nil {
|
||||||
|
return page, err
|
||||||
|
}
|
||||||
|
page.Total = int(total)
|
||||||
|
q2 := scope()
|
||||||
|
if after, err := strconv.ParseUint(strings.TrimSpace(q.After), 10, 64); err == nil && after > 0 {
|
||||||
|
q2 = q2.Where("id > ?", after)
|
||||||
|
}
|
||||||
|
var rows []models.URL
|
||||||
|
if err := q2.Order("id ASC").Limit(limit + 1).Find(&rows).Error; err != nil {
|
||||||
|
return page, err
|
||||||
|
}
|
||||||
|
if len(rows) > limit {
|
||||||
|
rows = rows[:limit]
|
||||||
|
page.Next = strconv.FormatUint(rows[len(rows)-1].ID, 10)
|
||||||
|
}
|
||||||
|
for _, r := range rows {
|
||||||
|
page.Entries = append(page.Entries, contract.Entry{
|
||||||
|
Group: r.Grp,
|
||||||
|
TypeKey: r.TypeKey,
|
||||||
|
RecordID: r.RecordID,
|
||||||
|
Locale: r.Locale,
|
||||||
|
URL: Absolute(site, r.URL),
|
||||||
|
Title: r.Title,
|
||||||
|
LastMod: r.LastMod,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
package classes
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ManifestMaxBytes is the largest updates manifest the sitemap reads.
|
|
||||||
const ManifestMaxBytes = 5 << 20
|
|
||||||
|
|
||||||
// Manifest maps a normalized URL path to its last-modified date text, the
|
|
||||||
// updates manifest a frontend build writes.
|
|
||||||
type Manifest map[string]string
|
|
||||||
|
|
||||||
// LoadManifest reads the updates manifest at path: a regular file of at
|
|
||||||
// most ManifestMaxBytes holding a JSON object of URL path to date. It fails
|
|
||||||
// safe like PHP: an empty path, a missing, unreadable, oversized or invalid
|
|
||||||
// file is no manifest (nil), logged without the file's content. Keys are
|
|
||||||
// normalized like PHP normalizeManifestPath; values that are not strings are
|
|
||||||
// ignored.
|
|
||||||
func LoadManifest(path string) Manifest {
|
|
||||||
path = strings.TrimSpace(path)
|
|
||||||
if path == "" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
info, err := os.Stat(path)
|
|
||||||
if err != nil || !info.Mode().IsRegular() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if info.Size() > ManifestMaxBytes {
|
|
||||||
pluginLog.Warn("golem15.sitemap: updates manifest is too large; lastmod omitted", "path", path, "max_bytes", ManifestMaxBytes)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
f, err := os.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
raw, err := io.ReadAll(io.LimitReader(f, ManifestMaxBytes+1))
|
|
||||||
if err != nil || len(raw) > ManifestMaxBytes {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
raw = bytes.TrimSpace(raw)
|
|
||||||
var decoded map[string]any
|
|
||||||
if len(raw) == 0 || raw[0] != '{' || json.Unmarshal(raw, &decoded) != nil {
|
|
||||||
pluginLog.Warn("golem15.sitemap: updates manifest is not a JSON object; lastmod omitted", "path", path)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
m := Manifest{}
|
|
||||||
for key, value := range decoded {
|
|
||||||
if s, ok := value.(string); ok {
|
|
||||||
m[normalizeManifestPath(key)] = s
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
|
|
||||||
// normalizeManifestPath is PHP normalizeManifestPath: a leading slash, no
|
|
||||||
// trailing slash except for the root.
|
|
||||||
func normalizeManifestPath(path string) string {
|
|
||||||
path = "/" + strings.TrimLeft(path, "/")
|
|
||||||
if path == "/" {
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
return strings.TrimRight(path, "/")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Lastmod is PHP lookupManifestLastmod: the date listed for the URL's path,
|
|
||||||
// parsed like the ISO 8601 forms strtotime reads (a date without a zone is
|
|
||||||
// UTC). ok is false when the path is not listed or its date does not parse.
|
|
||||||
func (m Manifest) Lastmod(url string) (time.Time, bool) {
|
|
||||||
if len(m) == 0 {
|
|
||||||
return time.Time{}, false
|
|
||||||
}
|
|
||||||
path := URLPath(url)
|
|
||||||
if path == "" {
|
|
||||||
path = "/"
|
|
||||||
}
|
|
||||||
text, ok := m[normalizeManifestPath(path)]
|
|
||||||
if !ok {
|
|
||||||
return time.Time{}, false
|
|
||||||
}
|
|
||||||
t, ok := parseManifestDate(text)
|
|
||||||
if !ok || t.Unix() == 0 {
|
|
||||||
return time.Time{}, false
|
|
||||||
}
|
|
||||||
return t, true
|
|
||||||
}
|
|
||||||
|
|
||||||
var manifestLayouts = []string{
|
|
||||||
time.RFC3339Nano,
|
|
||||||
"2006-01-02T15:04:05.999999999Z0700",
|
|
||||||
"2006-01-02T15:04:05",
|
|
||||||
"2006-01-02T15:04",
|
|
||||||
"2006-01-02 15:04:05Z07:00",
|
|
||||||
"2006-01-02 15:04:05",
|
|
||||||
"2006-01-02",
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseManifestDate(s string) (time.Time, bool) {
|
|
||||||
s = strings.TrimSpace(s)
|
|
||||||
for _, layout := range manifestLayouts {
|
|
||||||
if t, err := time.ParseInLocation(layout, s, time.UTC); err == nil {
|
|
||||||
return t, true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return time.Time{}, false
|
|
||||||
}
|
|
||||||
@@ -1,81 +0,0 @@
|
|||||||
package classes_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestManifest pins the updates manifest reader: it fails safe (a missing,
|
|
||||||
// empty-path, directory, oversized, non-object or invalid file is no
|
|
||||||
// manifest, so lastmod is omitted), normalizes keys, ignores non-string
|
|
||||||
// values, and parses the ISO dates strtotime reads, a date without a zone
|
|
||||||
// as UTC.
|
|
||||||
func TestManifest(t *testing.T) {
|
|
||||||
dir := t.TempDir()
|
|
||||||
write := func(name, body string) string {
|
|
||||||
t.Helper()
|
|
||||||
path := filepath.Join(dir, name)
|
|
||||||
if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
for name, path := range map[string]string{
|
|
||||||
"empty path": "",
|
|
||||||
"spaces": " ",
|
|
||||||
"missing": filepath.Join(dir, "missing.json"),
|
|
||||||
"directory": dir,
|
|
||||||
"list": write("list.json", `["/a"]`),
|
|
||||||
"string": write("string.json", `"x"`),
|
|
||||||
"invalid": write("invalid.json", `{"/a": `),
|
|
||||||
"empty file": write("empty.json", ""),
|
|
||||||
"oversized": write("big.json", `{"/a":"2026-01-01","pad":"`+strings.Repeat("x", classes.ManifestMaxBytes)+`"}`),
|
|
||||||
"null": write("null.json", "null"),
|
|
||||||
"leading space": write("space.json", " \n"),
|
|
||||||
} {
|
|
||||||
if m := classes.LoadManifest(path); m != nil {
|
|
||||||
t.Errorf("%s: manifest = %v, want none", name, m)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if fifo := filepath.Join(dir, "link.json"); os.Symlink(dir, fifo) == nil {
|
|
||||||
if m := classes.LoadManifest(fifo); m != nil {
|
|
||||||
t.Error("a symlink to a directory is not a manifest")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
path := write("updates.json", ` {"blog/a/":"2026-01-02T03:04:05+02:00","/b":"2026-02-03","c":"2026-03-04 05:06:07","/":"2026-04-05T06:07","/num":12,"/bad":"yesterday","/epoch":"1970-01-01T00:00:00Z","/nested":{"x":1}}`)
|
|
||||||
m := classes.LoadManifest(path)
|
|
||||||
if m == nil {
|
|
||||||
t.Fatal("valid manifest not read")
|
|
||||||
}
|
|
||||||
if _, ok := m["/num"]; ok {
|
|
||||||
t.Fatal("a non-string value was kept")
|
|
||||||
}
|
|
||||||
for url, want := range map[string]string{
|
|
||||||
"https://h/blog/a": "2026-01-02T01:04:05Z",
|
|
||||||
"https://h/blog/a/": "2026-01-02T01:04:05Z",
|
|
||||||
"https://h/b?x=1": "2026-02-03T00:00:00Z",
|
|
||||||
"/c": "2026-03-04T05:06:07Z",
|
|
||||||
"https://h": "2026-04-05T06:07:00Z",
|
|
||||||
"https://h/": "2026-04-05T06:07:00Z",
|
|
||||||
} {
|
|
||||||
got, ok := m.Lastmod(url)
|
|
||||||
if !ok || got.UTC().Format(time.RFC3339) != want {
|
|
||||||
t.Errorf("Lastmod(%s) = %v %v, want %s", url, got, ok, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, url := range []string{"https://h/bad", "https://h/epoch", "https://h/unlisted", "https://h/num"} {
|
|
||||||
if got, ok := m.Lastmod(url); ok {
|
|
||||||
t.Errorf("Lastmod(%s) = %v, want none", url, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var none classes.Manifest
|
|
||||||
if _, ok := none.Lastmod("https://h/b"); ok {
|
|
||||||
t.Fatal("a nil manifest answered")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
239
classes/news.go
Normal file
239
classes/news.go
Normal file
@@ -0,0 +1,239 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/xml"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/signpost"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// NSNews is the namespace of the Google News sitemap.
|
||||||
|
const NSNews = "http://www.google.com/schemas/sitemap-news/0.9"
|
||||||
|
|
||||||
|
// NewsFile is the name of the News sitemap file.
|
||||||
|
const NewsFile = "sitemap-news.xml"
|
||||||
|
|
||||||
|
// The News sitemap's limits (RESEARCH Pitfall 9): articles first published
|
||||||
|
// in the last NewsWindow, at most MaxNewsEntries.
|
||||||
|
const (
|
||||||
|
NewsWindow = 48 * time.Hour
|
||||||
|
MaxNewsEntries = 1000
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewsEntry is one <url> of the News sitemap: the article's absolute
|
||||||
|
// address, the publication name and language, its first publication and
|
||||||
|
// its title.
|
||||||
|
type NewsEntry struct {
|
||||||
|
Loc string
|
||||||
|
Publication string
|
||||||
|
Language string
|
||||||
|
Published time.Time
|
||||||
|
Title string
|
||||||
|
}
|
||||||
|
|
||||||
|
// The prefixes of the news_sources values (P33-15).
|
||||||
|
const (
|
||||||
|
NewsSourceType = models.NewsSourceType
|
||||||
|
NewsSourceCategory = models.NewsSourceCategory
|
||||||
|
)
|
||||||
|
|
||||||
|
// newsSources are the parsed news_sources values: the article types and
|
||||||
|
// the parents listed.
|
||||||
|
type newsSources struct {
|
||||||
|
types map[string]bool
|
||||||
|
parents map[models.Ref]bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseNewsSources reads the news_sources values; a value of another form
|
||||||
|
// is ignored (the settings refuse it on save).
|
||||||
|
func parseNewsSources(values []string) newsSources {
|
||||||
|
out := newsSources{types: map[string]bool{}, parents: map[models.Ref]bool{}}
|
||||||
|
for _, v := range values {
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(v, NewsSourceType):
|
||||||
|
if key := strings.TrimPrefix(v, NewsSourceType); key != "" {
|
||||||
|
out.types[key] = true
|
||||||
|
}
|
||||||
|
case strings.HasPrefix(v, NewsSourceCategory):
|
||||||
|
rest := strings.TrimPrefix(v, NewsSourceCategory)
|
||||||
|
if i := strings.LastIndex(rest, ":"); i > 0 && i < len(rest)-1 {
|
||||||
|
out.parents[models.Ref{Type: rest[:i], ID: rest[i+1:]}] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// empty reports whether no source is listed: every article type is.
|
||||||
|
func (s newsSources) empty() bool { return len(s.types) == 0 && len(s.parents) == 0 }
|
||||||
|
|
||||||
|
// matches reports whether an article of typeKey with parents is listed:
|
||||||
|
// its type or one of its parents is (P33-15).
|
||||||
|
func (s newsSources) matches(typeKey string, parents []models.Ref) bool {
|
||||||
|
if s.empty() || s.types[typeKey] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for _, p := range parents {
|
||||||
|
if s.parents[p] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewsLanguage is the News language code of a locale: the lowercase
|
||||||
|
// primary subtag (pl-PL: pl), except Chinese, which Google names zh-cn or
|
||||||
|
// zh-tw.
|
||||||
|
func NewsLanguage(locale string) string {
|
||||||
|
l := strings.ToLower(strings.ReplaceAll(strings.TrimSpace(locale), "_", "-"))
|
||||||
|
if l == "zh-tw" || l == "zh-hant" || strings.HasPrefix(l, "zh-hant-") {
|
||||||
|
return "zh-tw"
|
||||||
|
}
|
||||||
|
if l == "zh" || strings.HasPrefix(l, "zh-") {
|
||||||
|
return "zh-cn"
|
||||||
|
}
|
||||||
|
if i := strings.IndexByte(l, '-'); i > 0 {
|
||||||
|
return l[:i]
|
||||||
|
}
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewsPublication is the publication name of the News sitemap: the
|
||||||
|
// news_publication setting, else the config key app.name.
|
||||||
|
func NewsPublication(app *backpack.App, s models.Settings) string {
|
||||||
|
if name := strings.TrimSpace(models.Text(s.NewsPublication)); name != "" {
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
if app != nil && app.Config != nil {
|
||||||
|
return strings.TrimSpace(app.Config.String("app.name"))
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewsEntries lists the News sitemap's articles (D-31, RESEARCH Pitfall 9):
|
||||||
|
// listed addresses of content types of kind article first published within
|
||||||
|
// NewsWindow before now, of the news_sources (every article type when none
|
||||||
|
// is listed), newest first, at most MaxNewsEntries. An address without a
|
||||||
|
// locale takes the default_locale setting, else app.locale.
|
||||||
|
func NewsEntries(db *gorm.DB, app *backpack.App, s models.Settings, now time.Time) ([]NewsEntry, error) {
|
||||||
|
sources := parseNewsSources(s.Sources())
|
||||||
|
q := db.Model(&models.URL{}).
|
||||||
|
Where("kind = ? AND excluded_reason = '' AND published_at IS NOT NULL AND published_at >= ? AND published_at <= ?", pact.ContentKindArticle, now.Add(-NewsWindow), now).
|
||||||
|
Order("published_at DESC, id DESC")
|
||||||
|
if sources.empty() {
|
||||||
|
q = q.Limit(MaxNewsEntries)
|
||||||
|
}
|
||||||
|
var rows []models.URL
|
||||||
|
if err := q.Find(&rows).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
site := SiteURL(app, s)
|
||||||
|
publication := NewsPublication(app, s)
|
||||||
|
fallback := models.Text(s.DefaultLocale)
|
||||||
|
if fallback == "" && app != nil && app.Config != nil {
|
||||||
|
fallback = app.Config.String("app.locale")
|
||||||
|
}
|
||||||
|
out := make([]NewsEntry, 0, min(len(rows), MaxNewsEntries))
|
||||||
|
for _, r := range rows {
|
||||||
|
if len(out) == MaxNewsEntries {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if !sources.matches(r.TypeKey, r.ParentRefs.Get()) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
loc := Absolute(site, r.URL)
|
||||||
|
if loc == "" || r.PublishedAt == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
locale := r.Locale
|
||||||
|
if locale == "" {
|
||||||
|
locale = fallback
|
||||||
|
}
|
||||||
|
title := strings.TrimSpace(r.Title)
|
||||||
|
if title == "" {
|
||||||
|
title = loc
|
||||||
|
}
|
||||||
|
out = append(out, NewsEntry{Loc: loc, Publication: publication, Language: NewsLanguage(locale), Published: r.PublishedAt.UTC(), Title: title})
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteNewsURLSet writes the News sitemap: a <url> per article with its
|
||||||
|
// <loc> and news:news (news:publication with news:name and news:language,
|
||||||
|
// news:publication_date and news:title).
|
||||||
|
func WriteNewsURLSet(w io.Writer, entries []NewsEntry) error {
|
||||||
|
bw := bufio.NewWriter(w)
|
||||||
|
bw.WriteString(xml.Header)
|
||||||
|
bw.WriteString(`<urlset xmlns="` + NSSitemap + `" xmlns:news="` + NSNews + `">`)
|
||||||
|
for _, e := range entries {
|
||||||
|
bw.WriteString("\n<url><loc>")
|
||||||
|
escape(bw, e.Loc)
|
||||||
|
bw.WriteString("</loc><news:news><news:publication><news:name>")
|
||||||
|
escape(bw, e.Publication)
|
||||||
|
bw.WriteString("</news:name><news:language>")
|
||||||
|
escape(bw, e.Language)
|
||||||
|
bw.WriteString("</news:language></news:publication><news:publication_date>")
|
||||||
|
bw.WriteString(lastmod(e.Published))
|
||||||
|
bw.WriteString("</news:publication_date><news:title>")
|
||||||
|
escape(bw, e.Title)
|
||||||
|
bw.WriteString("</news:title></news:news></url>")
|
||||||
|
}
|
||||||
|
bw.WriteString("\n</urlset>\n")
|
||||||
|
return bw.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewsSource is one value the news_sources setting may take, with what it
|
||||||
|
// lists: Type is the content type key, ID the category's record ID ("" for
|
||||||
|
// a whole type) and Title the category's title.
|
||||||
|
type NewsSource struct {
|
||||||
|
Value string `json:"value"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
ID string `json:"id,omitempty"`
|
||||||
|
Title string `json:"title,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// maxNewsSourceCategories caps the categories NewsSources lists.
|
||||||
|
const maxNewsSourceCategories = 500
|
||||||
|
|
||||||
|
// NewsSources lists the values news_sources may take (P33-15): type:<key>
|
||||||
|
// for every content type of kind article, then category:<key>:<id> for
|
||||||
|
// every parent the listed articles name (their categories), with its title
|
||||||
|
// from the slot table (the default locale's first), at most 500.
|
||||||
|
func NewsSources(db *gorm.DB, reg *signpost.Registry, defaultLocale string) ([]NewsSource, error) {
|
||||||
|
out := []NewsSource{}
|
||||||
|
if reg != nil {
|
||||||
|
for _, typ := range reg.ContentTypes() {
|
||||||
|
if typ.Content != nil && typ.Content.Kind == pact.ContentKindArticle {
|
||||||
|
out = append(out, NewsSource{Value: NewsSourceType + typ.Key, Type: typ.Key})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var rows []struct {
|
||||||
|
Type string `gorm:"column:type"`
|
||||||
|
ID string `gorm:"column:id"`
|
||||||
|
Title string `gorm:"column:title"`
|
||||||
|
}
|
||||||
|
if err := db.Raw(`SELECT DISTINCT ON (p.type, p.id) p.type, p.id, COALESCE(c.title, '') AS title
|
||||||
|
FROM (SELECT DISTINCT r->>'type' AS type, r->>'id' AS id
|
||||||
|
FROM golem15_sitemap_urls u, jsonb_array_elements(u.parent_refs) r
|
||||||
|
WHERE u.kind = ? AND u.excluded_reason = '') p
|
||||||
|
LEFT JOIN golem15_sitemap_urls c ON c.type_key = p.type AND c.record_id = p.id
|
||||||
|
ORDER BY p.type, p.id, (c.locale = ?) DESC, c.id
|
||||||
|
LIMIT ?`, pact.ContentKindArticle, defaultLocale, maxNewsSourceCategories).Scan(&rows).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, r := range rows {
|
||||||
|
v := NewsSourceCategory + r.Type + ":" + r.ID
|
||||||
|
if models.ValidNewsSource(v) {
|
||||||
|
out = append(out, NewsSource{Value: v, Type: r.Type, ID: r.ID, Title: r.Title})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
126
classes/news_test.go
Normal file
126
classes/news_test.go
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestNewsLimits pins the News sitemap's window and cap (RESEARCH Pitfall
|
||||||
|
// 9): 48 hours and 1000 articles. The 47 h and 49 h boundaries on the
|
||||||
|
// database are TestNewsSitemap's.
|
||||||
|
func TestNewsLimits(t *testing.T) {
|
||||||
|
if NewsWindow != 48*time.Hour || MaxNewsEntries != 1000 || NewsFile != "sitemap-news.xml" {
|
||||||
|
t.Fatalf("window %s, cap %d, file %s", NewsWindow, MaxNewsEntries, NewsFile)
|
||||||
|
}
|
||||||
|
now := time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC)
|
||||||
|
for _, tc := range []struct {
|
||||||
|
age time.Duration
|
||||||
|
want bool
|
||||||
|
}{{0, true}, {47 * time.Hour, true}, {48 * time.Hour, true}, {48*time.Hour + time.Second, false}, {49 * time.Hour, false}} {
|
||||||
|
published := now.Add(-tc.age)
|
||||||
|
in := !published.Before(now.Add(-NewsWindow)) && !published.After(now)
|
||||||
|
if in != tc.want {
|
||||||
|
t.Errorf("published %s before now: in window %v, want %v", tc.age, in, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestParseNewsSources pins the news_sources values: type:<key> and
|
||||||
|
// category:<type>:<id> (the last colon splits, so a type key may hold
|
||||||
|
// one); other forms and empty parts are ignored.
|
||||||
|
func TestParseNewsSources(t *testing.T) {
|
||||||
|
s := parseNewsSources([]string{"type:blog-post", "category:blog-category:7", "category:a:b:9", "type:", "category:x", "category::1", "category:x:", "other:1", ""})
|
||||||
|
if len(s.types) != 1 || !s.types["blog-post"] {
|
||||||
|
t.Fatalf("types = %v", s.types)
|
||||||
|
}
|
||||||
|
if len(s.parents) != 2 || !s.parents[models.Ref{Type: "blog-category", ID: "7"}] || !s.parents[models.Ref{Type: "a:b", ID: "9"}] {
|
||||||
|
t.Fatalf("parents = %v", s.parents)
|
||||||
|
}
|
||||||
|
if s.empty() || !parseNewsSources(nil).empty() || !parseNewsSources([]string{"bogus"}).empty() {
|
||||||
|
t.Fatal("empty() is wrong")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNewsSourcesMatch pins P33-15: no source lists every article; else an
|
||||||
|
// article is listed by its type or by one of its parents.
|
||||||
|
func TestNewsSourcesMatch(t *testing.T) {
|
||||||
|
cat := models.Ref{Type: "blog-category", ID: "7"}
|
||||||
|
other := models.Ref{Type: "blog-category", ID: "8"}
|
||||||
|
all := parseNewsSources(nil)
|
||||||
|
byType := parseNewsSources([]string{"type:news"})
|
||||||
|
byCat := parseNewsSources([]string{"category:blog-category:7"})
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
s newsSources
|
||||||
|
typ string
|
||||||
|
parents []models.Ref
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{"none listed", all, "blog-post", nil, true},
|
||||||
|
{"type listed", byType, "news", nil, true},
|
||||||
|
{"other type", byType, "blog-post", []models.Ref{cat}, false},
|
||||||
|
{"parent listed", byCat, "blog-post", []models.Ref{other, cat}, true},
|
||||||
|
{"other parent", byCat, "blog-post", []models.Ref{other}, false},
|
||||||
|
{"no parents", byCat, "blog-post", nil, false},
|
||||||
|
} {
|
||||||
|
if got := tc.s.matches(tc.typ, tc.parents); got != tc.want {
|
||||||
|
t.Errorf("%s: matches = %v, want %v", tc.name, got, tc.want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNewsLanguage pins the language codes Google reads.
|
||||||
|
func TestNewsLanguage(t *testing.T) {
|
||||||
|
for in, want := range map[string]string{
|
||||||
|
"pl": "pl", "pl-PL": "pl", "pl_PL": "pl", " EN ": "en", "en-GB": "en",
|
||||||
|
"zh": "zh-cn", "zh-Hans": "zh-cn", "zh-CN": "zh-cn", "zh-TW": "zh-tw", "zh_tw": "zh-tw", "zh-Hant": "zh-tw", "zh-Hant-HK": "zh-tw",
|
||||||
|
"": "",
|
||||||
|
} {
|
||||||
|
if got := NewsLanguage(in); got != want {
|
||||||
|
t.Errorf("NewsLanguage(%q) = %q, want %q", in, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNewsPublication pins the publication name: the setting, else
|
||||||
|
// app.name, else nothing.
|
||||||
|
func TestNewsPublication(t *testing.T) {
|
||||||
|
cfg, err := compass.Open(compass.Options{Dir: t.TempDir(), Environ: []string{"SUMMER_APP__NAME=Acme Daily"}})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
app := backpack.New(cfg)
|
||||||
|
named := " The Acme Times "
|
||||||
|
if got := NewsPublication(app, models.Settings{NewsPublication: &named}); got != "The Acme Times" {
|
||||||
|
t.Fatalf("with the setting: %q", got)
|
||||||
|
}
|
||||||
|
blank := " "
|
||||||
|
if got := NewsPublication(app, models.Settings{NewsPublication: &blank}); got != "Acme Daily" {
|
||||||
|
t.Fatalf("with a blank setting: %q, want app.name", got)
|
||||||
|
}
|
||||||
|
if got := NewsPublication(nil, models.Settings{}); got != "" {
|
||||||
|
t.Fatalf("without an app: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWriteNewsURLSet pins the News file: the news namespace, every
|
||||||
|
// element in order, escaping and the UTC publication date.
|
||||||
|
func TestWriteNewsURLSet(t *testing.T) {
|
||||||
|
at := time.Date(2026, 11, 4, 9, 0, 0, 0, time.FixedZone("CET", 3600))
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := WriteNewsURLSet(&buf, []NewsEntry{{Loc: "https://example.test/a?b&c", Publication: "A & B", Language: "pl", Published: at, Title: "<Grzyby>"}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
out := buf.String()
|
||||||
|
want := `<url><loc>https://example.test/a?b&c</loc><news:news><news:publication><news:name>A & B</news:name><news:language>pl</news:language></news:publication><news:publication_date>2026-11-04T08:00:00Z</news:publication_date><news:title><Grzyby></news:title></news:news></url>`
|
||||||
|
if !strings.Contains(out, `xmlns:news="`+NSNews+`"`) || !strings.Contains(out, want) {
|
||||||
|
t.Fatalf("news file:\n%s", out)
|
||||||
|
}
|
||||||
|
wellFormed(t, out)
|
||||||
|
}
|
||||||
682
classes/rebuild.go
Normal file
682
classes/rebuild.go
Normal file
@@ -0,0 +1,682 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/sha256"
|
||||||
|
"database/sql/driver"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/contract"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/signpost"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RebuildKind is the River kind of the rebuild job.
|
||||||
|
const RebuildKind = "golem15.sitemap.rebuild"
|
||||||
|
|
||||||
|
// RebuildArgs are the arguments of the rebuild job: it has none, a rebuild
|
||||||
|
// always covers every content type and the additional addresses.
|
||||||
|
type RebuildArgs struct{}
|
||||||
|
|
||||||
|
// Kind is RebuildKind.
|
||||||
|
func (RebuildArgs) Kind() string { return RebuildKind }
|
||||||
|
|
||||||
|
// recordsPage is the page size the rebuild asks the content types for.
|
||||||
|
const recordsPage = 500
|
||||||
|
|
||||||
|
// ErrNoDatabase is returned when the application publishes no database.
|
||||||
|
var ErrNoDatabase = errors.New("golem15.sitemap: database is not configured")
|
||||||
|
|
||||||
|
// RebuildResult is what one rebuild changed, as absolute URLs: Added are
|
||||||
|
// newly listed addresses, Changed listed addresses whose URL changed and
|
||||||
|
// Removed addresses that left the files. Listed counts the listed
|
||||||
|
// addresses and Files the files they fill.
|
||||||
|
type RebuildResult struct {
|
||||||
|
Added []string
|
||||||
|
Changed []string
|
||||||
|
Removed []string
|
||||||
|
Listed int
|
||||||
|
Files int
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultSlug is the file name part of a content type's group: the last
|
||||||
|
// segment of its key in plural form (journal-post: posts, journal-category:
|
||||||
|
// categories, seo-page: pages).
|
||||||
|
func DefaultSlug(key string) string {
|
||||||
|
key = strings.ToLower(strings.TrimSpace(key))
|
||||||
|
if i := strings.LastIndexAny(key, "-_."); i >= 0 {
|
||||||
|
key = key[i+1:]
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
for _, r := range key {
|
||||||
|
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') {
|
||||||
|
b.WriteRune(r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s := b.String()
|
||||||
|
switch {
|
||||||
|
case s == "":
|
||||||
|
return "pages"
|
||||||
|
case strings.HasSuffix(s, "y") && len(s) > 1 && !strings.ContainsRune("aeiou", rune(s[len(s)-2])):
|
||||||
|
return s[:len(s)-1] + "ies"
|
||||||
|
case strings.HasSuffix(s, "s"):
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return s + "s"
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExtraRecordID is the record_id of an additional address: the hex SHA-256
|
||||||
|
// of the address.
|
||||||
|
func ExtraRecordID(u string) string {
|
||||||
|
sum := sha256.Sum256([]byte(u))
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// slotKey identifies a row of the slot table.
|
||||||
|
type slotKey struct {
|
||||||
|
typeKey, recordID, locale string
|
||||||
|
}
|
||||||
|
|
||||||
|
// wanted is one address a rebuild found: its group, its row key, its path
|
||||||
|
// and title, its first lastmod (for a new row) and the reason it is left
|
||||||
|
// out ("" when listed). An additional address carries its own lastmod,
|
||||||
|
// which the editor sets, so it is written on every rebuild. images, kind,
|
||||||
|
// published and parents are the record's facts for the image and News
|
||||||
|
// sitemaps and the HTML sitemap.
|
||||||
|
type wanted struct {
|
||||||
|
key slotKey
|
||||||
|
grp string
|
||||||
|
url string
|
||||||
|
title string
|
||||||
|
firstMod *time.Time
|
||||||
|
reason string
|
||||||
|
extra bool
|
||||||
|
extraMod *time.Time
|
||||||
|
alternates []models.Alternate
|
||||||
|
images []string
|
||||||
|
kind string
|
||||||
|
published *time.Time
|
||||||
|
parents []models.Ref
|
||||||
|
}
|
||||||
|
|
||||||
|
// collected is what a rebuild read from the content types and settings.
|
||||||
|
type collected struct {
|
||||||
|
rows []wanted
|
||||||
|
unpublished map[slotKey]bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rebuild reads every content type's published records (signpost Records,
|
||||||
|
// D-93) and the additional addresses, writes them into the slot table and
|
||||||
|
// numbers the files. A record that is gone or unpublished leaves its rows
|
||||||
|
// in the table with a reason, as a hole; only a changed file size
|
||||||
|
// renumbers the files (D-30). In production, with IndexNow on, the added,
|
||||||
|
// changed and removed addresses are queued for IndexNow after the commit
|
||||||
|
// (NotifyIndexNow), with the rows the record listeners marked
|
||||||
|
// (indexnow_pending_at): a deleted record's addresses as removed, an
|
||||||
|
// edited record's listed addresses as changed.
|
||||||
|
//
|
||||||
|
// Two rebuilds never interleave (L2 WR-02): one transaction takes the
|
||||||
|
// transaction-scoped advisory lock golem15.sitemap.rebuild first, then
|
||||||
|
// reads the settings and the type settings, collects the records, locks
|
||||||
|
// the settings row and applies, so a second rebuild collects only after
|
||||||
|
// the first has committed and an older snapshot never overwrites a newer
|
||||||
|
// one. A rebuild never writes the lastmod of a content row it did not
|
||||||
|
// create (WR-03), so a lastmod that RecordSaved moved meanwhile stays.
|
||||||
|
func Rebuild(ctx context.Context, app *backpack.App) (RebuildResult, error) {
|
||||||
|
var res RebuildResult
|
||||||
|
if app == nil {
|
||||||
|
return res, ErrNoDatabase
|
||||||
|
}
|
||||||
|
db, ok := app.Lookup[*gorm.DB]()
|
||||||
|
if !ok || db == nil {
|
||||||
|
return res, ErrNoDatabase
|
||||||
|
}
|
||||||
|
db = db.WithContext(ctx)
|
||||||
|
reg, _ := app.Lookup[*signpost.Registry]()
|
||||||
|
filter, _ := app.Lookup[contract.Filter]()
|
||||||
|
err := db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := tx.Exec(`SELECT pg_advisory_xact_lock(hashtext('golem15.sitemap.rebuild'))`).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
settings, err := LoadSettings(tx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
types, err := LoadTypeSettings(tx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
site := SiteURL(app, settings)
|
||||||
|
found, err := collect(ctx, reg, filter, settings, types, site)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Exec(`SELECT id FROM golem15_sitemap_settings WHERE id = 1 FOR UPDATE`).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
locked, err := LoadSettings(tx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
res, err = apply(ctx, tx, found, locked, site)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
// IndexNow hears of the change once it is committed (D-31); a queue
|
||||||
|
// error is logged and never fails the rebuild.
|
||||||
|
if err := NotifyIndexNow(ctx, app, db, res); err != nil {
|
||||||
|
pluginLog.Warn("golem15.sitemap: queue indexnow", "error", err)
|
||||||
|
}
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// afterSlotReadKey carries the WithAfterSlotRead hook.
|
||||||
|
type afterSlotReadKey struct{}
|
||||||
|
|
||||||
|
// WithAfterSlotRead returns ctx with fn, which a rebuild on ctx calls right
|
||||||
|
// after apply has read the slot rows and before it writes them: a test
|
||||||
|
// seam for what happens concurrently (nil, the default, calls nothing).
|
||||||
|
func WithAfterSlotRead(ctx context.Context, fn func()) context.Context {
|
||||||
|
return context.WithValue(ctx, afterSlotReadKey{}, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// collect walks the content types page by page and adds the additional
|
||||||
|
// addresses. The records of a type switched off in the settings are kept
|
||||||
|
// in the table with the reason contract.ReasonType, so the settings screen
|
||||||
|
// counts them. Every other page of addresses (and the additional
|
||||||
|
// addresses) is one batch for the published contract.Filter, when there is
|
||||||
|
// one (D-95): an excluded address keeps its row with the Filter's reason, a
|
||||||
|
// Decision.Group moves it to that file group, and Decision.LastMod is the
|
||||||
|
// first lastmod of a new row. The hreflang alternates of a record are its
|
||||||
|
// listed addresses (D-55 to D-57). Each address keeps its page's images
|
||||||
|
// (PageImages, on site), the type's kind, the record's first publication
|
||||||
|
// and its parents. An additional address a listed record already has is
|
||||||
|
// left out as models.ReasonDuplicate (markListedExtras).
|
||||||
|
func collect(ctx context.Context, reg *signpost.Registry, filter contract.Filter, settings models.Settings, types map[string]models.TypeSetting, site string) (collected, error) {
|
||||||
|
out := collected{unpublished: map[slotKey]bool{}}
|
||||||
|
seen := map[slotKey]bool{}
|
||||||
|
defaultLocale := models.Text(settings.DefaultLocale)
|
||||||
|
// batch decides one batch and adds its rows; rows of one record are
|
||||||
|
// adjacent, so the alternates are computed per run of a record.
|
||||||
|
batch := func(rows []wanted) error {
|
||||||
|
var fresh []wanted
|
||||||
|
for _, w := range rows {
|
||||||
|
if !seen[w.key] {
|
||||||
|
seen[w.key] = true
|
||||||
|
fresh = append(fresh, w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := decide(ctx, filter, fresh); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
setAlternates(fresh, defaultLocale)
|
||||||
|
out.rows = append(out.rows, fresh...)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if reg != nil {
|
||||||
|
for _, typ := range reg.ContentTypes() {
|
||||||
|
cfg := EffectiveType(typ, types)
|
||||||
|
kind := ""
|
||||||
|
if typ.Content != nil {
|
||||||
|
kind = typ.Content.Kind
|
||||||
|
}
|
||||||
|
after := ""
|
||||||
|
for {
|
||||||
|
page, err := reg.Records(ctx, typ.Key, after, recordsPage, defaultLocale)
|
||||||
|
if err != nil {
|
||||||
|
return out, fmt.Errorf("golem15.sitemap: records of %s: %w", typ.Key, err)
|
||||||
|
}
|
||||||
|
var rows []wanted
|
||||||
|
for _, rec := range page.Records {
|
||||||
|
if !rec.Published {
|
||||||
|
out.unpublished[slotKey{typ.Key, rec.ID, ""}] = true
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
parents := make([]models.Ref, 0, len(rec.Parents))
|
||||||
|
for _, p := range rec.Parents {
|
||||||
|
if p.Type != "" && p.ID != "" {
|
||||||
|
parents = append(parents, models.Ref{Type: p.Type, ID: p.ID})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, l := range rec.Locales {
|
||||||
|
if strings.TrimSpace(l.URL) == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
w := wanted{
|
||||||
|
key: slotKey{typ.Key, rec.ID, l.Locale},
|
||||||
|
grp: cfg.Slug,
|
||||||
|
url: l.URL,
|
||||||
|
title: l.Title,
|
||||||
|
firstMod: rec.LastMod,
|
||||||
|
images: PageImages(l, site),
|
||||||
|
kind: kind,
|
||||||
|
published: rec.PublishedAt,
|
||||||
|
parents: parents,
|
||||||
|
}
|
||||||
|
if !cfg.Include {
|
||||||
|
w.reason = contract.ReasonType
|
||||||
|
}
|
||||||
|
rows = append(rows, w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := batch(rows); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
if page.Next == "" || page.Next == after {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
after = page.Next
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
extras := extraRows(settings.Extra())
|
||||||
|
markListedExtras(out.rows, extras, site)
|
||||||
|
if err := batch(extras); err != nil {
|
||||||
|
return out, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// extraRows turns the settings' additional addresses into rows; an address
|
||||||
|
// that is not allowed is skipped.
|
||||||
|
func extraRows(list []models.ExtraURL) []wanted {
|
||||||
|
var extras []wanted
|
||||||
|
for _, e := range list {
|
||||||
|
u := strings.TrimSpace(e.URL)
|
||||||
|
if !models.AllowedAddress(u) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
mod := models.ParseDate(e.LastMod)
|
||||||
|
extras = append(extras, wanted{
|
||||||
|
key: slotKey{models.ExtraTypeKey, ExtraRecordID(u), ""},
|
||||||
|
grp: models.ExtraGroup,
|
||||||
|
url: u,
|
||||||
|
extra: true,
|
||||||
|
extraMod: mod,
|
||||||
|
firstMod: mod,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return extras
|
||||||
|
}
|
||||||
|
|
||||||
|
// markListedExtras leaves out (models.ReasonDuplicate) every additional
|
||||||
|
// address whose absolute URL a content record already lists, so an address
|
||||||
|
// both in a content type and in the additional addresses (a definition
|
||||||
|
// migrated from the old sitemap, for example) is in the files once, with
|
||||||
|
// the record's lastmod and alternates. A record left out by the filter or
|
||||||
|
// the type switch does not count: the editor's additional address then
|
||||||
|
// stays listed. The rows keep their place in the slot table, so the
|
||||||
|
// settings screen counts them by reason.
|
||||||
|
func markListedExtras(records, extras []wanted, site string) {
|
||||||
|
listed := map[string]bool{}
|
||||||
|
for _, w := range records {
|
||||||
|
if w.reason == "" && !w.extra {
|
||||||
|
listed[addressKey(site, w.url)] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := range extras {
|
||||||
|
if extras[i].reason == "" && listed[addressKey(site, extras[i].url)] {
|
||||||
|
extras[i].reason = models.ReasonDuplicate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// addressKey is the absolute form of an address for comparison, or the
|
||||||
|
// address itself when it has none (a path without a site URL).
|
||||||
|
func addressKey(site, u string) string {
|
||||||
|
u = strings.TrimSpace(u)
|
||||||
|
if a := Absolute(site, u); a != "" {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
|
// decide asks filter about the rows not already left out (a type switched
|
||||||
|
// off is decided by the settings) and applies its decisions. Without a
|
||||||
|
// Filter every row stays listed.
|
||||||
|
func decide(ctx context.Context, filter contract.Filter, rows []wanted) error {
|
||||||
|
if filter == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var asked []int
|
||||||
|
var candidates []contract.Candidate
|
||||||
|
for i, w := range rows {
|
||||||
|
if w.reason != "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
asked = append(asked, i)
|
||||||
|
candidates = append(candidates, contract.Candidate{TypeKey: w.key.typeKey, RecordID: w.key.recordID, Locale: w.key.locale, URL: w.url})
|
||||||
|
}
|
||||||
|
if len(candidates) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
decisions, err := filter.Decide(ctx, candidates)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("golem15.sitemap: filter: %w", err)
|
||||||
|
}
|
||||||
|
if len(decisions) != len(candidates) {
|
||||||
|
return fmt.Errorf("golem15.sitemap: filter answered %d decisions for %d candidates", len(decisions), len(candidates))
|
||||||
|
}
|
||||||
|
for j, d := range decisions {
|
||||||
|
w := &rows[asked[j]]
|
||||||
|
if d.Exclude {
|
||||||
|
w.reason = strings.TrimSpace(d.Reason)
|
||||||
|
if w.reason == "" {
|
||||||
|
w.reason = contract.ReasonNoindex
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if g := strings.TrimSpace(d.Group); g != "" {
|
||||||
|
if ValidSlug(g) && !ReservedSlugs[g] {
|
||||||
|
w.grp = g
|
||||||
|
} else {
|
||||||
|
pluginLog.Warn("golem15.sitemap: filter group ignored", "group", g, "type", w.key.typeKey, "record", w.key.recordID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if d.LastMod != nil {
|
||||||
|
w.firstMod = d.LastMod
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// setAlternates gives the listed addresses of every record with more than
|
||||||
|
// one listed locale its hreflang alternates: each listed locale with its
|
||||||
|
// address, itself included, then x-default on the default locale's address
|
||||||
|
// (the record's first listed locale when the default has none). A locale
|
||||||
|
// without an address or left out has no alternate; a record with one
|
||||||
|
// listed locale gets none (D-55 to D-57, RESEARCH Pitfall 3).
|
||||||
|
func setAlternates(rows []wanted, defaultLocale string) {
|
||||||
|
type record struct{ typeKey, id string }
|
||||||
|
listed := map[record][]int{}
|
||||||
|
var order []record
|
||||||
|
for i, w := range rows {
|
||||||
|
if w.reason != "" || w.extra || w.key.locale == "" || w.key.locale == "x-default" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
r := record{w.key.typeKey, w.key.recordID}
|
||||||
|
if _, ok := listed[r]; !ok {
|
||||||
|
order = append(order, r)
|
||||||
|
}
|
||||||
|
listed[r] = append(listed[r], i)
|
||||||
|
}
|
||||||
|
for _, r := range order {
|
||||||
|
idx := listed[r]
|
||||||
|
if len(idx) < 2 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
alts := make([]models.Alternate, 0, len(idx)+1)
|
||||||
|
xDefault := rows[idx[0]].url
|
||||||
|
for _, i := range idx {
|
||||||
|
alts = append(alts, models.Alternate{Hreflang: rows[i].key.locale, Href: rows[i].url})
|
||||||
|
if rows[i].key.locale == defaultLocale {
|
||||||
|
xDefault = rows[i].url
|
||||||
|
}
|
||||||
|
}
|
||||||
|
alts = append(alts, models.Alternate{Hreflang: "x-default", Href: xDefault})
|
||||||
|
for _, i := range idx {
|
||||||
|
rows[i].alternates = alts
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// apply writes the found addresses into the slot table and numbers the
|
||||||
|
// files, inside the rebuild's transaction.
|
||||||
|
func apply(ctx context.Context, tx *gorm.DB, found collected, settings models.Settings, site string) (RebuildResult, error) {
|
||||||
|
var res RebuildResult
|
||||||
|
var existing []models.URL
|
||||||
|
if err := tx.Order("id ASC").Find(&existing).Error; err != nil {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
if fn, _ := ctx.Value(afterSlotReadKey{}).(func()); fn != nil {
|
||||||
|
fn()
|
||||||
|
}
|
||||||
|
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||||
|
byKey := make(map[slotKey]*models.URL, len(existing))
|
||||||
|
for i := range existing {
|
||||||
|
r := &existing[i]
|
||||||
|
byKey[slotKey{r.TypeKey, r.RecordID, r.Locale}] = r
|
||||||
|
}
|
||||||
|
dirty := map[uint64]bool{}
|
||||||
|
var created []*models.URL
|
||||||
|
matched := map[slotKey]bool{}
|
||||||
|
// pending are the rows the record listeners marked for IndexNow
|
||||||
|
// (P33-62), with the mark this rebuild read; notified the addresses
|
||||||
|
// already in Added or Changed.
|
||||||
|
pending := map[uint64]time.Time{}
|
||||||
|
notified := map[string]bool{}
|
||||||
|
for _, w := range found.rows {
|
||||||
|
matched[w.key] = true
|
||||||
|
r, ok := byKey[w.key]
|
||||||
|
if !ok {
|
||||||
|
mod := w.firstMod
|
||||||
|
if mod == nil && !w.extra {
|
||||||
|
mod = &now
|
||||||
|
}
|
||||||
|
row := &models.URL{
|
||||||
|
Grp: w.grp,
|
||||||
|
TypeKey: w.key.typeKey,
|
||||||
|
RecordID: w.key.recordID,
|
||||||
|
Locale: w.key.locale,
|
||||||
|
URL: w.url,
|
||||||
|
Title: w.title,
|
||||||
|
FirstSeen: now,
|
||||||
|
LastMod: utcPtr(mod),
|
||||||
|
Alternates: lagoon.Jsonable[[]models.Alternate]{Data: nonNil(w.alternates), Valid: true},
|
||||||
|
Images: lagoon.Jsonable[[]string]{Data: nonNil(w.images), Valid: true},
|
||||||
|
Kind: w.kind,
|
||||||
|
PublishedAt: utcPtr(w.published),
|
||||||
|
ParentRefs: lagoon.Jsonable[[]models.Ref]{Data: nonNil(w.parents), Valid: true},
|
||||||
|
ExcludedReason: w.reason,
|
||||||
|
UpdatedAt: now,
|
||||||
|
}
|
||||||
|
created = append(created, row)
|
||||||
|
if w.reason == "" {
|
||||||
|
res.Added = append(res.Added, Absolute(site, w.url))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
wasListed := r.ExcludedReason == ""
|
||||||
|
before := *r
|
||||||
|
if r.Grp != w.grp {
|
||||||
|
r.Grp = w.grp
|
||||||
|
r.FileNo = nil
|
||||||
|
}
|
||||||
|
r.URL = w.url
|
||||||
|
r.Title = w.title
|
||||||
|
r.ExcludedReason = w.reason
|
||||||
|
r.Alternates = lagoon.Jsonable[[]models.Alternate]{Data: nonNil(w.alternates), Valid: true}
|
||||||
|
r.Images = lagoon.Jsonable[[]string]{Data: nonNil(w.images), Valid: true}
|
||||||
|
r.Kind = w.kind
|
||||||
|
r.PublishedAt = utcPtr(w.published)
|
||||||
|
r.ParentRefs = lagoon.Jsonable[[]models.Ref]{Data: nonNil(w.parents), Valid: true}
|
||||||
|
if w.extra {
|
||||||
|
r.LastMod = utcPtr(w.extraMod)
|
||||||
|
}
|
||||||
|
listed := w.reason == ""
|
||||||
|
switch {
|
||||||
|
case listed && !wasListed:
|
||||||
|
res.Added = append(res.Added, Absolute(site, r.URL))
|
||||||
|
notified[r.URL] = true
|
||||||
|
case !listed && wasListed:
|
||||||
|
res.Removed = append(res.Removed, Absolute(site, before.URL))
|
||||||
|
case listed && before.URL != r.URL:
|
||||||
|
res.Changed = append(res.Changed, Absolute(site, r.URL))
|
||||||
|
notified[r.URL] = true
|
||||||
|
}
|
||||||
|
if r.IndexNowPendingAt != nil {
|
||||||
|
pending[r.ID] = *r.IndexNowPendingAt
|
||||||
|
if listed && !notified[r.URL] {
|
||||||
|
// A content edit that kept the address (RecordSaved
|
||||||
|
// moved its lastmod).
|
||||||
|
res.Changed = append(res.Changed, Absolute(site, r.URL))
|
||||||
|
notified[r.URL] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if rowChanged(before, *r) {
|
||||||
|
dirty[r.ID] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for i := range existing {
|
||||||
|
r := &existing[i]
|
||||||
|
key := slotKey{r.TypeKey, r.RecordID, r.Locale}
|
||||||
|
if matched[key] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
reason := models.ReasonDeleted
|
||||||
|
if found.unpublished[slotKey{r.TypeKey, r.RecordID, ""}] {
|
||||||
|
reason = models.ReasonUnpublished
|
||||||
|
}
|
||||||
|
if r.IndexNowPendingAt != nil {
|
||||||
|
// RecordDeleted already excluded the row; it was listed when
|
||||||
|
// it marked it, so IndexNow hears of it as removed.
|
||||||
|
pending[r.ID] = *r.IndexNowPendingAt
|
||||||
|
if r.ExcludedReason != "" {
|
||||||
|
res.Removed = append(res.Removed, Absolute(site, r.URL))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if r.ExcludedReason == reason {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if r.ExcludedReason == "" {
|
||||||
|
res.Removed = append(res.Removed, Absolute(site, r.URL))
|
||||||
|
}
|
||||||
|
r.ExcludedReason = reason
|
||||||
|
dirty[r.ID] = true
|
||||||
|
}
|
||||||
|
if len(created) > 0 {
|
||||||
|
if err := tx.CreateInBatches(created, 500).Error; err != nil {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
size := settings.EffectiveFileSize()
|
||||||
|
renumber := settings.NumberedSize == nil || *settings.NumberedSize != size
|
||||||
|
slots := make([]*Slot, 0, len(existing)+len(created))
|
||||||
|
rowsByID := make(map[uint64]*models.URL, len(existing)+len(created))
|
||||||
|
for i := range existing {
|
||||||
|
r := &existing[i]
|
||||||
|
rowsByID[r.ID] = r
|
||||||
|
slots = append(slots, &Slot{ID: r.ID, Grp: r.Grp, FileNo: r.FileNo, FirstSeen: r.FirstSeen, Listed: r.ExcludedReason == ""})
|
||||||
|
}
|
||||||
|
for _, r := range created {
|
||||||
|
rowsByID[r.ID] = r
|
||||||
|
slots = append(slots, &Slot{ID: r.ID, Grp: r.Grp, FileNo: r.FileNo, FirstSeen: r.FirstSeen, Listed: r.ExcludedReason == ""})
|
||||||
|
}
|
||||||
|
AssignSlots(slots, size, renumber)
|
||||||
|
files := map[string]bool{}
|
||||||
|
for _, s := range slots {
|
||||||
|
r := rowsByID[s.ID]
|
||||||
|
if !sameInt(r.FileNo, s.FileNo) {
|
||||||
|
r.FileNo = s.FileNo
|
||||||
|
dirty[r.ID] = true
|
||||||
|
}
|
||||||
|
if s.Listed {
|
||||||
|
res.Listed++
|
||||||
|
if s.FileNo != nil {
|
||||||
|
files[FileName(s.Grp, *s.FileNo)] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The image files: the listed rows with images, numbered like the
|
||||||
|
// per-group files (stable, holes kept, renumbered with them).
|
||||||
|
imageSlots := make([]*Slot, 0, len(slots))
|
||||||
|
for _, s := range slots {
|
||||||
|
r := rowsByID[s.ID]
|
||||||
|
imageSlots = append(imageSlots, &Slot{ID: r.ID, Grp: ImagesGroup, FileNo: r.ImageFileNo, FirstSeen: r.FirstSeen, Listed: s.Listed && len(r.Images.Get()) > 0})
|
||||||
|
}
|
||||||
|
AssignSlots(imageSlots, size, renumber)
|
||||||
|
for _, s := range imageSlots {
|
||||||
|
r := rowsByID[s.ID]
|
||||||
|
if !sameInt(r.ImageFileNo, s.FileNo) {
|
||||||
|
r.ImageFileNo = s.FileNo
|
||||||
|
dirty[r.ID] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res.Files = len(files)
|
||||||
|
for id := range dirty {
|
||||||
|
r := rowsByID[id]
|
||||||
|
r.UpdatedAt = now
|
||||||
|
values := map[string]any{
|
||||||
|
"grp": r.Grp,
|
||||||
|
"url": r.URL,
|
||||||
|
"title": r.Title,
|
||||||
|
"file_no": r.FileNo,
|
||||||
|
"alternates": r.Alternates,
|
||||||
|
"images": r.Images,
|
||||||
|
"image_file_no": r.ImageFileNo,
|
||||||
|
"kind": r.Kind,
|
||||||
|
"published_at": r.PublishedAt,
|
||||||
|
"parent_refs": r.ParentRefs,
|
||||||
|
"excluded_reason": r.ExcludedReason,
|
||||||
|
"updated_at": r.UpdatedAt,
|
||||||
|
}
|
||||||
|
// Only an additional address takes its lastmod from the rebuild; a
|
||||||
|
// content row's lastmod is RecordSaved's, never written back from
|
||||||
|
// this rebuild's read (WR-03).
|
||||||
|
if r.TypeKey == models.ExtraTypeKey {
|
||||||
|
values["lastmod"] = r.LastMod
|
||||||
|
}
|
||||||
|
if err := tx.Model(&models.URL{}).Where("id = ?", id).Updates(values).Error; err != nil {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The IndexNow marks this rebuild read are cleared; a mark set after
|
||||||
|
// the read (a later save) survives for the next rebuild.
|
||||||
|
for id, at := range pending {
|
||||||
|
if err := tx.Exec(`UPDATE golem15_sitemap_urls SET indexnow_pending_at = NULL WHERE id = ? AND indexnow_pending_at <= ?`, id, at).Error; err != nil {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Exec(`UPDATE golem15_sitemap_settings SET numbered_size = ?, built_at = ? WHERE id = 1`, size, now).Error; err != nil {
|
||||||
|
return res, err
|
||||||
|
}
|
||||||
|
return res, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// rowChanged reports whether a rebuild changed a stored row.
|
||||||
|
func rowChanged(a, b models.URL) bool {
|
||||||
|
if a.Grp != b.Grp || a.URL != b.URL || a.Title != b.Title || a.ExcludedReason != b.ExcludedReason || a.Kind != b.Kind ||
|
||||||
|
!sameInt(a.FileNo, b.FileNo) || !sameTime(a.LastMod, b.LastMod) || !sameTime(a.PublishedAt, b.PublishedAt) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return jsonDiffers(a.Alternates, b.Alternates) || jsonDiffers(a.Images, b.Images) || jsonDiffers(a.ParentRefs, b.ParentRefs)
|
||||||
|
}
|
||||||
|
|
||||||
|
// jsonDiffers reports whether two stored JSON values differ.
|
||||||
|
func jsonDiffers(a, b driver.Valuer) bool {
|
||||||
|
av, _ := a.Value()
|
||||||
|
bv, _ := b.Value()
|
||||||
|
return fmt.Sprint(av) != fmt.Sprint(bv)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sameInt(a, b *int) bool {
|
||||||
|
return (a == nil && b == nil) || (a != nil && b != nil && *a == *b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func sameTime(a, b *time.Time) bool {
|
||||||
|
return (a == nil && b == nil) || (a != nil && b != nil && a.Equal(*b))
|
||||||
|
}
|
||||||
|
|
||||||
|
func utcPtr(t *time.Time) *time.Time {
|
||||||
|
if t == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
u := t.UTC().Truncate(time.Microsecond)
|
||||||
|
return &u
|
||||||
|
}
|
||||||
|
|
||||||
|
func nonNil[T any](s []T) []T {
|
||||||
|
if s == nil {
|
||||||
|
return []T{}
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
51
classes/rebuild_test.go
Normal file
51
classes/rebuild_test.go
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/contract"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestMarkListedExtras pins the de-duplication of the additional
|
||||||
|
// addresses: an address a listed record has (as a path or as the same
|
||||||
|
// absolute URL) is left out as duplicate; a record left out by the filter
|
||||||
|
// or the type switch, another address and a record's other locale do not
|
||||||
|
// count; an address already left out keeps its reason.
|
||||||
|
func TestMarkListedExtras(t *testing.T) {
|
||||||
|
const site = "https://example.test"
|
||||||
|
records := []wanted{
|
||||||
|
{key: slotKey{"page", "1", "en"}, url: "/"},
|
||||||
|
{key: slotKey{"page", "2", "en"}, url: "/blog"},
|
||||||
|
{key: slotKey{"page", "3", "en"}, url: "/faq", reason: contract.ReasonNoindex},
|
||||||
|
{key: slotKey{"page", "4", "en"}, url: "/off", reason: contract.ReasonType},
|
||||||
|
{key: slotKey{"page", "5", "pl"}, url: "/pl/o-nas"},
|
||||||
|
}
|
||||||
|
extras := extraRows([]models.ExtraURL{
|
||||||
|
{URL: "/"},
|
||||||
|
{URL: site + "/blog"},
|
||||||
|
{URL: "/faq"},
|
||||||
|
{URL: "/off"},
|
||||||
|
{URL: "/kontakt"},
|
||||||
|
{URL: "/o-nas"},
|
||||||
|
{URL: "javascript:alert(1)"},
|
||||||
|
})
|
||||||
|
if len(extras) != 6 {
|
||||||
|
t.Fatalf("extraRows kept %d addresses, want 6 (the javascript: one is not allowed)", len(extras))
|
||||||
|
}
|
||||||
|
extras[5].reason = contract.ReasonNoindex
|
||||||
|
markListedExtras(records, extras, site)
|
||||||
|
want := []string{models.ReasonDuplicate, models.ReasonDuplicate, "", "", "", contract.ReasonNoindex}
|
||||||
|
for i, w := range extras {
|
||||||
|
if w.reason != want[i] {
|
||||||
|
t.Errorf("extra %s: reason %q, want %q", w.url, w.reason, want[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without a site URL the paths are compared as they are.
|
||||||
|
extras = extraRows([]models.ExtraURL{{URL: "/blog"}, {URL: site + "/blog"}})
|
||||||
|
markListedExtras(records, extras, "")
|
||||||
|
if extras[0].reason != models.ReasonDuplicate || extras[1].reason != "" {
|
||||||
|
t.Fatalf("without a site URL: %q %q, want duplicate and listed", extras[0].reason, extras[1].reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
package classes
|
|
||||||
|
|
||||||
import (
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
)
|
|
||||||
|
|
||||||
// The PHP routes.php patterns of the frontend rewrite.
|
|
||||||
var (
|
|
||||||
locElement = regexp.MustCompile(`<loc>(.*?)</loc>`)
|
|
||||||
xhtmlLinkRef = regexp.MustCompile(`(<xhtml:link[^>]*href=")([^"]*)(")`)
|
|
||||||
)
|
|
||||||
|
|
||||||
// Rewrite is the frontend_url rewrite of PHP routes.php: with frontendURL
|
|
||||||
// set, backendURL is replaced literally (str_replace) inside every loc
|
|
||||||
// element, inside every xhtml:link href and in the exact stylesheet href.
|
|
||||||
// Both URLs are right-trimmed of slashes first. An empty frontendURL (or
|
|
||||||
// "0", which PHP reads as false) leaves xml unchanged.
|
|
||||||
//
|
|
||||||
// PHP inserted the stored text as it was. Three rules keep that text out of
|
|
||||||
// the document unless it is a plain http(s) URL (T-17-15):
|
|
||||||
//
|
|
||||||
// - a frontendURL that models.AllowedFrontendURL refuses leaves xml
|
|
||||||
// unchanged, whatever is stored in the settings row;
|
|
||||||
// - the frontend URL is inserted through EscapeText in loc and through
|
|
||||||
// EscapeAttr in the hrefs. Both are the identity for every accepted
|
|
||||||
// value, which keeps the PHP bytes;
|
|
||||||
// - a loc or xhtml:link href whose rewritten value does not start with
|
|
||||||
// http:// or https:// keeps its value. The generator applies the same
|
|
||||||
// filter before the rewrite.
|
|
||||||
func Rewrite(xml, backendURL, frontendURL string) string {
|
|
||||||
if frontendURL == "" || frontendURL == "0" {
|
|
||||||
return xml
|
|
||||||
}
|
|
||||||
if !models.AllowedFrontendURL(frontendURL) {
|
|
||||||
return xml
|
|
||||||
}
|
|
||||||
frontend := strings.TrimRight(frontendURL, "/")
|
|
||||||
backend := strings.TrimRight(backendURL, "/")
|
|
||||||
if backend == "" {
|
|
||||||
return xml
|
|
||||||
}
|
|
||||||
frontendText, frontendAttr := EscapeText(frontend), EscapeAttr(frontend)
|
|
||||||
xml = locElement.ReplaceAllStringFunc(xml, func(m string) string {
|
|
||||||
inner := m[len("<loc>") : len(m)-len("</loc>")]
|
|
||||||
rewritten := strings.ReplaceAll(inner, backend, frontendText)
|
|
||||||
if !httpURL(rewritten) {
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
return "<loc>" + rewritten + "</loc>"
|
|
||||||
})
|
|
||||||
xml = xhtmlLinkRef.ReplaceAllStringFunc(xml, func(m string) string {
|
|
||||||
sub := xhtmlLinkRef.FindStringSubmatch(m)
|
|
||||||
rewritten := strings.ReplaceAll(sub[2], backend, frontendAttr)
|
|
||||||
if !httpURL(rewritten) {
|
|
||||||
return m
|
|
||||||
}
|
|
||||||
return sub[1] + rewritten + sub[3]
|
|
||||||
})
|
|
||||||
return strings.ReplaceAll(xml, `href="`+backend+`/sitemap.xsl"`, `href="`+frontendAttr+`/sitemap.xsl"`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// BackendURL is PHP rtrim(url('/'), '/') for a request whose root URL is
|
|
||||||
// root: the URL the rewrite replaces.
|
|
||||||
func BackendURL(root string) string {
|
|
||||||
return strings.TrimRight(URLTo(root, "/"), "/")
|
|
||||||
}
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
package classes_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
|
||||||
)
|
|
||||||
|
|
||||||
// rewriteBackend and rewriteDoc are the backend URL and the document of the
|
|
||||||
// rewrite tests: a stylesheet instruction, a loc, hreflang links and the
|
|
||||||
// backend URL in places the rewrite leaves alone.
|
|
||||||
const rewriteBackend = "https://api.ex.pl"
|
|
||||||
|
|
||||||
var rewriteDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
|
|
||||||
`<?xml-stylesheet type="text/xsl" href="https://api.ex.pl/sitemap.xsl"?>` + "\n" +
|
|
||||||
`<urlset><url><loc>https://api.ex.pl/a</loc><lastmod>2026</lastmod><changefreq>https://api.ex.pl</changefreq><priority>1</priority>` +
|
|
||||||
`<xhtml:link rel="alternate" hreflang="pl" href="https://api.ex.pl/a"/><xhtml:link rel="alternate" hreflang="en" href="https://api.ex.pl/en/a"/>` +
|
|
||||||
`<extra>https://api.ex.pl/x</extra></url><url><loc>https://other.pl/https://api.ex.pl</loc><changefreq>c</changefreq><priority>p</priority></url></urlset>` + "\n"
|
|
||||||
|
|
||||||
// TestRewrite pins the PHP routes.php frontend_url rewrite: the backend URL
|
|
||||||
// is replaced inside loc, inside xhtml:link href and in the exact stylesheet
|
|
||||||
// href, nowhere else; slashes are trimmed on both; an empty or "0" frontend
|
|
||||||
// URL and equal URLs leave the document unchanged.
|
|
||||||
func TestRewrite(t *testing.T) {
|
|
||||||
const backend = rewriteBackend
|
|
||||||
doc := rewriteDoc
|
|
||||||
want := "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
|
|
||||||
`<?xml-stylesheet type="text/xsl" href="https://www.ex.pl/sitemap.xsl"?>` + "\n" +
|
|
||||||
`<urlset><url><loc>https://www.ex.pl/a</loc><lastmod>2026</lastmod><changefreq>https://api.ex.pl</changefreq><priority>1</priority>` +
|
|
||||||
`<xhtml:link rel="alternate" hreflang="pl" href="https://www.ex.pl/a"/><xhtml:link rel="alternate" hreflang="en" href="https://www.ex.pl/en/a"/>` +
|
|
||||||
`<extra>https://api.ex.pl/x</extra></url><url><loc>https://other.pl/https://www.ex.pl</loc><changefreq>c</changefreq><priority>p</priority></url></urlset>` + "\n"
|
|
||||||
for _, frontend := range []string{"https://www.ex.pl", "https://www.ex.pl/", "https://www.ex.pl///"} {
|
|
||||||
for _, back := range []string{backend, backend + "/"} {
|
|
||||||
if got := classes.Rewrite(doc, back, frontend); got != want {
|
|
||||||
t.Fatalf("Rewrite(%q, %q):\n%s\nwant:\n%s", back, frontend, got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, frontend := range []string{"", "0"} {
|
|
||||||
if got := classes.Rewrite(doc, backend, frontend); got != doc {
|
|
||||||
t.Fatalf("frontend %q changed the document", frontend)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if got := classes.Rewrite(doc, backend, backend); got != doc {
|
|
||||||
t.Fatal("equal URLs changed the document")
|
|
||||||
}
|
|
||||||
if got := classes.Rewrite(doc, backend+"/", backend); got != doc {
|
|
||||||
t.Fatal("equal URLs up to a slash changed the document")
|
|
||||||
}
|
|
||||||
// An empty backend URL replaces nothing.
|
|
||||||
if got := classes.Rewrite(doc, "", "https://www.ex.pl"); got != doc {
|
|
||||||
t.Fatal("an empty backend URL changed the document")
|
|
||||||
}
|
|
||||||
// A stylesheet on another path is not the PHP pattern.
|
|
||||||
other := `<?xml-stylesheet type="text/xsl" href="https://api.ex.pl/other.xsl"?>`
|
|
||||||
if got := classes.Rewrite(other, backend, "https://www.ex.pl"); got != other {
|
|
||||||
t.Fatalf("other stylesheet = %q", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The two frontend_url values of the T-17-15 reproduction: a script URL the
|
|
||||||
// stylesheet would render as a link, and a value that closes the attribute
|
|
||||||
// and the element it is written into.
|
|
||||||
var frontendAttacks = []string{
|
|
||||||
"javascript:alert(document.domain)//",
|
|
||||||
`https://x"/><y a="`,
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestRewriteUnsafeFrontendURL pins the T-17-15 output rule: a frontend URL
|
|
||||||
// that models.AllowedFrontendURL refuses leaves the document byte for byte
|
|
||||||
// as it was, so no part of it reaches loc, an hreflang href or the
|
|
||||||
// stylesheet instruction; an accepted one still rewrites; and a loc or href
|
|
||||||
// that the rewrite would turn into something other than an http(s) URL
|
|
||||||
// keeps its value.
|
|
||||||
func TestRewriteUnsafeFrontendURL(t *testing.T) {
|
|
||||||
refused := append([]string{
|
|
||||||
"https://www.ex.pl/?a=1&b=2",
|
|
||||||
"https://www.ex.pl <x>",
|
|
||||||
" https://www.ex.pl",
|
|
||||||
"https://www.ex.pl\n",
|
|
||||||
"//www.ex.pl",
|
|
||||||
"www.ex.pl",
|
|
||||||
"https:///x",
|
|
||||||
"data:text/html,x",
|
|
||||||
}, frontendAttacks...)
|
|
||||||
for _, frontend := range refused {
|
|
||||||
if got := classes.Rewrite(rewriteDoc, rewriteBackend, frontend); got != rewriteDoc {
|
|
||||||
t.Errorf("frontend %q changed the document:\n%s", frontend, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The reproduction through the generator.
|
|
||||||
const root = "https://api.example.test"
|
|
||||||
xml, err := (&classes.Generator{Root: root}).Generate(context.Background(), urlItems("/blog/x"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if !strings.Contains(xml, `href="https://api.example.test/sitemap.xsl"`) {
|
|
||||||
t.Fatalf("the generated document lacks the stylesheet instruction:\n%s", xml)
|
|
||||||
}
|
|
||||||
for _, frontend := range frontendAttacks {
|
|
||||||
got := classes.Rewrite(xml, classes.BackendURL(root), frontend)
|
|
||||||
if got != xml {
|
|
||||||
t.Errorf("frontend %q changed the generated sitemap:\n%s", frontend, got)
|
|
||||||
}
|
|
||||||
if !strings.Contains(got, "<loc>https://api.example.test/blog/x</loc>") {
|
|
||||||
t.Errorf("frontend %q: the loc is not on the backend URL:\n%s", frontend, got)
|
|
||||||
}
|
|
||||||
if lower := strings.ToLower(got); strings.Contains(lower, "javascript") || strings.Contains(lower, "<y a=") {
|
|
||||||
t.Errorf("frontend %q reached the sitemap:\n%s", frontend, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A value the predicate accepts still rewrites all three places.
|
|
||||||
got := classes.Rewrite(xml, classes.BackendURL(root), "https://www.example.test")
|
|
||||||
if !strings.Contains(got, "<loc>https://www.example.test/blog/x</loc>") || !strings.Contains(got, `href="https://www.example.test/sitemap.xsl"`) || strings.Contains(got, "api.example.test") {
|
|
||||||
t.Errorf("a valid frontend URL did not rewrite the sitemap:\n%s", got)
|
|
||||||
}
|
|
||||||
if got := classes.Rewrite(xml, classes.BackendURL(root), "HTTPS://WWW.EXAMPLE.TEST"); !strings.Contains(got, "<loc>HTTPS://WWW.EXAMPLE.TEST/blog/x</loc>") {
|
|
||||||
t.Errorf("an upper-case frontend URL did not rewrite the loc:\n%s", got)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The http(s) output filter after the rewrite: replacing "s://api.ex.pl"
|
|
||||||
// would write httphttps://www.ex.pl/a, so loc and href keep their values.
|
|
||||||
entry := `<url><loc>https://api.ex.pl/a</loc><xhtml:link rel="alternate" hreflang="pl" href="https://api.ex.pl/a"/></url>`
|
|
||||||
if got := classes.Rewrite(entry, "s://api.ex.pl", "https://www.ex.pl"); got != entry {
|
|
||||||
t.Errorf("a rewrite to a non-http(s) URL was written:\n%s", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
package classes
|
|
||||||
|
|
||||||
import "strings"
|
|
||||||
|
|
||||||
// The sitemap document is written by hand in the exact format PHP's
|
|
||||||
// DOMDocument::saveXML (libxml2) produced for the PHP plugin: the XML
|
|
||||||
// declaration and the stylesheet processing instruction each followed by a
|
|
||||||
// newline, everything else on one line, an empty urlset self-closed,
|
|
||||||
// xhtml:link elements self-closed without a space. The standard library's
|
|
||||||
// XML encoder escapes and closes elements differently, so the writer is a
|
|
||||||
// strings.Builder.
|
|
||||||
|
|
||||||
// The urlset opening tag's attributes, in the order PHP set them.
|
|
||||||
const urlsetAttrs = ` xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"` +
|
|
||||||
` xmlns:xhtml="http://www.w3.org/1999/xhtml"` +
|
|
||||||
` xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"` +
|
|
||||||
` xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"`
|
|
||||||
|
|
||||||
// textEscaper is libxml's escaping of text nodes: &, <, > and carriage
|
|
||||||
// return; quotes, tabs, newlines and UTF-8 stay literal.
|
|
||||||
var textEscaper = strings.NewReplacer("&", "&", "<", "<", ">", ">", "\r", " ")
|
|
||||||
|
|
||||||
// attrEscaper is libxml's escaping of attribute values: also the double
|
|
||||||
// quote, tab and newline; the single quote stays literal.
|
|
||||||
var attrEscaper = strings.NewReplacer(
|
|
||||||
"&", "&", "<", "<", ">", ">", `"`, """,
|
|
||||||
"\r", " ", "\t", "	", "\n", " ",
|
|
||||||
)
|
|
||||||
|
|
||||||
// EscapeText escapes s as libxml writes a text node.
|
|
||||||
func EscapeText(s string) string { return textEscaper.Replace(s) }
|
|
||||||
|
|
||||||
// EscapeAttr escapes s as libxml writes an attribute value.
|
|
||||||
func EscapeAttr(s string) string { return attrEscaper.Replace(s) }
|
|
||||||
|
|
||||||
// Alternate is one hreflang link of a sitemap URL.
|
|
||||||
type Alternate struct {
|
|
||||||
Hreflang string
|
|
||||||
Href string
|
|
||||||
}
|
|
||||||
|
|
||||||
// URLEntry is one url element: Loc, an optional Lastmod, Changefreq and
|
|
||||||
// Priority as they are written, the alternates (written only when there are
|
|
||||||
// more than one) and Extra, pre-escaped child XML that AddItem listeners
|
|
||||||
// appended, written before the closing tag.
|
|
||||||
type URLEntry struct {
|
|
||||||
Loc string
|
|
||||||
Lastmod string
|
|
||||||
Changefreq string
|
|
||||||
Priority string
|
|
||||||
Alternates []Alternate
|
|
||||||
Extra []string
|
|
||||||
}
|
|
||||||
|
|
||||||
// writeURL appends one url element.
|
|
||||||
func writeURL(b *strings.Builder, e URLEntry) {
|
|
||||||
b.WriteString("<url><loc>")
|
|
||||||
b.WriteString(EscapeText(e.Loc))
|
|
||||||
b.WriteString("</loc>")
|
|
||||||
if e.Lastmod != "" {
|
|
||||||
b.WriteString("<lastmod>")
|
|
||||||
b.WriteString(EscapeText(e.Lastmod))
|
|
||||||
b.WriteString("</lastmod>")
|
|
||||||
}
|
|
||||||
b.WriteString("<changefreq>")
|
|
||||||
b.WriteString(EscapeText(e.Changefreq))
|
|
||||||
b.WriteString("</changefreq><priority>")
|
|
||||||
b.WriteString(EscapeText(e.Priority))
|
|
||||||
b.WriteString("</priority>")
|
|
||||||
if len(e.Alternates) > 1 {
|
|
||||||
for _, a := range e.Alternates {
|
|
||||||
b.WriteString(`<xhtml:link rel="alternate" hreflang="`)
|
|
||||||
b.WriteString(EscapeAttr(a.Hreflang))
|
|
||||||
b.WriteString(`" href="`)
|
|
||||||
b.WriteString(EscapeAttr(a.Href))
|
|
||||||
b.WriteString(`"/>`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, x := range e.Extra {
|
|
||||||
b.WriteString(x)
|
|
||||||
}
|
|
||||||
b.WriteString("</url>")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Serialize writes the sitemap document: the XML declaration, the
|
|
||||||
// stylesheet processing instruction pointing at stylesheet (written as it
|
|
||||||
// is, like libxml writes PI data) and the urlset with entries.
|
|
||||||
func Serialize(stylesheet string, entries []URLEntry) string {
|
|
||||||
var b strings.Builder
|
|
||||||
b.WriteString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
|
|
||||||
b.WriteString(`<?xml-stylesheet type="text/xsl" href="`)
|
|
||||||
b.WriteString(stylesheet)
|
|
||||||
b.WriteString("\"?>\n<urlset")
|
|
||||||
b.WriteString(urlsetAttrs)
|
|
||||||
if len(entries) == 0 {
|
|
||||||
b.WriteString("/>\n")
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
b.WriteString(">")
|
|
||||||
for _, e := range entries {
|
|
||||||
writeURL(&b, e)
|
|
||||||
}
|
|
||||||
b.WriteString("</urlset>\n")
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
@@ -1,95 +0,0 @@
|
|||||||
package classes_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestXMLEscaping ports the PHP XmlEscapingTest (SITE-002) as behaviour:
|
|
||||||
// every value the sitemap writes is escaped exactly as libxml escapes it,
|
|
||||||
// text nodes (loc, lastmod, changefreq, priority) and attribute values
|
|
||||||
// (hreflang, href), and no raw value reaches the output.
|
|
||||||
func TestXMLEscaping(t *testing.T) {
|
|
||||||
const raw = "a&b<c>d\"e'f\rg\th\ni"
|
|
||||||
if got := classes.EscapeText(raw); got != "a&b<c>d\"e'f g\th\ni" {
|
|
||||||
t.Fatalf("EscapeText = %q", got)
|
|
||||||
}
|
|
||||||
if got := classes.EscapeAttr(raw); got != "a&b<c>d"e'f g	h i" {
|
|
||||||
t.Fatalf("EscapeAttr = %q", got)
|
|
||||||
}
|
|
||||||
if got := classes.EscapeText("zażółć — &"); got != "zażółć — &amp;" {
|
|
||||||
t.Fatalf("EscapeText keeps UTF-8 and escapes an existing entity again: %q", got)
|
|
||||||
}
|
|
||||||
|
|
||||||
xml := classes.Serialize("https://h/sitemap.xsl", []classes.URLEntry{{
|
|
||||||
Loc: "https://h/a?x=1&y=<2>",
|
|
||||||
Lastmod: "2026-01-02T03:04:05+00:00",
|
|
||||||
Changefreq: "weekly&<>",
|
|
||||||
Priority: "0.5\r",
|
|
||||||
Alternates: []classes.Alternate{
|
|
||||||
{Hreflang: "pl\"x", Href: "https://h/pl?a=1&b=\"2\"\t\n"},
|
|
||||||
{Hreflang: "en", Href: "https://h/en'x"},
|
|
||||||
},
|
|
||||||
}})
|
|
||||||
want := "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
|
|
||||||
"<?xml-stylesheet type=\"text/xsl\" href=\"https://h/sitemap.xsl\"?>\n" +
|
|
||||||
`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">` +
|
|
||||||
"<url><loc>https://h/a?x=1&y=<2></loc><lastmod>2026-01-02T03:04:05+00:00</lastmod><changefreq>weekly&<></changefreq><priority>0.5 </priority>" +
|
|
||||||
`<xhtml:link rel="alternate" hreflang="pl"x" href="https://h/pl?a=1&b="2"	 "/>` +
|
|
||||||
`<xhtml:link rel="alternate" hreflang="en" href="https://h/en'x"/>` +
|
|
||||||
"</url></urlset>\n"
|
|
||||||
if xml != want {
|
|
||||||
t.Fatalf("serialized:\n%q\nwant:\n%q", xml, want)
|
|
||||||
}
|
|
||||||
|
|
||||||
// One alternate is not written; an empty urlset is self-closed.
|
|
||||||
single := classes.Serialize("s", []classes.URLEntry{{Loc: "l", Changefreq: "c", Priority: "p", Alternates: []classes.Alternate{{Hreflang: "pl", Href: "x"}}}})
|
|
||||||
if strings.Contains(single, "xhtml:link") || strings.Contains(single, "<lastmod>") {
|
|
||||||
t.Fatalf("single alternate or empty lastmod written: %q", single)
|
|
||||||
}
|
|
||||||
if empty := classes.Serialize("s", nil); !strings.HasSuffix(empty, `sitemap.xsd"/>`+"\n") {
|
|
||||||
t.Fatalf("empty urlset = %q", empty)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Through the generator: stored changefreq and priority, a resolved
|
|
||||||
// alternate's locale and a url item with every special character.
|
|
||||||
url := "/q?a=1&b=<x>&c=\"y\""
|
|
||||||
changefreq := "daily&<weekly>"
|
|
||||||
priority := "0.9\"'"
|
|
||||||
gen := &classes.Generator{Root: "https://api.example.test", Settings: models.Settings{}, Resolver: fakeResolver{t: t, types: map[string]map[string]goldenResolved{
|
|
||||||
"acme-post": {"1": {URL: "/p?x=1&y=2", Alternates: [][2]string{{"pl&<", "/p?x=1&y=2"}, {"en\"", "/en/p?z=<1>"}}}},
|
|
||||||
}}}
|
|
||||||
out, err := gen.Generate(context.Background(), []models.DefinitionItem{
|
|
||||||
{Type: models.ItemTypeURL, URL: &url, Changefreq: &changefreq, Priority: &priority},
|
|
||||||
{Type: "acme-post", Reference: text("1"), Changefreq: &changefreq, Priority: &priority},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
body := out[strings.Index(out, "<url>"):]
|
|
||||||
for _, bad := range []string{"<x>", "&b", "&y", `"y"`, "<weekly>", "daily&<", `hreflang="pl&<"`, `en""`, "<1>"} {
|
|
||||||
if strings.Contains(body, bad) {
|
|
||||||
t.Fatalf("raw value %q reached the output:\n%s", bad, body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, good := range []string{
|
|
||||||
"<changefreq>daily&<weekly></changefreq>",
|
|
||||||
"<priority>0.9\"'</priority>",
|
|
||||||
`hreflang="pl&<"`,
|
|
||||||
`hreflang="en""`,
|
|
||||||
"y=2",
|
|
||||||
} {
|
|
||||||
if !strings.Contains(body, good) {
|
|
||||||
t.Fatalf("output lacks %q:\n%s", good, body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if strings.Count(body, "<url>") != 2 {
|
|
||||||
t.Fatalf("urls = %d:\n%s", strings.Count(body, "<url>"), body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func text(s string) *string { return &s }
|
|
||||||
98
classes/settings.go
Normal file
98
classes/settings.go
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SiteURLConfigKey is the config key of the site address the sitemaps use
|
||||||
|
// when the setting is empty.
|
||||||
|
const SiteURLConfigKey = "golem15.sitemap.site_url"
|
||||||
|
|
||||||
|
// LoadSettings reads the settings row; without one the defaults apply.
|
||||||
|
func LoadSettings(db *gorm.DB) (models.Settings, error) {
|
||||||
|
var rows []models.Settings
|
||||||
|
if err := db.Where("id = ?", 1).Limit(1).Find(&rows).Error; err != nil {
|
||||||
|
return models.Settings{}, err
|
||||||
|
}
|
||||||
|
if len(rows) == 0 {
|
||||||
|
return models.DefaultSettings(), nil
|
||||||
|
}
|
||||||
|
return rows[0], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SiteURL is the absolute site address every <loc> starts with, without a
|
||||||
|
// trailing slash: the site_url setting, else the config key
|
||||||
|
// golem15.sitemap.site_url, else app.url (CONTEXT 2026-10-28). A value that
|
||||||
|
// is not an absolute http(s) URL (models.AllowedFrontendURL) is skipped.
|
||||||
|
// The request's Host header is never used; "" means no site address is
|
||||||
|
// configured.
|
||||||
|
func SiteURL(app *backpack.App, s models.Settings) string {
|
||||||
|
candidates := []string{models.Text(s.SiteURL)}
|
||||||
|
if app != nil && app.Config != nil {
|
||||||
|
candidates = append(candidates, app.Config.String(SiteURLConfigKey), app.Config.String("app.url"))
|
||||||
|
}
|
||||||
|
for _, c := range candidates {
|
||||||
|
c = strings.TrimRight(strings.TrimSpace(c), "/")
|
||||||
|
if c != "" && models.AllowedFrontendURL(c) {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Absolute turns a stored address into the absolute URL of a <loc>: a path
|
||||||
|
// starting with a single / is put on site; an absolute http(s) URL is kept.
|
||||||
|
// Anything else, or a path without a site address, is "".
|
||||||
|
func Absolute(site, u string) string {
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(u, "/") && !strings.HasPrefix(u, "//"):
|
||||||
|
if site == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return site + u
|
||||||
|
case models.AllowedFrontendURL(u):
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// MergeHTMLPaths merges submitted HTML sitemap addresses (locale to path)
|
||||||
|
// into the stored ones: a sent locale replaces its address, a blank one
|
||||||
|
// removes it, the others keep theirs. problem is true when a sent address
|
||||||
|
// is not a models.ValidHTMLPath; nothing is merged then.
|
||||||
|
func MergeHTMLPaths(db *gorm.DB, sent map[string]string) (map[string]string, bool) {
|
||||||
|
settings, err := LoadSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return nil, true
|
||||||
|
}
|
||||||
|
merged := settings.EffectiveHTMLPaths()
|
||||||
|
for locale, path := range sent {
|
||||||
|
locale, path = strings.TrimSpace(locale), strings.TrimSpace(path)
|
||||||
|
if locale == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if path == "" {
|
||||||
|
delete(merged, locale)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !models.ValidHTMLPath(path) {
|
||||||
|
return nil, true
|
||||||
|
}
|
||||||
|
merged[locale] = path
|
||||||
|
}
|
||||||
|
return merged, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// StoreHTMLPaths writes the HTML sitemap addresses to settings row 1.
|
||||||
|
func StoreHTMLPaths(db *gorm.DB, paths map[string]string) error {
|
||||||
|
raw, err := json.Marshal(paths)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return db.Exec(`UPDATE golem15_sitemap_settings SET html_paths = ?::jsonb WHERE id = 1`, string(raw)).Error
|
||||||
|
}
|
||||||
95
classes/slots.go
Normal file
95
classes/slots.go
Normal file
@@ -0,0 +1,95 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"slices"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Slot is what file numbering needs of one row of the slot table: its
|
||||||
|
// group, its file number (nil while unnumbered), when it was first seen and
|
||||||
|
// whether it is listed. A row left out keeps its number: its file keeps the
|
||||||
|
// hole instead of the later files shifting (D-30, RESEARCH Pitfall 5).
|
||||||
|
type Slot struct {
|
||||||
|
ID uint64
|
||||||
|
Grp string
|
||||||
|
FileNo *int
|
||||||
|
FirstSeen time.Time
|
||||||
|
Listed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// AssignSlots numbers the rows for files of size addresses and reports
|
||||||
|
// whether any number changed. Without renumber, a numbered row keeps its
|
||||||
|
// number and every listed row without one is appended to the last file of
|
||||||
|
// its group while that file has room (counting the holes of left-out rows),
|
||||||
|
// then to the next file, oldest first (first seen, then id). With renumber
|
||||||
|
// (the file size changed), every group's listed rows are numbered again
|
||||||
|
// from file 1, oldest first, and the left-out rows lose their numbers.
|
||||||
|
func AssignSlots(rows []*Slot, size int, renumber bool) bool {
|
||||||
|
if size < 1 {
|
||||||
|
size = 1
|
||||||
|
}
|
||||||
|
groups := map[string][]*Slot{}
|
||||||
|
var order []string
|
||||||
|
for _, r := range rows {
|
||||||
|
if _, ok := groups[r.Grp]; !ok {
|
||||||
|
order = append(order, r.Grp)
|
||||||
|
}
|
||||||
|
groups[r.Grp] = append(groups[r.Grp], r)
|
||||||
|
}
|
||||||
|
changed := false
|
||||||
|
set := func(r *Slot, n *int) {
|
||||||
|
if (r.FileNo == nil) != (n == nil) || (r.FileNo != nil && *r.FileNo != *n) {
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
r.FileNo = n
|
||||||
|
}
|
||||||
|
for _, grp := range order {
|
||||||
|
members := groups[grp]
|
||||||
|
slices.SortStableFunc(members, func(a, b *Slot) int {
|
||||||
|
if c := a.FirstSeen.Compare(b.FirstSeen); c != 0 {
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case a.ID < b.ID:
|
||||||
|
return -1
|
||||||
|
case a.ID > b.ID:
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
})
|
||||||
|
if renumber {
|
||||||
|
i := 0
|
||||||
|
for _, r := range members {
|
||||||
|
if !r.Listed {
|
||||||
|
set(r, nil)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
n := i/size + 1
|
||||||
|
set(r, &n)
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
counts := map[int]int{}
|
||||||
|
last := 0
|
||||||
|
for _, r := range members {
|
||||||
|
if r.FileNo == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
counts[*r.FileNo]++
|
||||||
|
last = max(last, *r.FileNo)
|
||||||
|
}
|
||||||
|
for _, r := range members {
|
||||||
|
if r.FileNo != nil || !r.Listed {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if last == 0 || counts[last] >= size {
|
||||||
|
last++
|
||||||
|
}
|
||||||
|
n := last
|
||||||
|
set(r, &n)
|
||||||
|
counts[last]++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return changed
|
||||||
|
}
|
||||||
107
classes/slots_test.go
Normal file
107
classes/slots_test.go
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestAssignSlots pins stable numbering without a database (D-30, RESEARCH
|
||||||
|
// Pitfall 5): appends fill the last file of their group, a left-out row
|
||||||
|
// keeps its number as a hole, only a renumber packs the listed rows again,
|
||||||
|
// and groups are numbered apart.
|
||||||
|
func TestAssignSlots(t *testing.T) {
|
||||||
|
t0 := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
rows := []*Slot{}
|
||||||
|
add := func(id uint64, grp string, at time.Duration) *Slot {
|
||||||
|
s := &Slot{ID: id, Grp: grp, FirstSeen: t0.Add(at), Listed: true}
|
||||||
|
rows = append(rows, s)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
files := func(grp string) []int {
|
||||||
|
var out []int
|
||||||
|
for _, r := range rows {
|
||||||
|
if r.Grp == grp && r.Listed && r.FileNo != nil {
|
||||||
|
out = append(out, *r.FileNo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
eq := func(a []int, b ...int) bool {
|
||||||
|
if len(a) != len(b) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i := range a {
|
||||||
|
if a[i] != b[i] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
for i := uint64(1); i <= 5; i++ {
|
||||||
|
add(i, "pages", 0)
|
||||||
|
}
|
||||||
|
add(9, "posts", 0)
|
||||||
|
if !AssignSlots(rows, 2, true) || !eq(files("pages"), 1, 1, 2, 2, 3) || !eq(files("posts"), 1) {
|
||||||
|
t.Fatalf("first numbering: pages %v posts %v", files("pages"), files("posts"))
|
||||||
|
}
|
||||||
|
if AssignSlots(rows, 2, false) {
|
||||||
|
t.Fatal("a second pass changed numbers")
|
||||||
|
}
|
||||||
|
rows[1].Listed = false
|
||||||
|
if AssignSlots(rows, 2, false) || !eq(files("pages"), 1, 2, 2, 3) || *rows[1].FileNo != 1 {
|
||||||
|
t.Fatalf("after a delete: %v, hole %v", files("pages"), rows[1].FileNo)
|
||||||
|
}
|
||||||
|
add(6, "pages", time.Hour)
|
||||||
|
add(7, "pages", 2*time.Hour)
|
||||||
|
AssignSlots(rows, 2, false)
|
||||||
|
if *rows[len(rows)-2].FileNo != 3 || *rows[len(rows)-1].FileNo != 4 {
|
||||||
|
t.Fatalf("appends: %v %v", *rows[len(rows)-2].FileNo, *rows[len(rows)-1].FileNo)
|
||||||
|
}
|
||||||
|
AssignSlots(rows, 3, true)
|
||||||
|
if !eq(files("pages"), 1, 1, 1, 2, 2, 2) || rows[1].FileNo != nil {
|
||||||
|
t.Fatalf("renumber: %v, left-out row %v", files("pages"), rows[1].FileNo)
|
||||||
|
}
|
||||||
|
// A returning row fills its own hole when it still has one.
|
||||||
|
rows[1].Listed = true
|
||||||
|
n := 1
|
||||||
|
rows[1].FileNo = &n
|
||||||
|
AssignSlots(rows, 3, false)
|
||||||
|
if *rows[1].FileNo != 1 {
|
||||||
|
t.Fatalf("returning row moved to %d", *rows[1].FileNo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestAssignSlotsEdges pins the edges: a size below 1 counts as 1, the
|
||||||
|
// oldest unnumbered row is appended first (first seen, then id), an empty
|
||||||
|
// table changes nothing, and a renumber with nothing listed clears every
|
||||||
|
// number.
|
||||||
|
func TestAssignSlotsEdges(t *testing.T) {
|
||||||
|
if AssignSlots(nil, 10, true) {
|
||||||
|
t.Fatal("an empty table changed")
|
||||||
|
}
|
||||||
|
t0 := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
|
||||||
|
rows := []*Slot{
|
||||||
|
{ID: 3, Grp: "pages", FirstSeen: t0, Listed: true},
|
||||||
|
{ID: 1, Grp: "pages", FirstSeen: t0.Add(time.Minute), Listed: true},
|
||||||
|
{ID: 2, Grp: "pages", FirstSeen: t0, Listed: true},
|
||||||
|
}
|
||||||
|
if !AssignSlots(rows, 0, false) {
|
||||||
|
t.Fatal("numbering reported no change")
|
||||||
|
}
|
||||||
|
// Size 0 is 1: one row per file, oldest first (id 2 before id 3 at the
|
||||||
|
// same time, then id 1).
|
||||||
|
if *rows[2].FileNo != 1 || *rows[0].FileNo != 2 || *rows[1].FileNo != 3 {
|
||||||
|
t.Fatalf("files: id3=%d id1=%d id2=%d", *rows[0].FileNo, *rows[1].FileNo, *rows[2].FileNo)
|
||||||
|
}
|
||||||
|
for _, r := range rows {
|
||||||
|
r.Listed = false
|
||||||
|
}
|
||||||
|
if !AssignSlots(rows, 5, true) {
|
||||||
|
t.Fatal("renumber reported no change")
|
||||||
|
}
|
||||||
|
for _, r := range rows {
|
||||||
|
if r.FileNo != nil {
|
||||||
|
t.Fatalf("row %d kept file %d after a renumber with nothing listed", r.ID, *r.FileNo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
58
classes/testdata/full.golden
vendored
58
classes/testdata/full.golden
vendored
@@ -1,58 +0,0 @@
|
|||||||
=== escaping
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://a&b<c>.pl/x</loc><changefreq>a&b<c>"d'e f g
|
|
||||||
h</changefreq><priority>0.5 & <1> "q" 'a'</priority></url><url><loc>https://api.example.test/za%C5%BC%C3%B3%C5%82%C4%87%20%26%20co</loc><lastmod>2026-01-02T03:04:05+00:00</lastmod><changefreq>x>y</changefreq><priority><0.9></priority><xhtml:link rel="alternate" hreflang="x"y&z<	 '>" href="https://q&r<s>.pl/p"/><xhtml:link rel="alternate" hreflang="en" href="https://api.example.test/en/za%C5%BC%C3%B3%C5%82%C4%87"/></url></urlset>
|
|
||||||
=== empty-urlset
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"/>
|
|
||||||
=== no-items
|
|
||||||
=== hreflang-list
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://api.example.test/pl/a</loc><lastmod>2026-02-01T00:00:00+00:00</lastmod><changefreq>monthly</changefreq><priority>0.4</priority><xhtml:link rel="alternate" hreflang="pl" href="https://api.example.test/pl/a"/><xhtml:link rel="alternate" hreflang="en" href="https://api.example.test/en/a"/></url><url><loc>https://api.example.test/en/a</loc><lastmod>2026-02-01T00:00:00+00:00</lastmod><changefreq>monthly</changefreq><priority>0.4</priority><xhtml:link rel="alternate" hreflang="pl" href="https://api.example.test/pl/a"/><xhtml:link rel="alternate" hreflang="en" href="https://api.example.test/en/a"/></url><url><loc>https://api.example.test/pl/b</loc><changefreq>monthly</changefreq><priority>0.4</priority><xhtml:link rel="alternate" hreflang="pl" href="https://api.example.test/pl/b"/><xhtml:link rel="alternate" hreflang="en" href="https://api.example.test/en/b"/><xhtml:link rel="alternate" hreflang="de" href="https://api.example.test/de/b"/></url><url><loc>https://api.example.test/en/b</loc><changefreq>monthly</changefreq><priority>0.4</priority><xhtml:link rel="alternate" hreflang="pl" href="https://api.example.test/pl/b"/><xhtml:link rel="alternate" hreflang="en" href="https://api.example.test/en/b"/><xhtml:link rel="alternate" hreflang="de" href="https://api.example.test/de/b"/></url><url><loc>https://api.example.test/de/b</loc><changefreq>monthly</changefreq><priority>0.4</priority><xhtml:link rel="alternate" hreflang="pl" href="https://api.example.test/pl/b"/><xhtml:link rel="alternate" hreflang="en" href="https://api.example.test/en/b"/><xhtml:link rel="alternate" hreflang="de" href="https://api.example.test/de/b"/></url><url><loc>https://api.example.test/solo</loc><changefreq>monthly</changefreq><priority>0.4</priority></url></urlset>
|
|
||||||
=== nested
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://api.example.test/kategoria/a</loc><lastmod>2026-03-01T12:00:00+00:00</lastmod><changefreq>daily</changefreq><priority>0.7</priority><xhtml:link rel="alternate" hreflang="pl" href="https://api.example.test/kategoria/a"/><xhtml:link rel="alternate" hreflang="en" href="https://api.example.test/en/category/a"/></url><url><loc>https://api.example.test/kategoria/b</loc><lastmod>2026-03-02T12:00:00+00:00</lastmod><changefreq>daily</changefreq><priority>0.7</priority><xhtml:link rel="alternate" hreflang="pl" href="https://api.example.test/kategoria/b"/><xhtml:link rel="alternate" hreflang="en" href="https://api.example.test/en/category/b"/></url><url><loc>https://api.example.test/kategoria/c</loc><changefreq>daily</changefreq><priority>0.7</priority></url></urlset>
|
|
||||||
=== tiers-default
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://api.example.test/</loc><changefreq>weekly</changefreq><priority>1.0</priority></url><url><loc>https://api.example.test/en</loc><changefreq>weekly</changefreq><priority>1.0</priority></url><url><loc>https://api.example.test/en</loc><changefreq>weekly</changefreq><priority>1.0</priority></url><url><loc>https://api.example.test/uslugi/x</loc><changefreq>weekly</changefreq><priority>0.8</priority></url><url><loc>https://api.example.test/uslugi/x/y</loc><changefreq>weekly</changefreq><priority>0.3</priority></url><url><loc>https://api.example.test/realizacje/r</loc><changefreq>weekly</changefreq><priority>0.8</priority></url><url><loc>https://api.example.test/en/work/w</loc><changefreq>weekly</changefreq><priority>0.8</priority></url><url><loc>https://api.example.test/blog/a/b</loc><changefreq>weekly</changefreq><priority>0.6</priority></url><url><loc>https://api.example.test/en/blog/a/b</loc><changefreq>weekly</changefreq><priority>0.6</priority></url><url><loc>https://api.example.test/blog/a</loc><changefreq>weekly</changefreq><priority>0.4</priority></url><url><loc>https://api.example.test/blog</loc><changefreq>weekly</changefreq><priority>0.4</priority></url><url><loc>https://api.example.test/en/blog</loc><changefreq>weekly</changefreq><priority>0.4</priority></url><url><loc>https://api.example.test/uslugi</loc><changefreq>weekly</changefreq><priority>0.4</priority></url><url><loc>https://api.example.test/kontakt</loc><changefreq>weekly</changefreq><priority>0.2</priority></url><url><loc>https://api.example.test/kontakt</loc><changefreq>weekly</changefreq><priority>0.2</priority></url><url><loc>https://api.example.test/en/ai-lab/blob-playground</loc><changefreq>weekly</changefreq><priority>0.2</priority></url><url><loc>https://api.example.test/other</loc><changefreq>weekly</changefreq><priority>0.3</priority></url><url><loc>https://elsewhere.pl/uslugi/z</loc><changefreq>weekly</changefreq><priority>0.8</priority></url><url><loc>https://api.example.test/o-nas?x=1</loc><changefreq>weekly</changefreq><priority>0.2</priority></url><url><loc>https://api.example.test/blog/a/b/c</loc><changefreq>weekly</changefreq><priority>0.3</priority></url></urlset>
|
|
||||||
=== tiers-settings
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://api.example.test/</loc><changefreq>weekly</changefreq><priority>0.95</priority></url><url><loc>https://api.example.test/blog/a/b</loc><changefreq>weekly</changefreq><priority></priority></url><url><loc>https://api.example.test/regulamin</loc><changefreq>weekly</changefreq><priority>0.15</priority></url><url><loc>https://api.example.test/x</loc><changefreq>weekly</changefreq><priority>0.3</priority></url></urlset>
|
|
||||||
=== tiers-off
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://api.example.test/</loc><changefreq>weekly</changefreq><priority>0.1</priority></url><url><loc>https://api.example.test/blog/a/b</loc><changefreq>weekly</changefreq><priority>0.2</priority></url></urlset>
|
|
||||||
=== rewrite
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://www.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://www.example.test/</loc><changefreq>weekly</changefreq><priority>0.5</priority></url><url><loc>https://www.example.test/a</loc><changefreq>weekly</changefreq><priority>0.5</priority></url><url><loc>https://www.example.test/b?x=https%3A%2F%2Fapi.example.test%2Fc</loc><changefreq>weekly</changefreq><priority>0.5</priority></url><url><loc>https://other.example.test/api.example.test</loc><changefreq>weekly</changefreq><priority>0.5</priority></url><url><loc>https://www.example.test/p</loc><changefreq>daily</changefreq><priority>0.7</priority><xhtml:link rel="alternate" hreflang="pl" href="https://www.example.test/p"/><xhtml:link rel="alternate" hreflang="en" href="https://www.example.test/en/p"/></url><url><loc>https://www.example.test/en/p</loc><changefreq>daily</changefreq><priority>0.7</priority><xhtml:link rel="alternate" hreflang="pl" href="https://www.example.test/p"/><xhtml:link rel="alternate" hreflang="en" href="https://www.example.test/en/p"/></url></urlset>
|
|
||||||
=== rewrite-same
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://api.example.test/a</loc><changefreq>weekly</changefreq><priority>0.5</priority></url></urlset>
|
|
||||||
=== manifest
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://api.example.test/</loc><lastmod>2026-05-01T08:00:00+00:00</lastmod><changefreq>weekly</changefreq><priority>0.5</priority></url><url><loc>https://api.example.test/about</loc><lastmod>2026-05-02T00:00:00+00:00</lastmod><changefreq>weekly</changefreq><priority>0.5</priority></url><url><loc>https://api.example.test/about</loc><lastmod>2026-05-02T00:00:00+00:00</lastmod><changefreq>weekly</changefreq><priority>0.5</priority></url><url><loc>https://api.example.test/blog/x</loc><changefreq>weekly</changefreq><priority>0.5</priority></url><url><loc>https://api.example.test/none</loc><changefreq>weekly</changefreq><priority>0.5</priority></url><url><loc>https://api.example.test/rel</loc><lastmod>2026-05-03T01:02:03+00:00</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url><url><loc>https://api.example.test/about</loc><lastmod>2026-06-01T00:00:00+00:00</lastmod><changefreq>daily</changefreq><priority>0.7</priority></url></urlset>
|
|
||||||
=== skip-extra
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://api.example.test/extra</loc><changefreq>weekly</changefreq><priority>0.5</priority><extra>a&b <c></extra></url><url><loc>https://api.example.test/keep</loc><changefreq>weekly</changefreq><priority>0.5</priority></url></urlset>
|
|
||||||
=== precision
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://api.example.test/p1</loc><changefreq>daily</changefreq><priority>0.5</priority></url><url><loc>https://api.example.test/p2</loc><changefreq>daily</changefreq><priority>1</priority></url><url><loc>https://api.example.test/p3</loc><changefreq>7</changefreq><priority>1</priority></url><url><loc>https://api.example.test/p4</loc><changefreq>daily</changefreq><priority>1.0</priority></url><url><loc>https://api.example.test/p5</loc><changefreq>daily</changefreq><priority>0.50</priority></url><url><loc>https://api.example.test/p6</loc><changefreq>daily</changefreq><priority>0.6</priority></url></urlset>
|
|
||||||
=== url-null
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://api.example.test/</loc><changefreq></changefreq><priority></priority></url><url><loc>https://api.example.test/0</loc><changefreq>daily</changefreq><priority>0.5</priority></url></urlset>
|
|
||||||
=== port-root
|
|
||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="http://localhost:8096/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>http://localhost:8096/</loc><changefreq>weekly</changefreq><priority>0.5</priority></url><url><loc>http://localhost:8096/a%20b</loc><changefreq>weekly</changefreq><priority>0.5</priority></url></urlset>
|
|
||||||
693
classes/testdata/full.json
vendored
693
classes/testdata/full.json
vendored
@@ -1,693 +0,0 @@
|
|||||||
{
|
|
||||||
"cases": [
|
|
||||||
{
|
|
||||||
"name": "escaping",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"settings": {
|
|
||||||
"enable_priority_tiers": false
|
|
||||||
},
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "https://a&b<c>.pl/x",
|
|
||||||
"changefreq": "a&b<c>\"d'e\rf\tg\nh",
|
|
||||||
"priority": "0.5 & <1> \"q\" 'a'"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "acme-post",
|
|
||||||
"reference": "1",
|
|
||||||
"urlPattern": "",
|
|
||||||
"changefreq": "x>y",
|
|
||||||
"priority": "<0.9>",
|
|
||||||
"nesting": "1"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"types": {
|
|
||||||
"acme-post": {
|
|
||||||
"1": {
|
|
||||||
"url": "/zażółć & co",
|
|
||||||
"mtime": "2026-01-02T03:04:05+00:00",
|
|
||||||
"alternates": [
|
|
||||||
[
|
|
||||||
"x\"y&z<\t\n\r'>",
|
|
||||||
"https://q&r<s>.pl/p"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"en",
|
|
||||||
"/en/zażółć"
|
|
||||||
]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "empty-urlset",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "acme-post",
|
|
||||||
"reference": "404",
|
|
||||||
"urlPattern": "",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": "0.7",
|
|
||||||
"nesting": "1"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "unknown-type",
|
|
||||||
"reference": "1",
|
|
||||||
"urlPattern": "",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": "0.7",
|
|
||||||
"nesting": "1"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"types": {
|
|
||||||
"acme-post": {}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "no-items",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"items": []
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "hreflang-list",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"settings": {
|
|
||||||
"enable_priority_tiers": false
|
|
||||||
},
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "acme-list",
|
|
||||||
"reference": "",
|
|
||||||
"urlPattern": "",
|
|
||||||
"changefreq": "monthly",
|
|
||||||
"priority": "0.4",
|
|
||||||
"nesting": "1"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"types": {
|
|
||||||
"acme-list": {
|
|
||||||
"": {
|
|
||||||
"url": "",
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"url": "/pl/a",
|
|
||||||
"mtime": "2026-02-01T00:00:00+00:00",
|
|
||||||
"alternates": [
|
|
||||||
[
|
|
||||||
"pl",
|
|
||||||
"/pl/a"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"en",
|
|
||||||
"/en/a"
|
|
||||||
]
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"url": "/pl/b",
|
|
||||||
"mtime": null,
|
|
||||||
"alternates": [
|
|
||||||
[
|
|
||||||
"pl",
|
|
||||||
"/pl/b"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"en",
|
|
||||||
"/en/b"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"de",
|
|
||||||
"/de/b"
|
|
||||||
]
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"url": "/solo",
|
|
||||||
"alternates": []
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "nested",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"settings": {
|
|
||||||
"enable_priority_tiers": false
|
|
||||||
},
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "acme-cat",
|
|
||||||
"reference": "5",
|
|
||||||
"urlPattern": "",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": "0.7",
|
|
||||||
"nesting": "1"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"types": {
|
|
||||||
"acme-cat": {
|
|
||||||
"5": {
|
|
||||||
"url": "/kategoria/a",
|
|
||||||
"mtime": "2026-03-01T12:00:00+00:00",
|
|
||||||
"alternates": [
|
|
||||||
[
|
|
||||||
"pl",
|
|
||||||
"/kategoria/a"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"en",
|
|
||||||
"/en/category/a"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"url": "/kategoria/b",
|
|
||||||
"mtime": "2026-03-02T12:00:00+00:00",
|
|
||||||
"alternates": [
|
|
||||||
[
|
|
||||||
"pl",
|
|
||||||
"/kategoria/b"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"en",
|
|
||||||
"/en/category/b"
|
|
||||||
]
|
|
||||||
],
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"url": "/kategoria/c",
|
|
||||||
"alternates": [
|
|
||||||
[
|
|
||||||
"x-default",
|
|
||||||
"/kategoria/c"
|
|
||||||
]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "tiers-default",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/en",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/en/",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/uslugi/x",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/uslugi/x/y",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/realizacje/r",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/en/work/w",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/blog/a/b",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/en/blog/a/b",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/blog/a",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/blog",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/en/blog/",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/uslugi",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/kontakt",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/kontakt/",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/en/ai-lab/blob-playground",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/other",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "https://elsewhere.pl/uslugi/z",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/o-nas?x=1",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/blog/a/b/c",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "tiers-settings",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"settings": {
|
|
||||||
"enable_priority_tiers": true,
|
|
||||||
"priority_homepage": "0.95",
|
|
||||||
"priority_blog": "",
|
|
||||||
"priority_legal": "0.15"
|
|
||||||
},
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/blog/a/b",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/regulamin",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/x",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.3"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "tiers-off",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"settings": {
|
|
||||||
"enable_priority_tiers": false
|
|
||||||
},
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.1"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/blog/a/b",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.2"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "rewrite",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"settings": {
|
|
||||||
"frontend_url": "https://www.example.test/",
|
|
||||||
"enable_priority_tiers": false
|
|
||||||
},
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/a",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "https://api.example.test/b?x=https://api.example.test/c",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "https://other.example.test/api.example.test",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "acme-list",
|
|
||||||
"reference": "",
|
|
||||||
"urlPattern": "",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": "0.7",
|
|
||||||
"nesting": "1"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"types": {
|
|
||||||
"acme-list": {
|
|
||||||
"": {
|
|
||||||
"url": "",
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"url": "/p",
|
|
||||||
"alternates": [
|
|
||||||
[
|
|
||||||
"pl",
|
|
||||||
"/p"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"en",
|
|
||||||
"https://api.example.test/en/p"
|
|
||||||
]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "rewrite-same",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"settings": {
|
|
||||||
"frontend_url": "https://api.example.test",
|
|
||||||
"enable_priority_tiers": false
|
|
||||||
},
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/a",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "manifest",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"settings": {
|
|
||||||
"enable_priority_tiers": false
|
|
||||||
},
|
|
||||||
"manifest": {
|
|
||||||
"/": "2026-05-01T10:00:00+02:00",
|
|
||||||
"about/": "2026-05-02",
|
|
||||||
"/blog/x": "not a date",
|
|
||||||
"/rel": "2026-05-03T01:02:03Z"
|
|
||||||
},
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/about",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/about/",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/blog/x",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/none",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "acme-post",
|
|
||||||
"reference": "2",
|
|
||||||
"urlPattern": "",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": "0.7",
|
|
||||||
"nesting": "1"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "acme-post",
|
|
||||||
"reference": "3",
|
|
||||||
"urlPattern": "",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": "0.7",
|
|
||||||
"nesting": "1"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"types": {
|
|
||||||
"acme-post": {
|
|
||||||
"2": {
|
|
||||||
"url": "/rel",
|
|
||||||
"mtime": null,
|
|
||||||
"alternates": [
|
|
||||||
[
|
|
||||||
"pl",
|
|
||||||
"/rel"
|
|
||||||
]
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"3": {
|
|
||||||
"url": "/about",
|
|
||||||
"mtime": "2026-06-01T00:00:00+00:00",
|
|
||||||
"alternates": [
|
|
||||||
[
|
|
||||||
"pl",
|
|
||||||
"/about"
|
|
||||||
]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "skip-extra",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"settings": {
|
|
||||||
"enable_priority_tiers": false
|
|
||||||
},
|
|
||||||
"skip": [
|
|
||||||
"https://api.example.test/skip-me",
|
|
||||||
"/rel-skip"
|
|
||||||
],
|
|
||||||
"extra": {
|
|
||||||
"https://api.example.test/extra": "a&b <c>"
|
|
||||||
},
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/skip-me",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/extra",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/keep",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "acme-post",
|
|
||||||
"reference": "9",
|
|
||||||
"urlPattern": "",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": "0.7",
|
|
||||||
"nesting": "1"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"types": {
|
|
||||||
"acme-post": {
|
|
||||||
"9": {
|
|
||||||
"url": "/rel-skip",
|
|
||||||
"alternates": [
|
|
||||||
[
|
|
||||||
"pl",
|
|
||||||
"/rel-skip"
|
|
||||||
]
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "precision",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"settings": {
|
|
||||||
"enable_priority_tiers": false
|
|
||||||
},
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/p1",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": 0.5
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/p2",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": 1.0
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/p3",
|
|
||||||
"changefreq": 7,
|
|
||||||
"priority": 1
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/p4",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": "1.0"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/p5",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": "0.50"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"url": "/p6",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": "0.6",
|
|
||||||
"cmsPage": "x",
|
|
||||||
"exists": true,
|
|
||||||
"fillable": [
|
|
||||||
"a"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "url-null",
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"settings": {
|
|
||||||
"enable_priority_tiers": false
|
|
||||||
},
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": null,
|
|
||||||
"changefreq": null,
|
|
||||||
"priority": null
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "0",
|
|
||||||
"changefreq": "daily",
|
|
||||||
"priority": "0.5"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "port-root",
|
|
||||||
"root": "http://localhost:8096",
|
|
||||||
"settings": {
|
|
||||||
"enable_priority_tiers": false
|
|
||||||
},
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"type": "url",
|
|
||||||
"url": "/a b",
|
|
||||||
"changefreq": "weekly",
|
|
||||||
"priority": "0.5"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
3
classes/testdata/tracer.golden
vendored
3
classes/testdata/tracer.golden
vendored
@@ -1,3 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<?xml-stylesheet type="text/xsl" href="https://api.example.test/sitemap.xsl"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"><url><loc>https://api.example.test/</loc><changefreq>always</changefreq><priority>1.0</priority></url><url><loc>https://api.example.test/news/hello</loc><lastmod>2026-03-04T10:00:00+00:00</lastmod><changefreq>weekly</changefreq><priority>0.5</priority><xhtml:link rel="alternate" hreflang="pl" href="https://api.example.test/news/hello"/><xhtml:link rel="alternate" hreflang="en" href="https://api.example.test/en/news/hello"/></url></urlset>
|
|
||||||
18
classes/testdata/tracer.json
vendored
18
classes/testdata/tracer.json
vendored
@@ -1,18 +0,0 @@
|
|||||||
{
|
|
||||||
"case": {
|
|
||||||
"root": "https://api.example.test",
|
|
||||||
"items": [
|
|
||||||
{"type": "url", "url": "/", "changefreq": "always", "priority": "1.0", "nesting": "0"},
|
|
||||||
{"type": "acme-post", "reference": "7", "urlPattern": "", "changefreq": "weekly", "priority": "0.5", "nesting": "1"}
|
|
||||||
],
|
|
||||||
"types": {
|
|
||||||
"acme-post": {
|
|
||||||
"7": {
|
|
||||||
"url": "/news/hello",
|
|
||||||
"mtime": "2026-03-04T10:00:00+00:00",
|
|
||||||
"alternates": [["pl", "/news/hello"], ["en", "/en/news/hello"]]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
58
classes/testdata/urlto.golden
vendored
58
classes/testdata/urlto.golden
vendored
@@ -1,58 +0,0 @@
|
|||||||
https://api.ex.pl/
|
|
||||||
https://api.ex.pl/
|
|
||||||
https://api.ex.pl/
|
|
||||||
https://api.ex.pl/blog
|
|
||||||
https://api.ex.pl/blog
|
|
||||||
https://api.ex.pl/blog
|
|
||||||
https://api.ex.pl/blog/za%C5%BC%C3%B3%C5%82%C4%87%20g%C4%99%C5%9Bl%C4%85
|
|
||||||
https://api.ex.pl/en/blog/%3Aslug
|
|
||||||
https://x.pl/q/
|
|
||||||
http://x.pl/
|
|
||||||
HTTP://X.pl:443/a
|
|
||||||
https://h:8080/a
|
|
||||||
https://h/a
|
|
||||||
http://h/
|
|
||||||
https://api.ex.pl/a?b=1&c=2
|
|
||||||
https://api.ex.pl/a?x%5B%5D=1&x%5B%5D=2&0=y
|
|
||||||
https://api.ex.pl/a?q=a&0=b%20c
|
|
||||||
https://api.ex.pl/a
|
|
||||||
https://api.ex.pl/a?b=&0=c
|
|
||||||
https://api.ex.pl/a?x&y
|
|
||||||
https://api.ex.pl/a?a=2
|
|
||||||
https://api.ex.pl/a?a%5Bb%5D=1
|
|
||||||
https://api.ex.pl/a#b%20c
|
|
||||||
https://api.ex.pl/a
|
|
||||||
#frag
|
|
||||||
cdn.x/a
|
|
||||||
mailto:a%40b.pl
|
|
||||||
tel:%2B48%20123
|
|
||||||
sms:%2B48123
|
|
||||||
https://api.ex.pl/a/c
|
|
||||||
https://api.ex.pl/a//b
|
|
||||||
https://api.ex.pl/a/%20b/%25zz
|
|
||||||
https://api.ex.pl/a%2Fb
|
|
||||||
https://api.ex.pl/%C5%9Bcie%C5%BCka/%C4%85%C4%99?x=%C5%BC#%C5%82
|
|
||||||
https://api.ex.pl/ftp%3A//x.pl/a%20b
|
|
||||||
ftp://x.pl/a
|
|
||||||
news:///comp.x
|
|
||||||
https://api.ex.pl/a%3Ab
|
|
||||||
https://api.ex.pl/a%3A1
|
|
||||||
https://api.ex.pl/user%40host
|
|
||||||
https://user:pass@h/x
|
|
||||||
https://api.ex.pl/%20%20/lead
|
|
||||||
https://api.ex.pl/trail
|
|
||||||
https://api.ex.pl/tab_here
|
|
||||||
https://api.ex.pl/new_line
|
|
||||||
https://api.ex.pl/
|
|
||||||
https://api.ex.pl/javascript%3Aalert%281%29
|
|
||||||
https://a&b<c>.pl/x
|
|
||||||
https://h/
|
|
||||||
https://api.ex.pl/en
|
|
||||||
https://api.ex.pl/en
|
|
||||||
https://api.ex.pl/a?x=%2B
|
|
||||||
https://api.ex.pl/a?k=v%20w
|
|
||||||
https://api.ex.pl/a%20b?x=1#y%20z
|
|
||||||
https://h/a?b=1#c
|
|
||||||
https://api.ex.pl/~tilde/_under.dot-dash
|
|
||||||
https://api.ex.pl/a%27b%22c
|
|
||||||
https://api.ex.pl/%3Cx%3E%26y
|
|
||||||
63
classes/testdata/urlto.json
vendored
63
classes/testdata/urlto.json
vendored
@@ -1,63 +0,0 @@
|
|||||||
{
|
|
||||||
"root": "https://api.ex.pl",
|
|
||||||
"urls": [
|
|
||||||
"/",
|
|
||||||
"",
|
|
||||||
null,
|
|
||||||
"/blog/",
|
|
||||||
"/blog",
|
|
||||||
"blog",
|
|
||||||
"/blog/zażółć gęślą",
|
|
||||||
"/en/blog/:slug",
|
|
||||||
"https://x.pl/q/",
|
|
||||||
"http://x.pl",
|
|
||||||
"HTTP://X.pl:443/a",
|
|
||||||
"https://h:8080/a",
|
|
||||||
"https://h:443/a",
|
|
||||||
"http://h:80/",
|
|
||||||
"/a?b=1&c=2",
|
|
||||||
"/a?x[]=1&x[]=2&y",
|
|
||||||
"/a?q=a%26b+c",
|
|
||||||
"/a?",
|
|
||||||
"/a?b=&c",
|
|
||||||
"/a?0=x&1=y",
|
|
||||||
"/a?a=1&a=2",
|
|
||||||
"/a?a[b]=1",
|
|
||||||
"/a#b c",
|
|
||||||
"/a#",
|
|
||||||
"#frag",
|
|
||||||
"//cdn.x/a",
|
|
||||||
"mailto:a@b.pl",
|
|
||||||
"tel:+48 123",
|
|
||||||
"sms:+48123",
|
|
||||||
"/../a/./b/../c",
|
|
||||||
"/a//b",
|
|
||||||
"/a/%20b/%zz",
|
|
||||||
"/a%2Fb",
|
|
||||||
"/ścieżka/ąę?x=ż#ł",
|
|
||||||
"ftp://x.pl/a b",
|
|
||||||
"ftp://x.pl/a",
|
|
||||||
"news:comp.x",
|
|
||||||
"/a:b",
|
|
||||||
"a:1",
|
|
||||||
"/user@host",
|
|
||||||
"https://user:pass@h/x",
|
|
||||||
" /lead",
|
|
||||||
"/trail ",
|
|
||||||
"/tab\there",
|
|
||||||
"/new\nline",
|
|
||||||
"/a/b/../../..",
|
|
||||||
"javascript:alert(1)",
|
|
||||||
"https://a&b<c>.pl/x",
|
|
||||||
"https://h/./",
|
|
||||||
"/en",
|
|
||||||
"/en/",
|
|
||||||
"/a?x=%2B",
|
|
||||||
"/a?k=v w",
|
|
||||||
"/a b?x=1#y z",
|
|
||||||
"https://h/a?b=1#c",
|
|
||||||
"/~tilde/_under.dot-dash",
|
|
||||||
"/a'b\"c",
|
|
||||||
"/<x>&y"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
package classes
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"regexp"
|
|
||||||
"slices"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/compass"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TiersConfigKey is the config key of the priority tier rules. The plugin's
|
|
||||||
// config/config.yaml ships the rules of the PHP getPriorityForUrl; a host
|
|
||||||
// replaces the whole list in its own config.
|
|
||||||
const TiersConfigKey = "golem15.sitemap.priority_tiers"
|
|
||||||
|
|
||||||
// TierConfig is one configured tier rule: Setting names the priority setting
|
|
||||||
// whose value applies (priority_homepage, priority_services, priority_blog,
|
|
||||||
// priority_categories or priority_legal), and exactly one of Exact (paths
|
|
||||||
// that match as they are) and Pattern (a regular expression, RE2 syntax)
|
|
||||||
// selects the URLs.
|
|
||||||
type TierConfig struct {
|
|
||||||
Setting string `koanf:"setting"`
|
|
||||||
Exact []string `koanf:"exact"`
|
|
||||||
Pattern string `koanf:"pattern"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// TierRule is a compiled tier rule.
|
|
||||||
type TierRule struct {
|
|
||||||
Setting string
|
|
||||||
Exact []string
|
|
||||||
Pattern *regexp.Regexp
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tiers is the ordered tier rule list; the first matching rule wins.
|
|
||||||
type Tiers []TierRule
|
|
||||||
|
|
||||||
// CompileTiers checks and compiles tier rules. Every error names the rule:
|
|
||||||
// an unknown setting, neither or both of exact and pattern, or a pattern
|
|
||||||
// that does not compile.
|
|
||||||
func CompileTiers(rules []TierConfig) (Tiers, error) {
|
|
||||||
out := make(Tiers, 0, len(rules))
|
|
||||||
for i, r := range rules {
|
|
||||||
if _, ok := models.PriorityDefaults[r.Setting]; !ok {
|
|
||||||
return nil, fmt.Errorf("%s[%d]: setting %q is not one of priority_homepage, priority_services, priority_blog, priority_categories, priority_legal", TiersConfigKey, i, r.Setting)
|
|
||||||
}
|
|
||||||
hasPattern := strings.TrimSpace(r.Pattern) != ""
|
|
||||||
if hasPattern == (len(r.Exact) > 0) {
|
|
||||||
return nil, fmt.Errorf("%s[%d]: set exactly one of exact and pattern", TiersConfigKey, i)
|
|
||||||
}
|
|
||||||
rule := TierRule{Setting: r.Setting, Exact: append([]string(nil), r.Exact...)}
|
|
||||||
if hasPattern {
|
|
||||||
re, err := regexp.Compile(r.Pattern)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("%s[%d]: pattern: %w", TiersConfigKey, i, err)
|
|
||||||
}
|
|
||||||
rule.Pattern = re
|
|
||||||
}
|
|
||||||
out = append(out, rule)
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// LoadTiers reads and compiles the rules at TiersConfigKey; an absent key
|
|
||||||
// is no rules.
|
|
||||||
func LoadTiers(cfg *compass.Config) (Tiers, error) {
|
|
||||||
if cfg == nil || !cfg.Has(TiersConfigKey) {
|
|
||||||
return Tiers{}, nil
|
|
||||||
}
|
|
||||||
var rules []TierConfig
|
|
||||||
if err := cfg.LoadSection(TiersConfigKey, &rules); err != nil {
|
|
||||||
return nil, fmt.Errorf("%s must be a list of {setting, exact} or {setting, pattern} rules: %w", TiersConfigKey, err)
|
|
||||||
}
|
|
||||||
return CompileTiers(rules)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Priority is PHP getPriorityForUrl with configured rules: when the
|
|
||||||
// settings enable tiers, the URL's path (parse_url's, "/" when it has none)
|
|
||||||
// right-trimmed of slashes is matched against the rules in order and the
|
|
||||||
// first match's setting value is returned. ok is false when tiers are off or
|
|
||||||
// no rule matches, so the item's own priority applies.
|
|
||||||
func (t Tiers) Priority(url string, s models.Settings) (string, bool) {
|
|
||||||
if !s.EnablePriorityTiers {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
path := URLPath(url)
|
|
||||||
if path == "" {
|
|
||||||
path = "/"
|
|
||||||
}
|
|
||||||
path = strings.TrimRight(path, "/")
|
|
||||||
for _, r := range t {
|
|
||||||
if r.Pattern != nil && r.Pattern.MatchString(path) || r.Pattern == nil && slices.Contains(r.Exact, path) {
|
|
||||||
return s.Priority(r.Setting), true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
package classes_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
sitemap "git.golem15.com/golem15/sm-sitemap-plugin"
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/compass"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestTiers pins the priority tiers (D-13): each default rule of the PHP
|
|
||||||
// getPriorityForUrl with paths from its list, trailing slashes, the first
|
|
||||||
// match winning, the settings' values, tiers turned off, a host list that
|
|
||||||
// replaces the defaults, and a bad rule failing the plugin's Boot.
|
|
||||||
func TestTiers(t *testing.T) {
|
|
||||||
tiers := pluginTiers(t)
|
|
||||||
if len(tiers) != 5 {
|
|
||||||
t.Fatalf("default rules = %d", len(tiers))
|
|
||||||
}
|
|
||||||
s := models.DefaultSettings()
|
|
||||||
for url, want := range map[string]string{
|
|
||||||
"https://h": "1.0",
|
|
||||||
"https://h/": "1.0",
|
|
||||||
"https://h/en": "1.0",
|
|
||||||
"https://h/en/": "1.0",
|
|
||||||
"https://h/uslugi/strony-www": "0.8",
|
|
||||||
"https://h/en/services/web": "0.8",
|
|
||||||
"https://h/realizacje/projekt/": "0.8",
|
|
||||||
"https://h/en/work/x": "0.8",
|
|
||||||
"https://h/blog/kategoria/wpis": "0.6",
|
|
||||||
"https://h/en/blog/category/post/": "0.6",
|
|
||||||
"https://h/blog": "0.4",
|
|
||||||
"https://h/blog/kategoria": "0.4",
|
|
||||||
"https://h/uslugi": "0.4",
|
|
||||||
"https://h/en/work": "0.4",
|
|
||||||
"https://h/polityka-prywatnosci": "0.2",
|
|
||||||
"https://h/en/terms/": "0.2",
|
|
||||||
"https://h/laboratorium-ai/zabawa-animacja": "0.2",
|
|
||||||
"https://h/en/ai-lab/blob-playground": "0.2",
|
|
||||||
"https://h/kontakt?x=1": "0.2",
|
|
||||||
} {
|
|
||||||
if got, ok := tiers.Priority(url, s); !ok || got != want {
|
|
||||||
t.Errorf("Priority(%s) = %q %v, want %s", url, got, ok, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, url := range []string{"https://h/other", "https://h/blog/a/b/c", "https://h/uslugi/a/b", "https://h/en/blogs/x", "https://h/kontakt/more"} {
|
|
||||||
if got, ok := tiers.Priority(url, s); ok {
|
|
||||||
t.Errorf("Priority(%s) = %q, want no rule", url, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
custom := s
|
|
||||||
custom.PriorityBlog = text("0.65")
|
|
||||||
if got, _ := tiers.Priority("https://h/blog/a/b", custom); got != "0.65" {
|
|
||||||
t.Fatalf("custom blog priority = %q", got)
|
|
||||||
}
|
|
||||||
off := s
|
|
||||||
off.EnablePriorityTiers = false
|
|
||||||
if _, ok := tiers.Priority("https://h/", off); ok {
|
|
||||||
t.Fatal("tiers apply while turned off")
|
|
||||||
}
|
|
||||||
|
|
||||||
// First match wins: an exact rule listed before a pattern that also matches.
|
|
||||||
ordered, err := classes.CompileTiers([]classes.TierConfig{
|
|
||||||
{Setting: models.PriorityLegal, Exact: []string{"/blog"}},
|
|
||||||
{Setting: models.PriorityCategories, Pattern: "^/blog$"},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if got, _ := ordered.Priority("https://h/blog/", s); got != "0.2" {
|
|
||||||
t.Fatalf("first match = %q", got)
|
|
||||||
}
|
|
||||||
if empty, err := classes.CompileTiers(nil); err != nil || len(empty) != 0 {
|
|
||||||
t.Fatalf("no rules = %v %v", empty, err)
|
|
||||||
}
|
|
||||||
if none, err := classes.LoadTiers(nil); err != nil || len(none) != 0 {
|
|
||||||
t.Fatalf("LoadTiers(nil) = %v %v", none, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Every refused rule names its index; a bad RE2 pattern too.
|
|
||||||
for name, rule := range map[string]classes.TierConfig{
|
|
||||||
"unknown setting": {Setting: "priority_other", Exact: []string{""}},
|
|
||||||
"neither": {Setting: models.PriorityHomepage},
|
|
||||||
"both": {Setting: models.PriorityHomepage, Exact: []string{""}, Pattern: "^/$"},
|
|
||||||
"lookahead": {Setting: models.PriorityBlog, Pattern: "^/(?=blog)"},
|
|
||||||
"unbalanced": {Setting: models.PriorityBlog, Pattern: "^/(blog"},
|
|
||||||
} {
|
|
||||||
_, err := classes.CompileTiers([]classes.TierConfig{{Setting: models.PriorityHomepage, Exact: []string{""}}, rule})
|
|
||||||
if err == nil || !strings.Contains(err.Error(), classes.TiersConfigKey+"[1]") {
|
|
||||||
t.Errorf("%s: err = %v", name, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A bad host rule fails the plugin's Boot.
|
|
||||||
dir := t.TempDir()
|
|
||||||
if err := os.WriteFile(filepath.Join(dir, "golem15.yaml"), []byte("sitemap:\n priority_tiers:\n - setting: priority_blog\n pattern: '^/(blog'\n"), 0o644); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{}})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
p := &sitemap.Plugin{}
|
|
||||||
if err := cfg.MergePlugin("golem15.sitemap", p.ConfigFS()); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := p.Boot(backpack.New(cfg)); err == nil || !strings.Contains(err.Error(), "priority_tiers[0]") {
|
|
||||||
t.Fatalf("Boot with a bad pattern = %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
54
classes/types.go
Normal file
54
classes/types.go
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReservedSlugs are file name parts no content type may use: the image
|
||||||
|
// and News sitemaps own them.
|
||||||
|
var ReservedSlugs = map[string]bool{"images": true, "news": true}
|
||||||
|
|
||||||
|
// TypeConfig is a content type's effective sitemap setting: its key and
|
||||||
|
// label, whether its records are listed, its group slug and its HTML
|
||||||
|
// sitemap headings (nil when none was saved).
|
||||||
|
type TypeConfig struct {
|
||||||
|
Key string
|
||||||
|
Label string
|
||||||
|
Include bool
|
||||||
|
Slug string
|
||||||
|
Titles map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadTypeSettings reads the saved content type settings by type key.
|
||||||
|
func LoadTypeSettings(db *gorm.DB) (map[string]models.TypeSetting, error) {
|
||||||
|
var rows []models.TypeSetting
|
||||||
|
if err := db.Find(&rows).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := make(map[string]models.TypeSetting, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
out[r.TypeKey] = r
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EffectiveType is the setting of typ: the saved row, else listed under
|
||||||
|
// DefaultSlug. A saved slug that is not a ValidSlug falls back to the
|
||||||
|
// default.
|
||||||
|
func EffectiveType(typ pact.MenuItemType, rows map[string]models.TypeSetting) TypeConfig {
|
||||||
|
cfg := TypeConfig{Key: typ.Key, Label: typ.Label, Include: true, Slug: DefaultSlug(typ.Key)}
|
||||||
|
row, ok := rows[typ.Key]
|
||||||
|
if !ok {
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
cfg.Include = row.Include
|
||||||
|
if ValidSlug(row.Slug) {
|
||||||
|
cfg.Slug = row.Slug
|
||||||
|
}
|
||||||
|
if titles := row.Titles.Get(); len(titles) > 0 {
|
||||||
|
cfg.Titles = titles
|
||||||
|
}
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
48
classes/types_test.go
Normal file
48
classes/types_test.go
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestDefaultSlug pins the default group slug: the last segment of the
|
||||||
|
// key, lower-cased, letters and digits only, in plural form.
|
||||||
|
func TestDefaultSlug(t *testing.T) {
|
||||||
|
for key, want := range map[string]string{
|
||||||
|
"journal-post": "posts", "journal-category": "categories", "seo-page": "pages", "journal-tag": "tags",
|
||||||
|
"journal-author": "authors", "acme.news": "news", "acme_day": "days", "shop-boxes": "boxes", "Acme-Story": "stories",
|
||||||
|
"x-y": "ys", "a-key": "keys", "": "pages", "acme-": "pages", "acme-żółw": "ws",
|
||||||
|
} {
|
||||||
|
if got := DefaultSlug(key); got != want {
|
||||||
|
t.Errorf("DefaultSlug(%q) = %q, want %q", key, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestEffectiveType pins a content type's setting: listed under its
|
||||||
|
// default slug without a saved row; the saved include, slug and headings
|
||||||
|
// otherwise, with an invalid saved slug falling back to the default.
|
||||||
|
func TestEffectiveType(t *testing.T) {
|
||||||
|
typ := pact.MenuItemType{Key: "journal-post", Label: "Posts"}
|
||||||
|
if got := EffectiveType(typ, nil); got.Key != "journal-post" || got.Label != "Posts" || !got.Include || got.Slug != "posts" || got.Titles != nil {
|
||||||
|
t.Fatalf("without a row = %+v", got)
|
||||||
|
}
|
||||||
|
rows := map[string]models.TypeSetting{"journal-post": {TypeKey: "journal-post", Include: false, Slug: "articles", Titles: lagoon.Jsonable[map[string]string]{Data: map[string]string{"pl": "Artykuły"}, Valid: true}}}
|
||||||
|
if got := EffectiveType(typ, rows); got.Include || got.Slug != "articles" || got.Titles["pl"] != "Artykuły" {
|
||||||
|
t.Fatalf("with a row = %+v", got)
|
||||||
|
}
|
||||||
|
rows["journal-post"] = models.TypeSetting{TypeKey: "journal-post", Include: true, Slug: "Bad Slug"}
|
||||||
|
if got := EffectiveType(typ, rows); !got.Include || got.Slug != "posts" || got.Titles != nil {
|
||||||
|
t.Fatalf("with an invalid slug = %+v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestReservedSlugs pins the slugs the image and News files own.
|
||||||
|
func TestReservedSlugs(t *testing.T) {
|
||||||
|
if !ReservedSlugs["images"] || !ReservedSlugs["news"] || len(ReservedSlugs) != 2 || ReservedSlugs["pages"] {
|
||||||
|
t.Fatalf("ReservedSlugs = %v", ReservedSlugs)
|
||||||
|
}
|
||||||
|
}
|
||||||
145
classes/typesettings.go
Normal file
145
classes/typesettings.go
Normal file
@@ -0,0 +1,145 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/clause"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The phrase keys of the content type refusals (UI-SPEC C26).
|
||||||
|
const (
|
||||||
|
errSlug = "golem15.sitemap::lang.errors.slug"
|
||||||
|
errSlugTaken = "golem15.sitemap::lang.errors.slug_taken"
|
||||||
|
)
|
||||||
|
|
||||||
|
var typeFieldUnsafe = regexp.MustCompile(`[^a-z0-9_]`)
|
||||||
|
|
||||||
|
// TypeFieldBase is the prefix of a content type's settings fields:
|
||||||
|
// type_<key>_, where every character of the key outside [a-z0-9_] becomes
|
||||||
|
// "_".
|
||||||
|
func TypeFieldBase(key string) string {
|
||||||
|
return "type_" + typeFieldUnsafe.ReplaceAllString(strings.ToLower(key), "_") + "_"
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveTypeSettings stores submitted content type settings: values holds
|
||||||
|
// TypeFieldBase(key)+"include" (a switch), +"slug" and +"title" (a locale
|
||||||
|
// map) per type; a type or value not sent keeps what is stored. A slug
|
||||||
|
// outside [a-z0-9-] is refused with errors.slug, one that another type (or
|
||||||
|
// the image and News sitemaps) uses with errors.slug_taken; an empty slug
|
||||||
|
// is the type's default. Refusals are by field name; nothing is written
|
||||||
|
// while there are any.
|
||||||
|
func SaveTypeSettings(db *gorm.DB, types []pact.MenuItemType, values map[string]any) (map[string][]string, error) {
|
||||||
|
rows, err := LoadTypeSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
refusals := map[string][]string{}
|
||||||
|
next := make([]models.TypeSetting, 0, len(types))
|
||||||
|
slugOwner := map[string]string{}
|
||||||
|
for _, typ := range types {
|
||||||
|
base := TypeFieldBase(typ.Key)
|
||||||
|
cfg := EffectiveType(typ, rows)
|
||||||
|
row, ok := rows[typ.Key]
|
||||||
|
if !ok {
|
||||||
|
row = models.TypeSetting{TypeKey: typ.Key, Include: true}
|
||||||
|
}
|
||||||
|
if raw, sent := values[base+"include"]; sent {
|
||||||
|
row.Include = truthy(raw)
|
||||||
|
}
|
||||||
|
slug := cfg.Slug
|
||||||
|
if raw, sent := values[base+"slug"]; sent {
|
||||||
|
slug = strings.TrimSpace(stringOf(raw))
|
||||||
|
if slug == "" {
|
||||||
|
slug = DefaultSlug(typ.Key)
|
||||||
|
} else if !ValidSlug(slug) {
|
||||||
|
refusals[base+"slug"] = append(refusals[base+"slug"], errSlug)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ReservedSlugs[slug] {
|
||||||
|
refusals[base+"slug"] = append(refusals[base+"slug"], errSlugTaken)
|
||||||
|
} else if owner, taken := slugOwner[slug]; taken && owner != typ.Key {
|
||||||
|
refusals[base+"slug"] = append(refusals[base+"slug"], errSlugTaken)
|
||||||
|
}
|
||||||
|
slugOwner[slug] = typ.Key
|
||||||
|
if slug == DefaultSlug(typ.Key) {
|
||||||
|
row.Slug = ""
|
||||||
|
} else {
|
||||||
|
row.Slug = slug
|
||||||
|
}
|
||||||
|
if raw, sent := values[base+"title"]; sent {
|
||||||
|
row.Titles = lagoon.Jsonable[map[string]string]{Data: titlesOf(raw), Valid: true}
|
||||||
|
}
|
||||||
|
next = append(next, row)
|
||||||
|
}
|
||||||
|
if len(refusals) > 0 {
|
||||||
|
return refusals, nil
|
||||||
|
}
|
||||||
|
now := time.Now().UTC()
|
||||||
|
for _, row := range next {
|
||||||
|
row.UpdatedAt = now
|
||||||
|
if !row.Titles.Valid {
|
||||||
|
row.Titles = lagoon.Jsonable[map[string]string]{Data: map[string]string{}, Valid: true}
|
||||||
|
}
|
||||||
|
if err := db.Clauses(clause.OnConflict{
|
||||||
|
Columns: []clause.Column{{Name: "type_key"}},
|
||||||
|
DoUpdates: clause.AssignmentColumns([]string{"include", "slug", "titles", "updated_at"}),
|
||||||
|
}).Create(&row).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// titlesOf reads a submitted translatable value (a map of locale to text);
|
||||||
|
// blank texts are dropped.
|
||||||
|
func titlesOf(v any) map[string]string {
|
||||||
|
out := map[string]string{}
|
||||||
|
switch m := v.(type) {
|
||||||
|
case map[string]string:
|
||||||
|
for k, s := range m {
|
||||||
|
if strings.TrimSpace(s) != "" {
|
||||||
|
out[k] = strings.TrimSpace(s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case map[string]any:
|
||||||
|
for k, s := range m {
|
||||||
|
if text, ok := s.(string); ok && strings.TrimSpace(text) != "" {
|
||||||
|
out[k] = strings.TrimSpace(text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// truthy reads a submitted switch value.
|
||||||
|
func truthy(v any) bool {
|
||||||
|
switch b := v.(type) {
|
||||||
|
case bool:
|
||||||
|
return b
|
||||||
|
case string:
|
||||||
|
return b == "1" || strings.EqualFold(b, "true") || strings.EqualFold(b, "on")
|
||||||
|
case float64:
|
||||||
|
return b != 0
|
||||||
|
case fmt.Stringer:
|
||||||
|
return b.String() == "1"
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// stringOf reads a submitted text value.
|
||||||
|
func stringOf(v any) string {
|
||||||
|
switch s := v.(type) {
|
||||||
|
case string:
|
||||||
|
return s
|
||||||
|
case nil:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return fmt.Sprint(v)
|
||||||
|
}
|
||||||
566
classes/urlto.go
566
classes/urlto.go
@@ -1,566 +0,0 @@
|
|||||||
package classes
|
|
||||||
|
|
||||||
import (
|
|
||||||
"regexp"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// This file ports the parts of WinterCMS's URL generator the PHP sitemap
|
|
||||||
// called, so the Go sitemap writes the same bytes: Laravel's Url::to plus
|
|
||||||
// Winter's UrlGenerator::buildUrl, PHP's parse_url, rawurlencode,
|
|
||||||
// rawurldecode and urldecode, and FILTER_VALIDATE_URL. It is deliberately
|
|
||||||
// hand written: net/url escapes differently. The golden table
|
|
||||||
// testdata/urlto.golden, generated from the vendored Winter router, pins
|
|
||||||
// it.
|
|
||||||
|
|
||||||
// validURLPrefix is Laravel UrlGenerator::isValidUrl's fast path.
|
|
||||||
var validURLPrefix = regexp.MustCompile(`^(#|//|https?://|(mailto|tel|sms):)`)
|
|
||||||
|
|
||||||
// URLTo is Winter's Url::to(path) for a request whose root URL is root
|
|
||||||
// (scheme and host, plus a base path if any, without a trailing slash). A
|
|
||||||
// valid URL is kept; anything else becomes root plus "/" plus the path
|
|
||||||
// trimmed of slashes, the query string appended as it is. The result then
|
|
||||||
// goes through BuildURL, which re-encodes every path segment, so "/" is the
|
|
||||||
// root with its slash, "/blog/" loses its trailing slash and ":" becomes
|
|
||||||
// "%3A".
|
|
||||||
func URLTo(root, path string) string {
|
|
||||||
if isValidURL(path) {
|
|
||||||
return BuildURL(path)
|
|
||||||
}
|
|
||||||
p, query := path, ""
|
|
||||||
if i := strings.IndexByte(path, '?'); i >= 0 {
|
|
||||||
p, query = path[:i], path[i:]
|
|
||||||
}
|
|
||||||
inner := strings.Trim(p+"/", "/")
|
|
||||||
return BuildURL(strings.Trim(root+"/"+inner, "/") + query)
|
|
||||||
}
|
|
||||||
|
|
||||||
// isValidURL is Laravel UrlGenerator::isValidUrl.
|
|
||||||
func isValidURL(path string) bool {
|
|
||||||
if validURLPrefix.MatchString(path) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return filterValidateURL(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
// filterURLChars is the character set PHP's FILTER_VALIDATE_URL accepts;
|
|
||||||
// a value with any other byte fails.
|
|
||||||
const filterURLChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$-_.+!*'(),{}|\\^~[]`<>#%\";/?:@&="
|
|
||||||
|
|
||||||
// filterValidateURL approximates PHP filter_var(FILTER_VALIDATE_URL): only
|
|
||||||
// URL characters, a scheme, a host unless the scheme is mailto, news or
|
|
||||||
// file, and a valid host name for http and https.
|
|
||||||
func filterValidateURL(s string) bool {
|
|
||||||
if s == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for i := 0; i < len(s); i++ {
|
|
||||||
if !strings.ContainsRune(filterURLChars, rune(s[i])) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
u := parseURL(s)
|
|
||||||
if !u.has(partScheme) || u.scheme == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
scheme := strings.ToLower(u.scheme)
|
|
||||||
if !u.has(partHost) || u.host == "" {
|
|
||||||
return scheme == "mailto" || scheme == "news" || scheme == "file"
|
|
||||||
}
|
|
||||||
if scheme == "http" || scheme == "https" {
|
|
||||||
return validHostName(u.host)
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// validHostName reports whether host is dot-separated labels of letters,
|
|
||||||
// digits and inner hyphens.
|
|
||||||
func validHostName(host string) bool {
|
|
||||||
host = strings.TrimSuffix(host, ".")
|
|
||||||
if host == "" || len(host) > 253 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for _, label := range strings.Split(host, ".") {
|
|
||||||
if label == "" || len(label) > 63 || label[0] == '-' || label[len(label)-1] == '-' {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
for i := 0; i < len(label); i++ {
|
|
||||||
c := label[i]
|
|
||||||
if !(isAlnum(c) || c == '-') {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// The parts a parsed URL may hold, as PHP parse_url's array keys.
|
|
||||||
const (
|
|
||||||
partScheme = 1 << iota
|
|
||||||
partHost
|
|
||||||
partUser
|
|
||||||
partPass
|
|
||||||
partPort
|
|
||||||
partPath
|
|
||||||
partQuery
|
|
||||||
partFragment
|
|
||||||
)
|
|
||||||
|
|
||||||
// phpURL is the array PHP parse_url returns; set records which keys exist.
|
|
||||||
type phpURL struct {
|
|
||||||
set int
|
|
||||||
scheme, host, user, pass, port, path, query, frag string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u phpURL) has(part int) bool { return u.set&part != 0 }
|
|
||||||
|
|
||||||
// parseURL ports PHP parse_url for the URL shapes a sitemap meets: an
|
|
||||||
// optional scheme, an authority after "//", a path, a query and a fragment.
|
|
||||||
// Control characters in a part are replaced by "_", as PHP does.
|
|
||||||
func parseURL(s string) phpURL {
|
|
||||||
var u phpURL
|
|
||||||
rest := s
|
|
||||||
if i := strings.IndexByte(rest, ':'); i > 0 && validScheme(rest[:i]) {
|
|
||||||
after := rest[i+1:]
|
|
||||||
if !strings.HasPrefix(after, "//") && portOnly(after) {
|
|
||||||
// "host:port/path" without a scheme.
|
|
||||||
} else {
|
|
||||||
u.scheme, u.set = rest[:i], u.set|partScheme
|
|
||||||
rest = after
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if strings.HasPrefix(rest, "//") {
|
|
||||||
rest = rest[2:]
|
|
||||||
end := strings.IndexAny(rest, "/?#")
|
|
||||||
authority := rest
|
|
||||||
if end >= 0 {
|
|
||||||
authority, rest = rest[:end], rest[end:]
|
|
||||||
} else {
|
|
||||||
rest = ""
|
|
||||||
}
|
|
||||||
u.parseAuthority(authority)
|
|
||||||
}
|
|
||||||
if i := strings.IndexByte(rest, '#'); i >= 0 {
|
|
||||||
u.frag, u.set = rest[i+1:], u.set|partFragment
|
|
||||||
rest = rest[:i]
|
|
||||||
}
|
|
||||||
if i := strings.IndexByte(rest, '?'); i >= 0 {
|
|
||||||
u.query, u.set = rest[i+1:], u.set|partQuery
|
|
||||||
rest = rest[:i]
|
|
||||||
}
|
|
||||||
if rest != "" {
|
|
||||||
u.path, u.set = rest, u.set|partPath
|
|
||||||
}
|
|
||||||
u.scheme = replaceControl(u.scheme)
|
|
||||||
u.host = replaceControl(u.host)
|
|
||||||
u.user = replaceControl(u.user)
|
|
||||||
u.pass = replaceControl(u.pass)
|
|
||||||
u.path = replaceControl(u.path)
|
|
||||||
u.query = replaceControl(u.query)
|
|
||||||
u.frag = replaceControl(u.frag)
|
|
||||||
return u
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *phpURL) parseAuthority(a string) {
|
|
||||||
if i := strings.LastIndexByte(a, '@'); i >= 0 {
|
|
||||||
userinfo := a[:i]
|
|
||||||
a = a[i+1:]
|
|
||||||
if j := strings.IndexByte(userinfo, ':'); j >= 0 {
|
|
||||||
u.user, u.pass = userinfo[:j], userinfo[j+1:]
|
|
||||||
u.set |= partUser | partPass
|
|
||||||
} else {
|
|
||||||
u.user = userinfo
|
|
||||||
u.set |= partUser
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if i := strings.LastIndexByte(a, ':'); i >= 0 && !strings.HasSuffix(a, "]") {
|
|
||||||
port := a[i+1:]
|
|
||||||
if port != "" && allDigits(port) {
|
|
||||||
u.port, u.set = port, u.set|partPort
|
|
||||||
}
|
|
||||||
a = a[:i]
|
|
||||||
}
|
|
||||||
if a != "" {
|
|
||||||
u.host, u.set = a, u.set|partHost
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func validScheme(s string) bool {
|
|
||||||
for i := 0; i < len(s); i++ {
|
|
||||||
c := s[i]
|
|
||||||
if !(isAlnum(c) || c == '+' || c == '-' || c == '.') {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return s != ""
|
|
||||||
}
|
|
||||||
|
|
||||||
// portOnly reports whether s is a port number up to the first "/", the
|
|
||||||
// case PHP parse_url reads as host:port rather than scheme:path.
|
|
||||||
func portOnly(s string) bool {
|
|
||||||
end := strings.IndexByte(s, '/')
|
|
||||||
if end < 0 {
|
|
||||||
end = len(s)
|
|
||||||
}
|
|
||||||
return end > 0 && end <= 5 && allDigits(s[:end])
|
|
||||||
}
|
|
||||||
|
|
||||||
func allDigits(s string) bool {
|
|
||||||
for i := 0; i < len(s); i++ {
|
|
||||||
if s[i] < '0' || s[i] > '9' {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return s != ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func isAlnum(c byte) bool {
|
|
||||||
return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9'
|
|
||||||
}
|
|
||||||
|
|
||||||
func replaceControl(s string) string {
|
|
||||||
if strings.IndexFunc(s, func(r rune) bool { return r < 0x20 || r == 0x7f }) < 0 {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
b := []byte(s)
|
|
||||||
for i, c := range b {
|
|
||||||
if c < 0x20 || c == 0x7f {
|
|
||||||
b[i] = '_'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return string(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
// phpTrim is PHP trim() with its default character list.
|
|
||||||
func phpTrim(s string) string {
|
|
||||||
return strings.Trim(s, " \t\n\r\x00\x0b")
|
|
||||||
}
|
|
||||||
|
|
||||||
// singleColonSchemes are written "scheme:" instead of "scheme://".
|
|
||||||
var singleColonSchemes = map[string]bool{"mailto": true, "tel": true, "sms": true}
|
|
||||||
|
|
||||||
// defaultPorts are Winter UrlGenerator::isDefaultPort's known ports.
|
|
||||||
var defaultPorts = map[string]int{
|
|
||||||
"ftp": 21, "ssh": 22, "sftp": 22, "telnet": 23, "smtp": 25, "dns": 53,
|
|
||||||
"gopher": 70, "http": 80, "pop3": 110, "imap": 143, "ldap": 389,
|
|
||||||
"https": 443, "smtps": 465, "ldaps": 636, "ftps": 990, "imaps": 993,
|
|
||||||
"pop3s": 995,
|
|
||||||
}
|
|
||||||
|
|
||||||
// BuildURL is Winter UrlGenerator::buildUrl($url) with no replacements: the
|
|
||||||
// query is URL-decoded, the URL parsed, every path segment re-encoded with
|
|
||||||
// rawurlencode(rawurldecode()) after "." and ".." are resolved, the query
|
|
||||||
// rebuilt with buildStr and the fragment re-encoded.
|
|
||||||
func BuildURL(raw string) string {
|
|
||||||
return buildParts(parseURL(decodeQueryParams(raw)))
|
|
||||||
}
|
|
||||||
|
|
||||||
// replacePath is buildUrl($url, ['path' => path]).
|
|
||||||
func replacePath(raw, path string) string {
|
|
||||||
u := parseURL(decodeQueryParams(raw))
|
|
||||||
u.path, u.set = path, u.set|partPath
|
|
||||||
return buildParts(u)
|
|
||||||
}
|
|
||||||
|
|
||||||
// decodeQueryParams URL-decodes everything after the first "?".
|
|
||||||
func decodeQueryParams(s string) string {
|
|
||||||
if i := strings.IndexByte(s, '?'); i >= 0 {
|
|
||||||
return s[:i] + "?" + urldecode(s[i+1:])
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
func buildParts(u phpURL) string {
|
|
||||||
u.scheme, u.host, u.user, u.pass = phpTrim(u.scheme), phpTrim(u.host), phpTrim(u.user), phpTrim(u.pass)
|
|
||||||
u.path, u.query, u.frag = phpTrim(u.path), phpTrim(u.query), phpTrim(u.frag)
|
|
||||||
port := 0
|
|
||||||
if u.has(partPort) {
|
|
||||||
if n, err := strconv.Atoi(phpTrim(u.port)); err == nil && n >= 1 && n <= 65535 {
|
|
||||||
port = n
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var b strings.Builder
|
|
||||||
hasScheme := u.has(partScheme) && u.scheme != ""
|
|
||||||
if hasScheme {
|
|
||||||
b.WriteString(u.scheme)
|
|
||||||
if singleColonSchemes[u.scheme] {
|
|
||||||
b.WriteString(":")
|
|
||||||
} else {
|
|
||||||
b.WriteString("://")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if u.has(partUser) && u.user != "" {
|
|
||||||
b.WriteString(u.user)
|
|
||||||
if u.has(partPass) && u.pass != "" {
|
|
||||||
b.WriteString(":" + u.pass)
|
|
||||||
}
|
|
||||||
b.WriteString("@")
|
|
||||||
}
|
|
||||||
if u.has(partHost) && u.host != "" {
|
|
||||||
b.WriteString(u.host)
|
|
||||||
}
|
|
||||||
if port != 0 {
|
|
||||||
if def, ok := defaultPorts[strings.ToLower(u.scheme)]; !ok || def != port {
|
|
||||||
b.WriteString(":" + strconv.Itoa(port))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
path := ""
|
|
||||||
if u.has(partPath) && u.path != "" {
|
|
||||||
var kept []string
|
|
||||||
for _, seg := range strings.Split(u.path, "/") {
|
|
||||||
switch {
|
|
||||||
case seg == ".":
|
|
||||||
case seg == ".." && len(kept) > 0:
|
|
||||||
kept = kept[:len(kept)-1]
|
|
||||||
default:
|
|
||||||
kept = append(kept, seg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for i, seg := range kept {
|
|
||||||
kept[i] = rawurlencode(rawurldecode(seg))
|
|
||||||
}
|
|
||||||
path = strings.Join(kept, "/")
|
|
||||||
}
|
|
||||||
if hasScheme && !singleColonSchemes[u.scheme] {
|
|
||||||
if !strings.HasPrefix(path, "/") {
|
|
||||||
b.WriteString("/")
|
|
||||||
}
|
|
||||||
b.WriteString(path)
|
|
||||||
} else {
|
|
||||||
b.WriteString(path)
|
|
||||||
}
|
|
||||||
if u.has(partQuery) && u.query != "" {
|
|
||||||
b.WriteString("?" + buildStr(parseQueryPairs(u.query), ""))
|
|
||||||
}
|
|
||||||
if u.has(partFragment) && u.frag != "" {
|
|
||||||
b.WriteString("#" + rawurlencode(rawurldecode(u.frag)))
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// phpKey is a PHP array key: an int or a string.
|
|
||||||
type phpKey struct {
|
|
||||||
isInt bool
|
|
||||||
i int64
|
|
||||||
s string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (k phpKey) String() string {
|
|
||||||
if k.isInt {
|
|
||||||
return strconv.FormatInt(k.i, 10)
|
|
||||||
}
|
|
||||||
return k.s
|
|
||||||
}
|
|
||||||
|
|
||||||
// keyOf is PHP's array key cast of a string: a canonical decimal integer
|
|
||||||
// becomes an int key.
|
|
||||||
func keyOf(s string) phpKey {
|
|
||||||
if n, err := strconv.ParseInt(s, 10, 64); err == nil && strconv.FormatInt(n, 10) == s {
|
|
||||||
return phpKey{isInt: true, i: n}
|
|
||||||
}
|
|
||||||
return phpKey{s: s}
|
|
||||||
}
|
|
||||||
|
|
||||||
// phpArray is an ordered PHP array of strings, nested arrays or nulls.
|
|
||||||
type phpArray struct {
|
|
||||||
keys []phpKey
|
|
||||||
vals []any
|
|
||||||
next int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *phpArray) index(k phpKey) int {
|
|
||||||
for i, have := range a.keys {
|
|
||||||
if have == k {
|
|
||||||
return i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return -1
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *phpArray) set(k phpKey, v any) {
|
|
||||||
if i := a.index(k); i >= 0 {
|
|
||||||
a.vals[i] = v
|
|
||||||
return
|
|
||||||
}
|
|
||||||
a.keys = append(a.keys, k)
|
|
||||||
a.vals = append(a.vals, v)
|
|
||||||
if k.isInt && k.i >= a.next {
|
|
||||||
a.next = k.i + 1
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *phpArray) push(v any) {
|
|
||||||
a.set(phpKey{isInt: true, i: a.next}, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseQueryPairs is buildUrl's split of a string query into
|
|
||||||
// $queryParams.
|
|
||||||
func parseQueryPairs(query string) *phpArray {
|
|
||||||
params := &phpArray{}
|
|
||||||
for _, pair := range strings.Split(query, "&") {
|
|
||||||
key, value := pair, pair
|
|
||||||
if i := strings.IndexByte(pair, '='); i >= 0 {
|
|
||||||
key, value = pair[:i], pair[i+1:]
|
|
||||||
}
|
|
||||||
if !strings.Contains(pair, "=") {
|
|
||||||
params.push(key)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if strings.Contains(urldecode(pair), "[") {
|
|
||||||
k := keyOf(key)
|
|
||||||
var inner *phpArray
|
|
||||||
if i := params.index(k); i >= 0 {
|
|
||||||
inner, _ = params.vals[i].(*phpArray)
|
|
||||||
}
|
|
||||||
if inner == nil {
|
|
||||||
inner = &phpArray{}
|
|
||||||
}
|
|
||||||
inner.push(value)
|
|
||||||
params.set(k, inner)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
params.set(keyOf(key), value)
|
|
||||||
}
|
|
||||||
return params
|
|
||||||
}
|
|
||||||
|
|
||||||
// buildStr is Winter UrlGenerator::buildStr.
|
|
||||||
func buildStr(query *phpArray, prefix string) string {
|
|
||||||
var out []string
|
|
||||||
for i, k := range query.keys {
|
|
||||||
v := query.vals[i]
|
|
||||||
var key string
|
|
||||||
if k.isInt && k.i == int64(i) {
|
|
||||||
if prefix != "" {
|
|
||||||
if strings.HasSuffix(prefix, "]") {
|
|
||||||
key = prefix
|
|
||||||
} else {
|
|
||||||
key = prefix + "[]"
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
key, _ = v.(string)
|
|
||||||
v = nil
|
|
||||||
}
|
|
||||||
} else if prefix != "" {
|
|
||||||
key = prefix + "[" + k.String() + "]"
|
|
||||||
} else {
|
|
||||||
key = k.String()
|
|
||||||
}
|
|
||||||
if nested, ok := v.(*phpArray); ok {
|
|
||||||
out = append(out, buildStr(nested, key))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
part := rawurlencode(rawurldecode(key))
|
|
||||||
if s, ok := v.(string); ok {
|
|
||||||
part += "=" + rawurlencode(rawurldecode(s))
|
|
||||||
}
|
|
||||||
out = append(out, part)
|
|
||||||
}
|
|
||||||
return strings.Join(out, "&")
|
|
||||||
}
|
|
||||||
|
|
||||||
// rawurlencode is PHP rawurlencode: every byte except A-Z a-z 0-9 - _ . ~
|
|
||||||
// becomes %XX with upper-case hex.
|
|
||||||
func rawurlencode(s string) string {
|
|
||||||
const hex = "0123456789ABCDEF"
|
|
||||||
var b strings.Builder
|
|
||||||
for i := 0; i < len(s); i++ {
|
|
||||||
c := s[i]
|
|
||||||
if isAlnum(c) || c == '-' || c == '_' || c == '.' || c == '~' {
|
|
||||||
b.WriteByte(c)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
b.WriteByte('%')
|
|
||||||
b.WriteByte(hex[c>>4])
|
|
||||||
b.WriteByte(hex[c&15])
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// rawurldecode is PHP rawurldecode: %XX becomes its byte, anything else,
|
|
||||||
// including a malformed escape, stays.
|
|
||||||
func rawurldecode(s string) string { return percentDecode(s, false) }
|
|
||||||
|
|
||||||
// urldecode is PHP urldecode: rawurldecode that also turns "+" into a
|
|
||||||
// space.
|
|
||||||
func urldecode(s string) string { return percentDecode(s, true) }
|
|
||||||
|
|
||||||
func percentDecode(s string, plus bool) string {
|
|
||||||
if !strings.ContainsAny(s, "%+") {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
var b strings.Builder
|
|
||||||
for i := 0; i < len(s); i++ {
|
|
||||||
c := s[i]
|
|
||||||
if c == '+' && plus {
|
|
||||||
b.WriteByte(' ')
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if c == '%' && i+2 < len(s) && isHex(s[i+1]) && isHex(s[i+2]) {
|
|
||||||
b.WriteByte(unhex(s[i+1])<<4 | unhex(s[i+2]))
|
|
||||||
i += 2
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
b.WriteByte(c)
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func isHex(c byte) bool {
|
|
||||||
return '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F'
|
|
||||||
}
|
|
||||||
|
|
||||||
func unhex(c byte) byte {
|
|
||||||
switch {
|
|
||||||
case '0' <= c && c <= '9':
|
|
||||||
return c - '0'
|
|
||||||
case 'a' <= c && c <= 'f':
|
|
||||||
return c - 'a' + 10
|
|
||||||
default:
|
|
||||||
return c - 'A' + 10
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// URLPath is the path PHP parse_url($url, PHP_URL_PATH) returns, "" when
|
|
||||||
// the URL has none.
|
|
||||||
func URLPath(raw string) string {
|
|
||||||
u := parseURL(raw)
|
|
||||||
if !u.has(partPath) {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return u.path
|
|
||||||
}
|
|
||||||
|
|
||||||
// schemePrefix matches a URL that starts with a scheme and its colon.
|
|
||||||
var schemePrefix = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.\-]*:`)
|
|
||||||
|
|
||||||
// AllowedItemURL reports whether a url item's address may be stored: empty,
|
|
||||||
// a path (relative or starting with a single "/"), or an absolute http or
|
|
||||||
// https URL. Any other scheme (javascript:, data:, mailto: and the like), a
|
|
||||||
// protocol-relative "//host" or "/\host", a bare fragment, surrounding
|
|
||||||
// whitespace and control characters are refused. Url::to keeps any URL
|
|
||||||
// FILTER_VALIDATE_URL accepts, so without this a javascript: URL reached
|
|
||||||
// <loc>, which sitemap.xsl renders as a link.
|
|
||||||
func AllowedItemURL(u string) bool {
|
|
||||||
if u == "" {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if strings.TrimSpace(u) != u || strings.ContainsFunc(u, func(r rune) bool { return r < 0x20 || r == 0x7f }) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if httpURL(u) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if schemePrefix.MatchString(u) || u[0] == '#' || u[0] == '\\' {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return !strings.HasPrefix(u, "//") && !strings.HasPrefix(u, `/\`)
|
|
||||||
}
|
|
||||||
|
|
||||||
// httpURL reports whether u starts with http:// or https://
|
|
||||||
// (case-insensitive).
|
|
||||||
func httpURL(u string) bool {
|
|
||||||
lower := strings.ToLower(u)
|
|
||||||
return strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://")
|
|
||||||
}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
package classes_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestURLTo runs every case of testdata/urlto.json through URLTo and
|
|
||||||
// compares it with the line PHP's Url::to wrote to urlto.golden (SC-3), then
|
|
||||||
// pins the helpers built on it: BackendURL and URLPath.
|
|
||||||
func TestURLTo(t *testing.T) {
|
|
||||||
var in struct {
|
|
||||||
Root string `json:"root"`
|
|
||||||
URLs []*string `json:"urls"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(readTestdata(t, "urlto.json"), &in); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
want := strings.Split(strings.TrimSuffix(string(readTestdata(t, "urlto.golden")), "\n"), "\n")
|
|
||||||
if len(in.URLs) < 50 || len(want) != len(in.URLs) {
|
|
||||||
t.Fatalf("%d inputs, %d golden lines", len(in.URLs), len(want))
|
|
||||||
}
|
|
||||||
for i, u := range in.URLs {
|
|
||||||
path := "<null>"
|
|
||||||
input := ""
|
|
||||||
if u != nil {
|
|
||||||
path, input = *u, *u
|
|
||||||
}
|
|
||||||
if got := classes.URLTo(in.Root, input); got != want[i] {
|
|
||||||
t.Errorf("case %d URLTo(%q) = %q, PHP %q", i, path, got, want[i])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tc := range []struct{ root, want string }{
|
|
||||||
{"https://api.ex.pl", "https://api.ex.pl"},
|
|
||||||
{"https://api.ex.pl/", "https://api.ex.pl"},
|
|
||||||
{"http://h:8080/base", "http://h:8080/base"},
|
|
||||||
} {
|
|
||||||
if got := classes.BackendURL(tc.root); got != tc.want {
|
|
||||||
t.Errorf("BackendURL(%q) = %q, want %q", tc.root, got, tc.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for raw, want := range map[string]string{
|
|
||||||
"https://h/a/b?x=1#f": "/a/b",
|
|
||||||
"https://h": "",
|
|
||||||
"https://h/": "/",
|
|
||||||
"/rel/path": "/rel/path",
|
|
||||||
"": "",
|
|
||||||
} {
|
|
||||||
if got := classes.URLPath(raw); got != want {
|
|
||||||
t.Errorf("URLPath(%q) = %q, want %q", raw, got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestAllowedItemURL pins the save rule of a url item's address (CR-01).
|
|
||||||
func TestAllowedItemURL(t *testing.T) {
|
|
||||||
for u, want := range map[string]bool{
|
|
||||||
"": true,
|
|
||||||
"/": true,
|
|
||||||
"/about": true,
|
|
||||||
"about/team?x=1": true,
|
|
||||||
"https://example.test/a": true,
|
|
||||||
"HTTP://example.test/a": true,
|
|
||||||
"javascript://%0aalert(1)%0a//x": false,
|
|
||||||
"javascript:alert(1)": false,
|
|
||||||
"data:text/html,x": false,
|
|
||||||
"mailto:a@example.test": false,
|
|
||||||
"//evil.test/x": false,
|
|
||||||
`/\evil.test/x`: false,
|
|
||||||
`\\evil.test`: false,
|
|
||||||
"#top": false,
|
|
||||||
" /about": false,
|
|
||||||
"/about\n": false,
|
|
||||||
"java\tscript:alert(1)": false,
|
|
||||||
} {
|
|
||||||
if got := classes.AllowedItemURL(u); got != want {
|
|
||||||
t.Errorf("AllowedItemURL(%q) = %v, want %v", u, got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
168
classes/writer.go
Normal file
168
classes/writer.go
Normal file
@@ -0,0 +1,168 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/xml"
|
||||||
|
"io"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The XML namespaces of the sitemap files.
|
||||||
|
const (
|
||||||
|
NSSitemap = "http://www.sitemaps.org/schemas/sitemap/0.9"
|
||||||
|
NSXHTML = "http://www.w3.org/1999/xhtml"
|
||||||
|
NSImage = "http://www.google.com/schemas/sitemap-image/1.1"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IndexFile is one <sitemap> of the index: the file's absolute URL and the
|
||||||
|
// newest lastmod of its addresses (nil when none has one).
|
||||||
|
type IndexFile struct {
|
||||||
|
Loc string
|
||||||
|
LastMod *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileAlternate is one xhtml:link alternate of a <url>, with an absolute
|
||||||
|
// href.
|
||||||
|
type FileAlternate struct {
|
||||||
|
Hreflang string
|
||||||
|
Href string
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileEntry is one <url> of a file: the absolute address, its lastmod and
|
||||||
|
// its hreflang alternates.
|
||||||
|
type FileEntry struct {
|
||||||
|
Loc string
|
||||||
|
LastMod *time.Time
|
||||||
|
Alternates []FileAlternate
|
||||||
|
}
|
||||||
|
|
||||||
|
// fileNamePattern is the name of a per-group file.
|
||||||
|
var fileNamePattern = regexp.MustCompile(`^sitemap-([a-z0-9][a-z0-9-]*)-([1-9][0-9]{0,8})\.xml$`)
|
||||||
|
|
||||||
|
// FileName is the name of file n of group grp: sitemap-<grp>-<n>.xml.
|
||||||
|
func FileName(grp string, n int) string {
|
||||||
|
return "sitemap-" + grp + "-" + strconv.Itoa(n) + ".xml"
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseFileName splits a file name made by FileName; ok is false for any
|
||||||
|
// other name.
|
||||||
|
func ParseFileName(name string) (grp string, n int, ok bool) {
|
||||||
|
m := fileNamePattern.FindStringSubmatch(name)
|
||||||
|
if m == nil {
|
||||||
|
return "", 0, false
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(m[2])
|
||||||
|
if err != nil || n < 1 {
|
||||||
|
return "", 0, false
|
||||||
|
}
|
||||||
|
return m[1], n, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// lastmod formats a lastmod in RFC 3339, UTC.
|
||||||
|
func lastmod(t time.Time) string { return t.UTC().Format(time.RFC3339) }
|
||||||
|
|
||||||
|
// escape writes s with encoding/xml's escaping, which covers &, <, >, both
|
||||||
|
// quotes and control whitespace, so it is safe in text and in attribute
|
||||||
|
// values.
|
||||||
|
func escape(w *bufio.Writer, s string) {
|
||||||
|
_ = xml.EscapeText(w, []byte(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteIndex writes the sitemap index: one <sitemap> per file with its
|
||||||
|
// <loc> and, when known, its <lastmod>.
|
||||||
|
func WriteIndex(w io.Writer, files []IndexFile) error {
|
||||||
|
bw := bufio.NewWriter(w)
|
||||||
|
bw.WriteString(xml.Header)
|
||||||
|
bw.WriteString(`<sitemapindex xmlns="` + NSSitemap + `">`)
|
||||||
|
for _, f := range files {
|
||||||
|
bw.WriteString("\n<sitemap><loc>")
|
||||||
|
escape(bw, f.Loc)
|
||||||
|
bw.WriteString("</loc>")
|
||||||
|
if f.LastMod != nil {
|
||||||
|
bw.WriteString("<lastmod>" + lastmod(*f.LastMod) + "</lastmod>")
|
||||||
|
}
|
||||||
|
bw.WriteString("</sitemap>")
|
||||||
|
}
|
||||||
|
bw.WriteString("\n</sitemapindex>\n")
|
||||||
|
return bw.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteURLSet writes one sitemap file: a <url> per entry with its <loc>, its
|
||||||
|
// <lastmod> when known and its xhtml:link alternates. The xhtml namespace
|
||||||
|
// is declared only when an entry has alternates. No <priority> and no
|
||||||
|
// <changefreq> are written (D-30).
|
||||||
|
func WriteURLSet(w io.Writer, entries []FileEntry) error {
|
||||||
|
bw := bufio.NewWriter(w)
|
||||||
|
bw.WriteString(xml.Header)
|
||||||
|
bw.WriteString(`<urlset xmlns="` + NSSitemap + `"`)
|
||||||
|
for _, e := range entries {
|
||||||
|
if len(e.Alternates) > 0 {
|
||||||
|
bw.WriteString(` xmlns:xhtml="` + NSXHTML + `"`)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bw.WriteString(">")
|
||||||
|
for _, e := range entries {
|
||||||
|
bw.WriteString("\n<url><loc>")
|
||||||
|
escape(bw, e.Loc)
|
||||||
|
bw.WriteString("</loc>")
|
||||||
|
if e.LastMod != nil {
|
||||||
|
bw.WriteString("<lastmod>" + lastmod(*e.LastMod) + "</lastmod>")
|
||||||
|
}
|
||||||
|
for _, a := range e.Alternates {
|
||||||
|
bw.WriteString(`<xhtml:link rel="alternate" hreflang="`)
|
||||||
|
escape(bw, a.Hreflang)
|
||||||
|
bw.WriteString(`" href="`)
|
||||||
|
escape(bw, a.Href)
|
||||||
|
bw.WriteString(`"/>`)
|
||||||
|
}
|
||||||
|
bw.WriteString("</url>")
|
||||||
|
}
|
||||||
|
bw.WriteString("\n</urlset>\n")
|
||||||
|
return bw.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ImageEntry is one <url> of an image sitemap: the page's absolute address
|
||||||
|
// and its images' absolute addresses (at most MaxImagesPerURL).
|
||||||
|
type ImageEntry struct {
|
||||||
|
Loc string
|
||||||
|
Images []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteImageURLSet writes one image sitemap file: a <url> per page with its
|
||||||
|
// <loc> and one <image:image><image:loc> per image. Only image:image and
|
||||||
|
// image:loc are written, the tags Google still reads (D-31).
|
||||||
|
func WriteImageURLSet(w io.Writer, entries []ImageEntry) error {
|
||||||
|
bw := bufio.NewWriter(w)
|
||||||
|
bw.WriteString(xml.Header)
|
||||||
|
bw.WriteString(`<urlset xmlns="` + NSSitemap + `" xmlns:image="` + NSImage + `">`)
|
||||||
|
for _, e := range entries {
|
||||||
|
bw.WriteString("\n<url><loc>")
|
||||||
|
escape(bw, e.Loc)
|
||||||
|
bw.WriteString("</loc>")
|
||||||
|
for i, img := range e.Images {
|
||||||
|
if i >= MaxImagesPerURL {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
bw.WriteString("<image:image><image:loc>")
|
||||||
|
escape(bw, img)
|
||||||
|
bw.WriteString("</image:loc></image:image>")
|
||||||
|
}
|
||||||
|
bw.WriteString("</url>")
|
||||||
|
}
|
||||||
|
bw.WriteString("\n</urlset>\n")
|
||||||
|
return bw.Flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
// validSlug reports whether s may name a file group.
|
||||||
|
func validSlug(s string) bool {
|
||||||
|
return s != "" && len(s) <= 64 && fileNamePattern.MatchString(FileName(s, 1)) && !strings.HasSuffix(s, "-")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidSlug reports whether s may name a file group: lowercase letters,
|
||||||
|
// digits and hyphens, starting with a letter or digit, at most 64
|
||||||
|
// characters.
|
||||||
|
func ValidSlug(s string) bool { return validSlug(s) }
|
||||||
141
classes/writer_test.go
Normal file
141
classes/writer_test.go
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
package classes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/xml"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestWriteURLSet pins a sitemap file: the sitemap namespace, the xhtml
|
||||||
|
// namespace only when an entry has alternates, escaped locs and
|
||||||
|
// attributes, lastmod in UTC RFC 3339 and never a priority or changefreq,
|
||||||
|
// and well-formed XML.
|
||||||
|
func TestWriteURLSet(t *testing.T) {
|
||||||
|
at := time.Date(2026, 11, 4, 18, 30, 0, 0, time.FixedZone("CET", 3600))
|
||||||
|
var buf bytes.Buffer
|
||||||
|
err := WriteURLSet(&buf, []FileEntry{
|
||||||
|
{Loc: "https://example.test/a?x=1&y=<2>", LastMod: &at},
|
||||||
|
{Loc: "https://example.test/b", Alternates: []FileAlternate{{Hreflang: "en", Href: "https://example.test/b"}, {Hreflang: "x-default", Href: `https://example.test/b?"q"`}}},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
out := buf.String()
|
||||||
|
for _, want := range []string{
|
||||||
|
xml.Header,
|
||||||
|
`<urlset xmlns="` + NSSitemap + `" xmlns:xhtml="` + NSXHTML + `">`,
|
||||||
|
`<loc>https://example.test/a?x=1&y=<2></loc><lastmod>2026-11-04T17:30:00Z</lastmod>`,
|
||||||
|
`<xhtml:link rel="alternate" hreflang="x-default" href="https://example.test/b?"q""/>`,
|
||||||
|
} {
|
||||||
|
if !strings.Contains(out, want) {
|
||||||
|
t.Fatalf("file lacks %s:\n%s", want, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, never := range []string{"<priority>", "<changefreq>"} {
|
||||||
|
if strings.Contains(out, never) {
|
||||||
|
t.Fatalf("file has %s:\n%s", never, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wellFormed(t, out)
|
||||||
|
|
||||||
|
buf.Reset()
|
||||||
|
if err := WriteURLSet(&buf, []FileEntry{{Loc: "https://example.test/"}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.Contains(buf.String(), "xmlns:xhtml") || strings.Contains(buf.String(), "<lastmod>") {
|
||||||
|
t.Fatalf("no alternates and no lastmod, yet:\n%s", buf.String())
|
||||||
|
}
|
||||||
|
wellFormed(t, buf.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWriteIndex pins the index: one sitemap per file, lastmod only when
|
||||||
|
// known.
|
||||||
|
func TestWriteIndex(t *testing.T) {
|
||||||
|
at := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := WriteIndex(&buf, []IndexFile{{Loc: "https://example.test/sitemap-pages-1.xml", LastMod: &at}, {Loc: "https://example.test/sitemap-posts-1.xml"}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
out := buf.String()
|
||||||
|
if !strings.Contains(out, `<sitemapindex xmlns="`+NSSitemap+`">`) ||
|
||||||
|
!strings.Contains(out, "<sitemap><loc>https://example.test/sitemap-pages-1.xml</loc><lastmod>2026-01-02T03:04:05Z</lastmod></sitemap>") ||
|
||||||
|
!strings.Contains(out, "<sitemap><loc>https://example.test/sitemap-posts-1.xml</loc></sitemap>") {
|
||||||
|
t.Fatalf("index:\n%s", out)
|
||||||
|
}
|
||||||
|
wellFormed(t, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestWriteImageURLSet pins the image file: the image namespace, only
|
||||||
|
// image:image and image:loc, escaping, and the MaxImagesPerURL cap.
|
||||||
|
func TestWriteImageURLSet(t *testing.T) {
|
||||||
|
many := make([]string, MaxImagesPerURL+5)
|
||||||
|
for i := range many {
|
||||||
|
many[i] = "https://cdn.example.test/i.jpg?n=" + strings.Repeat("1", i%3+1)
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := WriteImageURLSet(&buf, []ImageEntry{{Loc: "https://example.test/a", Images: []string{"https://cdn.example.test/c&d.webp"}}, {Loc: "https://example.test/b", Images: many}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
out := buf.String()
|
||||||
|
if !strings.Contains(out, `xmlns:image="`+NSImage+`"`) || !strings.Contains(out, "<image:image><image:loc>https://cdn.example.test/c&d.webp</image:loc></image:image>") {
|
||||||
|
t.Fatalf("image file:\n%s", out)
|
||||||
|
}
|
||||||
|
if n := strings.Count(out, "<image:image>"); n != 1+MaxImagesPerURL {
|
||||||
|
t.Fatalf("%d images, want 1 + the %d cap", n, MaxImagesPerURL)
|
||||||
|
}
|
||||||
|
for _, never := range []string{"image:caption", "image:title", "image:license"} {
|
||||||
|
if strings.Contains(out, never) {
|
||||||
|
t.Fatalf("image file has %s", never)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wellFormed(t, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFileNames pins FileName and ParseFileName as inverses and the names
|
||||||
|
// ParseFileName refuses.
|
||||||
|
func TestFileNamesRoundTrip(t *testing.T) {
|
||||||
|
for _, tc := range []struct {
|
||||||
|
grp string
|
||||||
|
n int
|
||||||
|
}{{"pages", 1}, {"posts", 12}, {"news-2", 999999999}, {"a", 3}} {
|
||||||
|
name := FileName(tc.grp, tc.n)
|
||||||
|
grp, n, ok := ParseFileName(name)
|
||||||
|
if !ok || grp != tc.grp || n != tc.n {
|
||||||
|
t.Errorf("ParseFileName(%q) = %q %d %v", name, grp, n, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bad := range []string{"sitemap.xml", "sitemap-pages-0.xml", "sitemap-pages-01.xml", "sitemap-Pages-1.xml", "sitemap--1.xml", "sitemap-pages-1.xml.gz", "sitemap-pages-1234567890.xml", "../sitemap-pages-1.xml", "sitemap-pages-1"} {
|
||||||
|
if _, _, ok := ParseFileName(bad); ok {
|
||||||
|
t.Errorf("ParseFileName(%q) accepted", bad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestValidSlug pins the group slug rule.
|
||||||
|
func TestValidSlug(t *testing.T) {
|
||||||
|
for s, want := range map[string]bool{
|
||||||
|
"pages": true, "news-2": true, "0abc": true, strings.Repeat("a", 64): true,
|
||||||
|
"": false, "-pages": false, "pages-": false, "Pages": false, "pa ges": false, "pa_ges": false, "żółw": false, strings.Repeat("a", 65): false,
|
||||||
|
} {
|
||||||
|
if got := ValidSlug(s); got != want {
|
||||||
|
t.Errorf("ValidSlug(%q) = %v, want %v", s, got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// wellFormed parses out as XML to its end.
|
||||||
|
func wellFormed(t *testing.T, out string) {
|
||||||
|
t.Helper()
|
||||||
|
d := xml.NewDecoder(strings.NewReader(out))
|
||||||
|
for {
|
||||||
|
_, err := d.Token()
|
||||||
|
if err != nil {
|
||||||
|
if err.Error() == "EOF" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
t.Fatalf("not well-formed: %v\n%s", err, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,7 +3,10 @@ package sitemap
|
|||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/conga"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestCommandsDocumented logs every console command whose help lacks a
|
// TestCommandsDocumented logs every console command whose help lacks a
|
||||||
@@ -19,3 +22,33 @@ func TestCommandsDocumented(t *testing.T) {
|
|||||||
t.Logf("%s", problem)
|
t.Logf("%s", problem)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestScheduleAndJobs pins the nightly sitemap:rebuild at 03:00, which must
|
||||||
|
// name a registered command, the rebuild job (kind golem15.sitemap.rebuild,
|
||||||
|
// three attempts) and the IndexNow job (golem15.sitemap.indexnow, five).
|
||||||
|
func TestScheduleAndJobs(t *testing.T) {
|
||||||
|
p := &Plugin{}
|
||||||
|
entries := p.Schedule()
|
||||||
|
if len(entries) != 1 || entries[0].Command != "sitemap:rebuild" || entries[0].Cadence != pact.DailyAt(3, 0) {
|
||||||
|
t.Fatalf("schedule = %+v", entries)
|
||||||
|
}
|
||||||
|
found := false
|
||||||
|
for _, c := range p.Commands() {
|
||||||
|
found = found || c.Name == entries[0].Command
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Fatal("the scheduled command is not registered")
|
||||||
|
}
|
||||||
|
jobs := p.Jobs()
|
||||||
|
if len(jobs) != 2 {
|
||||||
|
t.Fatalf("%d jobs", len(jobs))
|
||||||
|
}
|
||||||
|
info, ok := conga.Describe(jobs[0])
|
||||||
|
if !ok || info.Kind != classes.RebuildKind || info.MaxAttempts != 3 {
|
||||||
|
t.Fatalf("job = %+v %v", info, ok)
|
||||||
|
}
|
||||||
|
info, ok = conga.Describe(jobs[1])
|
||||||
|
if !ok || info.Kind != classes.IndexNowKind || info.MaxAttempts != 5 {
|
||||||
|
t.Fatalf("job = %+v %v", info, ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,44 +1,26 @@
|
|||||||
# golem15.sitemap defaults, read as golem15.sitemap.<key>.
|
# golem15.sitemap defaults, read as golem15.sitemap.<key>.
|
||||||
#
|
#
|
||||||
# cache_seconds is how long a generated /sitemap.xml is served from memory.
|
# site_url is the public site address every <loc> of the sitemaps starts
|
||||||
# A save of the definition or the settings shows at once; registry content
|
# with when the Site address setting is empty; without both, app.url is
|
||||||
# (a new or changed post) shows once the entry expires. 0 turns the cache
|
# used. The request's Host is never used. Set it per environment, e.g.:
|
||||||
# off.
|
|
||||||
cache_seconds: 60
|
|
||||||
#
|
#
|
||||||
# The priority tier rules assign a URL the value of one of the five
|
# site_url: https://www.example.com
|
||||||
# priority settings when Enable priority tiers is on. A URL's path, without
|
|
||||||
# trailing slashes ("" for the homepage), is matched against the rules in
|
|
||||||
# order and the first match wins; a URL no rule matches keeps its item's
|
|
||||||
# priority. Each rule names a setting (priority_homepage, priority_services,
|
|
||||||
# priority_blog, priority_categories or priority_legal) and either exact
|
|
||||||
# (a list of paths) or pattern (a regular expression in RE2 syntax, checked
|
|
||||||
# at boot).
|
|
||||||
#
|
#
|
||||||
# The defaults below are the rules the WinterCMS plugin had in code
|
# lastmod_ignore lists the record attributes whose change does not move an
|
||||||
# (getPriorityForUrl), so a site configured the same way produces the same
|
# address's lastmod: a save that changes only these (or nothing) leaves it
|
||||||
# priorities. A host replaces the whole list in its own config, for example
|
# as it was. A host replaces the whole list in its own config.
|
||||||
# in config/golem15.yaml under the same key below sitemap:.
|
lastmod_ignore:
|
||||||
priority_tiers:
|
- updated_at
|
||||||
- setting: priority_homepage
|
- created_at
|
||||||
exact: ["", "/en"]
|
- views
|
||||||
- setting: priority_services
|
- sort_order
|
||||||
pattern: '^/(uslugi|en/services|realizacje|en/work)/[^/]+$'
|
#
|
||||||
- setting: priority_blog
|
# rebuild_delay_seconds is how long after a record change the queued
|
||||||
pattern: '^/(blog|en/blog)/[^/]+/[^/]+$'
|
# rebuild runs; further changes in that time join the same rebuild.
|
||||||
- setting: priority_categories
|
rebuild_delay_seconds: 60
|
||||||
pattern: '^/(uslugi|en/services|realizacje|en/work|blog|en/blog)(/[^/]+)?$'
|
#
|
||||||
- setting: priority_legal
|
# IndexNow has no config key: the endpoint is fixed at
|
||||||
exact:
|
# https://api.indexnow.org/indexnow (the only host the plugin's outbound
|
||||||
- /polityka-prywatnosci
|
# client may reach), the key is generated in the settings and stored in the
|
||||||
- /en/privacy-policy
|
# database, and requests are sent only when the app environment is
|
||||||
- /regulamin
|
# production.
|
||||||
- /en/terms
|
|
||||||
- /o-nas
|
|
||||||
- /en/about
|
|
||||||
- /kontakt
|
|
||||||
- /en/contact
|
|
||||||
- /laboratorium-ai
|
|
||||||
- /en/ai-lab
|
|
||||||
- /laboratorium-ai/zabawa-animacja
|
|
||||||
- /en/ai-lab/blob-playground
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// Package console holds the sitemap plugin's commands: sitemap:import (the
|
// Package console holds the sitemap plugin's commands: sitemap:rebuild,
|
||||||
// PHP ImportCommand) and sitemap:import-winter (a copy of a WinterCMS
|
// sitemap:import (a JSON list of additional addresses) and
|
||||||
// site's definition and settings).
|
// sitemap:import-winter (a copy of a WinterCMS site's url items and
|
||||||
|
// settings).
|
||||||
package console
|
package console
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -56,20 +57,24 @@ func lookupDB(ctx context.Context, app *backpack.App) (*gorm.DB, func(), error)
|
|||||||
return gdb, func() { _ = sqlDB.Close() }, nil
|
return gdb, func() { _ = sqlDB.Close() }, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// singletonDefinition loads the definition with the fixed theme key,
|
// loadSettingsForUpdate reads settings row 1 inside tx, locked, creating
|
||||||
// creating it when there is none (PHP Definition::firstOrCreate).
|
// it when the migration's row is gone.
|
||||||
func singletonDefinition(tx *gorm.DB) (models.Definition, error) {
|
func loadSettingsForUpdate(tx *gorm.DB) (models.Settings, error) {
|
||||||
var defs []models.Definition
|
if err := tx.Exec(`INSERT INTO golem15_sitemap_settings (id) VALUES (1) ON CONFLICT (id) DO NOTHING`).Error; err != nil {
|
||||||
if err := tx.Where("theme = ?", models.DefinitionTheme).Order("id ASC").Limit(1).Find(&defs).Error; err != nil {
|
return models.Settings{}, err
|
||||||
return models.Definition{}, err
|
|
||||||
}
|
}
|
||||||
if len(defs) > 0 {
|
var s models.Settings
|
||||||
return defs[0], nil
|
if err := tx.Raw(`SELECT * FROM golem15_sitemap_settings WHERE id = 1 FOR UPDATE`).Scan(&s).Error; err != nil {
|
||||||
|
return models.Settings{}, err
|
||||||
}
|
}
|
||||||
theme := models.DefinitionTheme
|
return s, nil
|
||||||
def := models.Definition{Theme: &theme}
|
}
|
||||||
if err := tx.Create(&def).Error; err != nil {
|
|
||||||
return models.Definition{}, err
|
// saveExtra stores the additional addresses on settings row 1.
|
||||||
}
|
func saveExtra(tx *gorm.DB, rows []models.ExtraURL) error {
|
||||||
return def, nil
|
if rows == nil {
|
||||||
|
rows = []models.ExtraURL{}
|
||||||
|
}
|
||||||
|
value := lagoon.Jsonable[[]models.ExtraURL]{Data: rows, Valid: true}
|
||||||
|
return tx.Exec(`UPDATE golem15_sitemap_settings SET extra_urls = ? WHERE id = 1`, value).Error
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,55 +1,55 @@
|
|||||||
package console
|
package console
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Import is sitemap:import FILE [--theme=] [--append], the PHP
|
// Import is sitemap:import FILE [--append]: it reads a JSON array of URL
|
||||||
// ImportCommand: it reads a JSON array of URL entries ({"url": ...,
|
// entries ({"url": "/path", "lastmod": "2026-10-28"}; lastmod optional) into
|
||||||
// "changefreq": ..., "priority": ...}; changefreq defaults to monthly,
|
// the settings' additional addresses, in one transaction. Without --append
|
||||||
// priority to 0.5) into the sitemap definition. Without --append the
|
// the imported addresses replace the additional addresses; with --append
|
||||||
// definition keeps its non-url items first and the imported URLs replace
|
// they are added after them, an address already listed is skipped. An
|
||||||
// its url items; with --append the URLs are added after every existing item.
|
// entry whose url is not a path or an http(s) URL (models.AllowedAddress),
|
||||||
// The definition is always the one /sitemap.xml serves (theme default);
|
// or whose lastmod is not a date, stops the import before anything is
|
||||||
// --theme is accepted for PHP compatibility and a theme other than default
|
// written. The Phase 17 keys changefreq and priority are ignored, and
|
||||||
// is reported. An entry whose url is not a path or an http(s) URL
|
// --theme is accepted for the PHP command's sake. The files follow at the
|
||||||
// (classes.AllowedItemURL) is refused, as the admin form refuses it.
|
// next rebuild (sitemap:rebuild).
|
||||||
func Import(app *backpack.App) bonfire.Command {
|
func Import(app *backpack.App) bonfire.Command {
|
||||||
return bonfire.Command{
|
return bonfire.Command{
|
||||||
Name: "sitemap:import",
|
Name: "sitemap:import",
|
||||||
Description: "Import sitemap URLs from a JSON manifest file",
|
Description: "Import additional sitemap addresses from a JSON manifest file",
|
||||||
Long: `Reads a JSON array of URL entries ({"url": "/path", "changefreq":
|
Long: `Reads a JSON array of URL entries ({"url": "/path", "lastmod":
|
||||||
"monthly", "priority": "0.5"}; changefreq and priority are optional) and puts
|
"2026-10-28"}; lastmod is optional) and puts them into the sitemap's
|
||||||
them into the sitemap definition that /sitemap.xml serves, in one
|
additional addresses (Settings > Sitemaps > Additional addresses), in one
|
||||||
transaction. Every entry needs a url that is a path or an http(s) URL; one
|
transaction. Every entry needs a url that is a path or an http(s) URL; one bad
|
||||||
bad entry stops the import before anything is written.
|
entry stops the import before anything is written. The old changefreq and
|
||||||
|
priority keys are ignored: the sitemaps no longer write them.
|
||||||
|
|
||||||
By default the import replaces the definition's url items and keeps its
|
By default the import replaces the additional addresses. --append adds the
|
||||||
dynamic items (pages, posts and other generated types). --append adds the
|
addresses after them and skips those already listed. --theme is accepted for
|
||||||
URLs and keeps every existing item. --theme is accepted for the PHP command's
|
the PHP command's sake and does nothing. The files change at the next rebuild
|
||||||
sake: only the default definition is served, so the URLs always go there.
|
(sitemap:rebuild, a settings save or the nightly run). It ends with
|
||||||
It ends with "Imported N URLs into sitemap definition for theme 'default'."`,
|
"Imported N addresses into the sitemap's additional addresses."`,
|
||||||
Args: []bonfire.Arg{
|
Args: []bonfire.Arg{
|
||||||
{Name: "file", Description: "Path to the JSON manifest (relative to the working directory or absolute)", Required: true},
|
{Name: "file", Description: "Path to the JSON manifest (relative to the working directory or absolute)", Required: true},
|
||||||
},
|
},
|
||||||
Flags: []bonfire.Flag{
|
Flags: []bonfire.Flag{
|
||||||
{Name: "theme", Description: "Theme code of the PHP plugin; /sitemap.xml serves only the default definition"},
|
{Name: "theme", Description: "Accepted for the PHP command; ignored"},
|
||||||
{Name: "append", Description: "Add URLs without removing existing url-type items", Bare: true},
|
{Name: "append", Description: "Add the addresses instead of replacing the additional addresses", Bare: true},
|
||||||
},
|
},
|
||||||
Examples: []bonfire.Example{
|
Examples: []bonfire.Example{
|
||||||
{Command: "sitemap:import urls.json", Description: "Replace the url items with the manifest's URLs"},
|
{Command: "sitemap:import urls.json", Description: "Replace the additional addresses with the manifest's addresses"},
|
||||||
{Command: "sitemap:import urls.json --append", Description: "Add the URLs and keep every existing item"},
|
{Command: "sitemap:import urls.json --append", Description: "Add the addresses and keep the existing ones"},
|
||||||
},
|
},
|
||||||
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
|
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
|
||||||
file, _ := in.Argument("file")
|
file, _ := in.Argument("file")
|
||||||
@@ -72,136 +72,67 @@ func ImportFile(ctx context.Context, db *gorm.DB, file, theme string, appendMode
|
|||||||
}
|
}
|
||||||
return fmt.Errorf("Cannot read %s: %w", file, err)
|
return fmt.Errorf("Cannot read %s: %w", file, err)
|
||||||
}
|
}
|
||||||
entries, labels, ok := orderedEntries(raw)
|
entries, labels, ok := models.LegacyEntries(raw)
|
||||||
if !ok {
|
if !ok {
|
||||||
return errors.New("Invalid JSON: expected an array of URL entries")
|
return errors.New("Invalid JSON: expected an array of URL entries")
|
||||||
}
|
}
|
||||||
newItems := make([]models.DefinitionItem, 0, len(entries))
|
rows := make([]models.ExtraURL, 0, len(entries))
|
||||||
for i, entry := range entries {
|
for i, entry := range entries {
|
||||||
var fields map[string]json.RawMessage
|
var fields map[string]json.RawMessage
|
||||||
_ = json.Unmarshal(entry, &fields)
|
_ = json.Unmarshal(entry, &fields)
|
||||||
url, err := models.DecodeText(fields["url"])
|
url, err := models.DecodeText(fields["url"])
|
||||||
if fields["url"] == nil || err != nil || phpEmpty(fields["url"]) {
|
if fields["url"] == nil || err != nil || strings.TrimSpace(models.Text(url)) == "" {
|
||||||
return fmt.Errorf("Entry %s is missing a 'url' field", labels[i])
|
return fmt.Errorf("Entry %s is missing a 'url' field", labels[i])
|
||||||
}
|
}
|
||||||
if !classes.AllowedItemURL(models.Text(url)) {
|
u := strings.TrimSpace(models.Text(url))
|
||||||
|
if !models.AllowedAddress(u) {
|
||||||
return fmt.Errorf("Entry %s has a url that is not a path or an http(s) URL", labels[i])
|
return fmt.Errorf("Entry %s has a url that is not a path or an http(s) URL", labels[i])
|
||||||
}
|
}
|
||||||
item := models.DefinitionItem{Type: models.ItemTypeURL, URL: url}
|
row := models.ExtraURL{URL: u}
|
||||||
item.Changefreq = textOr(fields["changefreq"], "monthly")
|
if raw, ok := fields["lastmod"]; ok {
|
||||||
item.Priority = textOr(fields["priority"], "0.5")
|
mod, err := models.DecodeText(raw)
|
||||||
newItems = append(newItems, item)
|
if err != nil || (strings.TrimSpace(models.Text(mod)) != "" && !models.ValidDate(models.Text(mod))) {
|
||||||
|
return fmt.Errorf("Entry %s has a lastmod that is not a date (YYYY-MM-DD)", labels[i])
|
||||||
|
}
|
||||||
|
row.LastMod = strings.TrimSpace(models.Text(mod))
|
||||||
|
}
|
||||||
|
rows = append(rows, row)
|
||||||
}
|
}
|
||||||
var kept int
|
var kept, added int
|
||||||
err = db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
err = db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
def, err := singletonDefinition(tx)
|
s, err := loadSettingsForUpdate(tx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
existing := def.Items()
|
next := []models.ExtraURL{}
|
||||||
if !appendMode {
|
seen := map[string]bool{}
|
||||||
var dynamic []models.DefinitionItem
|
if appendMode {
|
||||||
for _, item := range existing {
|
for _, e := range s.Extra() {
|
||||||
if item.Type != models.ItemTypeURL {
|
next = append(next, e)
|
||||||
dynamic = append(dynamic, item)
|
seen[e.URL] = true
|
||||||
}
|
|
||||||
}
|
}
|
||||||
existing = dynamic
|
kept = len(next)
|
||||||
}
|
}
|
||||||
kept = len(existing)
|
for _, r := range rows {
|
||||||
def.SetItems(append(append([]models.DefinitionItem{}, existing...), newItems...))
|
if seen[r.URL] {
|
||||||
return tx.Save(&def).Error
|
continue
|
||||||
|
}
|
||||||
|
seen[r.URL] = true
|
||||||
|
next = append(next, r)
|
||||||
|
added++
|
||||||
|
}
|
||||||
|
return saveExtra(tx, next)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
out.Success(fmt.Sprintf("Imported %d URLs into sitemap definition for theme '%s'.", len(newItems), models.DefinitionTheme))
|
out.Success(fmt.Sprintf("Imported %d addresses into the sitemap's additional addresses.", added))
|
||||||
if kept > 0 {
|
if kept > 0 {
|
||||||
label := "existing non-URL (dynamic)"
|
out.Info(fmt.Sprintf("Kept %d existing addresses.", kept))
|
||||||
if appendMode {
|
|
||||||
label = "existing"
|
|
||||||
}
|
|
||||||
out.Info(fmt.Sprintf("Kept %d %s items.", kept, label))
|
|
||||||
}
|
}
|
||||||
if theme != "" && theme != models.DefinitionTheme {
|
if theme != "" {
|
||||||
out.Warning(fmt.Sprintf("Theme '%s' was given, but /sitemap.xml serves only the '%s' definition, so the URLs were imported there.", theme, models.DefinitionTheme))
|
out.Warning(fmt.Sprintf("Theme '%s' was given; the sitemap has one set of additional addresses, so the addresses were imported there.", theme))
|
||||||
}
|
}
|
||||||
|
out.Info("Run sitemap:rebuild (or save the sitemap settings) to update the files now.")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// orderedEntries splits a JSON array, or a JSON object in key order (a PHP
|
|
||||||
// array with keys), into its values with their PHP labels (index or key).
|
|
||||||
func orderedEntries(raw []byte) ([]json.RawMessage, []string, bool) {
|
|
||||||
raw = bytes.TrimSpace(raw)
|
|
||||||
if len(raw) == 0 {
|
|
||||||
return nil, nil, false
|
|
||||||
}
|
|
||||||
switch raw[0] {
|
|
||||||
case '[':
|
|
||||||
var list []json.RawMessage
|
|
||||||
if err := json.Unmarshal(raw, &list); err != nil {
|
|
||||||
return nil, nil, false
|
|
||||||
}
|
|
||||||
labels := make([]string, len(list))
|
|
||||||
for i := range list {
|
|
||||||
labels[i] = fmt.Sprint(i)
|
|
||||||
}
|
|
||||||
return list, labels, true
|
|
||||||
case '{':
|
|
||||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
|
||||||
if _, err := dec.Token(); err != nil {
|
|
||||||
return nil, nil, false
|
|
||||||
}
|
|
||||||
var list []json.RawMessage
|
|
||||||
var labels []string
|
|
||||||
for dec.More() {
|
|
||||||
tok, err := dec.Token()
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, false
|
|
||||||
}
|
|
||||||
key, _ := tok.(string)
|
|
||||||
var v json.RawMessage
|
|
||||||
if err := dec.Decode(&v); err != nil {
|
|
||||||
return nil, nil, false
|
|
||||||
}
|
|
||||||
list = append(list, v)
|
|
||||||
labels = append(labels, key)
|
|
||||||
}
|
|
||||||
return list, labels, true
|
|
||||||
}
|
|
||||||
return nil, nil, false
|
|
||||||
}
|
|
||||||
|
|
||||||
// phpEmpty is PHP empty() of a decoded JSON value.
|
|
||||||
func phpEmpty(raw json.RawMessage) bool {
|
|
||||||
var v any
|
|
||||||
if err := json.Unmarshal(raw, &v); err != nil {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
switch t := v.(type) {
|
|
||||||
case nil:
|
|
||||||
return true
|
|
||||||
case string:
|
|
||||||
return t == "" || t == "0"
|
|
||||||
case bool:
|
|
||||||
return !t
|
|
||||||
case float64:
|
|
||||||
return t == 0
|
|
||||||
case []any:
|
|
||||||
return len(t) == 0
|
|
||||||
case map[string]any:
|
|
||||||
return len(t) == 0
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// textOr is PHP `$entry[key] ?? fallback` as text: a missing or null value
|
|
||||||
// is the fallback.
|
|
||||||
func textOr(raw json.RawMessage, fallback string) *string {
|
|
||||||
if raw != nil {
|
|
||||||
if s, err := models.DecodeText(raw); err == nil && s != nil {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return &fallback
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -8,15 +8,12 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"slices"
|
|
||||||
"sort"
|
"sort"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||||
"git.golem15.com/golem15/summercms/modules/signpost"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -34,11 +31,12 @@ var droppedTypes = map[string]bool{
|
|||||||
// of scripts/winter-export-settings.sql (the JSON object of the
|
// of scripts/winter-export-settings.sql (the JSON object of the
|
||||||
// golem15_sitemap_settings system setting). Theme picks a definition when
|
// golem15_sitemap_settings system setting). Theme picks a definition when
|
||||||
// the export holds several. Maps rename item types (old to new) before they
|
// the export holds several. Maps rename item types (old to new) before they
|
||||||
// are checked. PageURLs turns a static or CMS page item into a url item:
|
// are checked. PageURLs turns a static or CMS page item into an additional
|
||||||
// its key is the item's reference (the PHP page file name, for example
|
// address: its key is the item's reference (the PHP page file name, for
|
||||||
// blog), its value the page's URL (/blog). Force replaces a definition that
|
// example blog), its value the page's URL (/blog). Force replaces
|
||||||
// has items; DryRun reports without writing. A frontend_url that
|
// additional addresses that are already stored; DryRun reports without
|
||||||
// models.AllowedFrontendURL refuses stops the import and nothing is written.
|
// writing. A frontend_url that models.AllowedFrontendURL refuses stops the
|
||||||
|
// import and nothing is written.
|
||||||
type WinterOptions struct {
|
type WinterOptions struct {
|
||||||
DefinitionsFile string
|
DefinitionsFile string
|
||||||
SettingsFile string
|
SettingsFile string
|
||||||
@@ -49,7 +47,7 @@ type WinterOptions struct {
|
|||||||
DryRun bool
|
DryRun bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// WinterReport is what sitemap:import-winter did: the items kept, the
|
// WinterReport is what sitemap:import-winter did: the addresses kept, the
|
||||||
// report lines of every dropped or remapped item, and whether the settings
|
// report lines of every dropped or remapped item, and whether the settings
|
||||||
// were copied.
|
// were copied.
|
||||||
type WinterReport struct {
|
type WinterReport struct {
|
||||||
@@ -60,50 +58,59 @@ type WinterReport struct {
|
|||||||
Settings bool
|
Settings bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// winterSettings are the WinterCMS settings the per-type sitemap reads.
|
||||||
|
type winterSettings struct {
|
||||||
|
SiteURL string
|
||||||
|
DefaultLocale string
|
||||||
|
}
|
||||||
|
|
||||||
// ImportWinter is sitemap:import-winter: it copies a WinterCMS site's
|
// ImportWinter is sitemap:import-winter: it copies a WinterCMS site's
|
||||||
// sitemap definition and settings into the definition /sitemap.xml serves
|
// sitemap definition into the settings' additional addresses and its
|
||||||
// (theme default) and the settings row. Item types are mapped (url kept,
|
// frontend_url and frontend_default_locale into the site address and the
|
||||||
// static and CMS page types dropped unless --page-url reference=/path names
|
// default locale (D-32). url items are kept (static and CMS page items
|
||||||
// their URL, --map old=new renames applied first),
|
// become addresses when --page-url reference=/path names their URL,
|
||||||
// an item of a registry type that takes references is dropped when its
|
// --map old=new renames applied first); every other item is dropped and
|
||||||
// reference is not among the type's current references, an item of an
|
// listed, because the content types list their records themselves. A url
|
||||||
// unknown type is dropped, a url item whose URL is not a path or an http(s)
|
// item whose URL is not a path or an http(s) URL (models.AllowedAddress)
|
||||||
// URL (classes.AllowedItemURL) is dropped, a URL pattern that is not a path
|
// is dropped. Stored additional addresses are replaced only with --force.
|
||||||
// (signpost.ValidItemPattern) is cleared, and every dropped, remapped or
|
// Settings keys of the PHP-parity format (priorities, tiers, the update
|
||||||
// cleared item is printed. A definition that already has items is refused
|
// manifest) are reported as ignored. A frontend_url that
|
||||||
// without --force. Settings keys missing from the export take the PHP
|
// models.AllowedFrontendURL refuses stops the import and nothing is
|
||||||
// defaults. A frontend_url that models.AllowedFrontendURL refuses stops the
|
// written.
|
||||||
// import and nothing is written.
|
|
||||||
func ImportWinter(app *backpack.App) bonfire.Command {
|
func ImportWinter(app *backpack.App) bonfire.Command {
|
||||||
return bonfire.Command{
|
return bonfire.Command{
|
||||||
Name: "sitemap:import-winter",
|
Name: "sitemap:import-winter",
|
||||||
Description: "Copy a WinterCMS sitemap definition and settings export into this application",
|
Description: "Copy a WinterCMS sitemap definition and settings export into this application",
|
||||||
Long: `Copies the sitemap definition of a WinterCMS site (the JSON lines that
|
Long: `Copies the sitemap definition of a WinterCMS site (the JSON lines that
|
||||||
scripts/winter-export-definitions.sql prints) and its settings (the JSON
|
scripts/winter-export-definitions.sql prints) and its settings (the JSON
|
||||||
object from scripts/winter-export-settings.sql) in one transaction. Item
|
object from scripts/winter-export-settings.sql) in one transaction. The
|
||||||
types this application knows are kept; --map renames a type (old=new) and
|
definition's url items become the sitemap's additional addresses; --page-url
|
||||||
--page-url turns a static or CMS page item into a url item with the given
|
turns a static or CMS page item into an address with the given path, and
|
||||||
path. Items that still have no known type are dropped and listed. When the
|
--map renames a type first (old=new). Every other item is dropped and listed:
|
||||||
export holds several themes, --theme picks the one to copy.
|
the content types (posts, categories and so on) list their records
|
||||||
|
themselves. The settings' frontend_url becomes the site address and
|
||||||
|
frontend_default_locale the default locale; priorities, tiers and the update
|
||||||
|
manifest are no longer used. When the export holds several themes, --theme
|
||||||
|
picks the one to copy.
|
||||||
|
|
||||||
Run it once when an application moves from WinterCMS, --dry-run first:
|
Run it once when an application moves from WinterCMS, --dry-run first:
|
||||||
--dry-run reports kept, remapped and dropped items and writes nothing. A
|
--dry-run reports kept, remapped and dropped items and writes nothing. Stored
|
||||||
definition that already has items is replaced only with --force. It ends
|
additional addresses are replaced only with --force. It ends with "Definition
|
||||||
with "Definition copied: N items kept, N remapped, N dropped." and "Settings
|
copied: N items kept, N remapped, N dropped." and "Settings copied." for the
|
||||||
copied." for the parts the export holds.`,
|
parts the export holds.`,
|
||||||
Flags: []bonfire.Flag{
|
Flags: []bonfire.Flag{
|
||||||
{Name: "definitions", Description: "Definitions export (JSON lines from scripts/winter-export-definitions.sql)"},
|
{Name: "definitions", Description: "Definitions export (JSON lines from scripts/winter-export-definitions.sql)"},
|
||||||
{Name: "settings", Description: "Settings export (the JSON object from scripts/winter-export-settings.sql)"},
|
{Name: "settings", Description: "Settings export (the JSON object from scripts/winter-export-settings.sql)"},
|
||||||
{Name: "theme", Description: "The PHP theme whose definition to copy when the export holds several"},
|
{Name: "theme", Description: "The PHP theme whose definition to copy when the export holds several"},
|
||||||
{Name: "map", Description: "Rename an item type, old=new (repeatable)", Repeatable: true},
|
{Name: "map", Description: "Rename an item type, old=new (repeatable)", Repeatable: true},
|
||||||
{Name: "page-url", Description: "Copy a static or CMS page item as a url item, reference=/path (repeatable)", Repeatable: true},
|
{Name: "page-url", Description: "Copy a static or CMS page item as an address, reference=/path (repeatable)", Repeatable: true},
|
||||||
{Name: "force", Description: "Replace a definition that already has items", Bare: true},
|
{Name: "force", Description: "Replace additional addresses that are already stored", Bare: true},
|
||||||
{Name: "dry-run", Description: "Report what would be copied without writing", Bare: true},
|
{Name: "dry-run", Description: "Report what would be copied without writing", Bare: true},
|
||||||
},
|
},
|
||||||
Examples: []bonfire.Example{
|
Examples: []bonfire.Example{
|
||||||
{Command: "sitemap:import-winter --definitions definitions.jsonl --settings settings.json --dry-run", Description: "Show what would be kept, remapped and dropped, without writing"},
|
{Command: "sitemap:import-winter --definitions definitions.jsonl --settings settings.json --dry-run", Description: "Show what would be kept, remapped and dropped, without writing"},
|
||||||
{Command: "sitemap:import-winter --definitions definitions.jsonl --theme main --map blog-post=journal-post", Description: "Copy the main theme's definition, renaming an item type"},
|
{Command: "sitemap:import-winter --definitions definitions.jsonl --theme main", Description: "Copy the url items of the main theme's definition"},
|
||||||
{Command: "sitemap:import-winter --definitions definitions.jsonl --page-url about=/about --force", Description: "Replace the definition, turning the about page into a url item"},
|
{Command: "sitemap:import-winter --definitions definitions.jsonl --page-url about=/about --force", Description: "Replace the additional addresses, turning the about page into an address"},
|
||||||
},
|
},
|
||||||
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
|
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
|
||||||
maps, err := parseMaps(in.Flags("map"))
|
maps, err := parseMaps(in.Flags("map"))
|
||||||
@@ -128,11 +135,7 @@ copied." for the parts the export holds.`,
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer done()
|
defer done()
|
||||||
var reg *signpost.Registry
|
_, err = ImportWinterFiles(ctx, db, opts, out)
|
||||||
if app != nil {
|
|
||||||
reg, _ = app.Lookup[*signpost.Registry]()
|
|
||||||
}
|
|
||||||
_, err = ImportWinterFiles(ctx, db, reg, opts, out)
|
|
||||||
return err
|
return err
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
@@ -178,15 +181,14 @@ type winterDefinition struct {
|
|||||||
Data json.RawMessage `json:"data"`
|
Data json.RawMessage `json:"data"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// ImportWinterFiles runs sitemap:import-winter against db; reg is the menu
|
// ImportWinterFiles runs sitemap:import-winter against db.
|
||||||
// item type registry the item types are checked against (nil knows none).
|
func ImportWinterFiles(ctx context.Context, db *gorm.DB, opts WinterOptions, out bonfire.Output) (WinterReport, error) {
|
||||||
func ImportWinterFiles(ctx context.Context, db *gorm.DB, reg *signpost.Registry, opts WinterOptions, out bonfire.Output) (WinterReport, error) {
|
|
||||||
var report WinterReport
|
var report WinterReport
|
||||||
if opts.DefinitionsFile == "" && opts.SettingsFile == "" {
|
if opts.DefinitionsFile == "" && opts.SettingsFile == "" {
|
||||||
return report, errors.New("give --definitions, --settings or both")
|
return report, errors.New("give --definitions, --settings or both")
|
||||||
}
|
}
|
||||||
var (
|
var (
|
||||||
items []models.DefinitionItem
|
rows []models.ExtraURL
|
||||||
haveDef bool
|
haveDef bool
|
||||||
)
|
)
|
||||||
if opts.DefinitionsFile != "" {
|
if opts.DefinitionsFile != "" {
|
||||||
@@ -194,14 +196,14 @@ func ImportWinterFiles(ctx context.Context, db *gorm.DB, reg *signpost.Registry,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
out.Info(fmt.Sprintf("Copying definition %s (theme '%s') into the '%s' definition.", strings.TrimSpace(string(row.ID)), models.Text(row.Theme), models.DefinitionTheme))
|
out.Info(fmt.Sprintf("Copying the url items of definition %s (theme '%s') into the additional addresses.", strings.TrimSpace(string(row.ID)), models.Text(row.Theme)))
|
||||||
items, err = mapItems(ctx, reg, row.Data, opts.Maps, opts.PageURLs, &report)
|
rows, err = mapItems(row.Data, opts.Maps, opts.PageURLs, &report)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
haveDef = true
|
haveDef = true
|
||||||
}
|
}
|
||||||
var settings models.Settings
|
var settings winterSettings
|
||||||
if opts.SettingsFile != "" {
|
if opts.SettingsFile != "" {
|
||||||
var err error
|
var err error
|
||||||
settings, err = readWinterSettings(opts.SettingsFile, &report)
|
settings, err = readWinterSettings(opts.SettingsFile, &report)
|
||||||
@@ -214,12 +216,12 @@ func ImportWinterFiles(ctx context.Context, db *gorm.DB, reg *signpost.Registry,
|
|||||||
out.Warning(line)
|
out.Warning(line)
|
||||||
}
|
}
|
||||||
if haveDef {
|
if haveDef {
|
||||||
var existing []models.Definition
|
var existing models.Settings
|
||||||
if err := db.WithContext(ctx).Where("theme = ?", models.DefinitionTheme).Order("id ASC").Limit(1).Find(&existing).Error; err != nil {
|
if err := db.WithContext(ctx).Where("id = ?", 1).Limit(1).Find(&existing).Error; err != nil {
|
||||||
return report, err
|
return report, err
|
||||||
}
|
}
|
||||||
if len(existing) > 0 && len(existing[0].Items()) > 0 && !opts.Force {
|
if n := len(existing.Extra()); n > 0 && !opts.Force {
|
||||||
msg := fmt.Sprintf("The sitemap definition already has %d items; rerun with --force to replace them.", len(existing[0].Items()))
|
msg := fmt.Sprintf("The sitemap already has %d additional addresses; rerun with --force to replace them.", n)
|
||||||
if !opts.DryRun {
|
if !opts.DryRun {
|
||||||
return report, errors.New(msg)
|
return report, errors.New(msg)
|
||||||
}
|
}
|
||||||
@@ -238,19 +240,17 @@ func ImportWinterFiles(ctx context.Context, db *gorm.DB, reg *signpost.Registry,
|
|||||||
return report, nil
|
return report, nil
|
||||||
}
|
}
|
||||||
err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
err := db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
|
if _, err := loadSettingsForUpdate(tx); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
if haveDef {
|
if haveDef {
|
||||||
def, err := singletonDefinition(tx)
|
if err := saveExtra(tx, rows); err != nil {
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
def.SetItems(items)
|
|
||||||
if err := tx.Save(&def).Error; err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if report.Settings {
|
if report.Settings {
|
||||||
settings.ID = 1
|
if err := tx.Exec(`UPDATE golem15_sitemap_settings SET site_url = ?, default_locale = ? WHERE id = 1`,
|
||||||
if err := tx.Save(&settings).Error; err != nil {
|
nullable(settings.SiteURL), nullable(settings.DefaultLocale)).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -268,6 +268,14 @@ func ImportWinterFiles(ctx context.Context, db *gorm.DB, reg *signpost.Registry,
|
|||||||
return report, nil
|
return report, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// nullable is nil for "", else s.
|
||||||
|
func nullable(s string) any {
|
||||||
|
if s == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
// pickDefinition reads the definitions export and returns the row of theme,
|
// pickDefinition reads the definitions export and returns the row of theme,
|
||||||
// or the only row when theme is empty.
|
// or the only row when theme is empty.
|
||||||
func pickDefinition(file, theme string) (winterDefinition, error) {
|
func pickDefinition(file, theme string) (winterDefinition, error) {
|
||||||
@@ -316,150 +324,100 @@ func pickDefinition(file, theme string) (winterDefinition, error) {
|
|||||||
return rows[0], nil
|
return rows[0], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// exportedJSON is a JSON value that the export may hold as text (a TEXT
|
// mapItems decodes the exported data and keeps its url items as
|
||||||
// column selected as it is) or as JSON: a string is decoded once more.
|
// additional addresses.
|
||||||
func exportedJSON(raw json.RawMessage) json.RawMessage {
|
func mapItems(data json.RawMessage, maps, pageURLs map[string]string, report *WinterReport) ([]models.ExtraURL, error) {
|
||||||
raw = bytes.TrimSpace(raw)
|
items, labels, err := models.ParseLegacyItems(data)
|
||||||
if len(raw) > 0 && raw[0] == '"' {
|
if err != nil {
|
||||||
var text string
|
return nil, err
|
||||||
if json.Unmarshal(raw, &text) == nil {
|
}
|
||||||
return json.RawMessage(strings.TrimSpace(text))
|
out := []models.ExtraURL{}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
keep := func(label, u string) {
|
||||||
|
if seen[u] {
|
||||||
|
report.Lines = append(report.Lines, fmt.Sprintf("%s: dropped (address '%s' is already listed)", label, u))
|
||||||
|
report.Dropped++
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
seen[u] = true
|
||||||
|
out = append(out, models.ExtraURL{URL: u})
|
||||||
|
report.Kept++
|
||||||
}
|
}
|
||||||
return raw
|
for i, item := range items {
|
||||||
}
|
|
||||||
|
|
||||||
// mapItems decodes the exported data and maps its items.
|
|
||||||
func mapItems(ctx context.Context, reg *signpost.Registry, data json.RawMessage, maps, pageURLs map[string]string, report *WinterReport) ([]models.DefinitionItem, error) {
|
|
||||||
data = exportedJSON(data)
|
|
||||||
if len(data) == 0 || bytes.Equal(data, []byte("null")) {
|
|
||||||
return []models.DefinitionItem{}, nil
|
|
||||||
}
|
|
||||||
rawItems, labels, ok := orderedEntries(data)
|
|
||||||
if !ok {
|
|
||||||
return nil, errors.New("the definition data is not a list of items")
|
|
||||||
}
|
|
||||||
out := []models.DefinitionItem{}
|
|
||||||
refs := map[string][]string{}
|
|
||||||
for i, raw := range rawItems {
|
|
||||||
var item models.DefinitionItem
|
|
||||||
if err := json.Unmarshal(raw, &item); err != nil {
|
|
||||||
return nil, fmt.Errorf("definition item %s: %w", labels[i], err)
|
|
||||||
}
|
|
||||||
var fields map[string]any
|
|
||||||
_ = json.Unmarshal(raw, &fields)
|
|
||||||
label := describeItem(labels[i], item)
|
label := describeItem(labels[i], item)
|
||||||
if page, ok := fields["cmsPage"].(string); ok && page != "" {
|
if item.CMSPage != "" {
|
||||||
report.Lines = append(report.Lines, fmt.Sprintf("%s: cmsPage '%s' dropped (CMS pages are not supported)", label, page))
|
report.Lines = append(report.Lines, fmt.Sprintf("%s: cmsPage '%s' dropped (CMS pages are not supported)", label, item.CMSPage))
|
||||||
}
|
}
|
||||||
if p := models.Text(item.URLPattern); p != "" && !signpost.ValidItemPattern(p) {
|
if url, ok := pageURLs[item.Reference]; ok && droppedTypes[item.Type] {
|
||||||
report.Lines = append(report.Lines, fmt.Sprintf("%s: urlPattern '%s' cleared (not a path starting with a single /)", label, p))
|
if !models.AllowedAddress(url) {
|
||||||
item.URLPattern = nil
|
|
||||||
}
|
|
||||||
if url, ok := pageURLs[models.Text(item.Reference)]; ok && droppedTypes[item.Type] {
|
|
||||||
if !classes.AllowedItemURL(url) {
|
|
||||||
report.Lines = append(report.Lines, fmt.Sprintf("%s: dropped (--page-url '%s' is not a path or an http(s) URL)", label, url))
|
report.Lines = append(report.Lines, fmt.Sprintf("%s: dropped (--page-url '%s' is not a path or an http(s) URL)", label, url))
|
||||||
report.Dropped++
|
report.Dropped++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
report.Lines = append(report.Lines, fmt.Sprintf("%s: copied as type 'url' with url '%s'", label, url))
|
report.Lines = append(report.Lines, fmt.Sprintf("%s: copied as an additional address '%s'", label, url))
|
||||||
report.Remapped++
|
report.Remapped++
|
||||||
item.Type = models.ItemTypeURL
|
keep(label, url)
|
||||||
item.URL = &url
|
|
||||||
item.Reference = nil
|
|
||||||
out = append(out, item)
|
|
||||||
report.Kept++
|
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if to, ok := maps[item.Type]; ok && to != item.Type {
|
if to, ok := maps[item.Type]; ok && to != item.Type {
|
||||||
report.Lines = append(report.Lines, fmt.Sprintf("%s: type '%s' mapped to '%s'", label, item.Type, to))
|
report.Lines = append(report.Lines, fmt.Sprintf("%s: type '%s' mapped to '%s'", label, item.Type, to))
|
||||||
report.Remapped++
|
report.Remapped++
|
||||||
item.Type = to
|
item.Type = to
|
||||||
if to == "" {
|
|
||||||
report.Lines = append(report.Lines, fmt.Sprintf("%s: dropped (mapped to nothing)", label))
|
|
||||||
report.Dropped++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if item.Type == models.ItemTypeURL {
|
switch {
|
||||||
if !classes.AllowedItemURL(models.Text(item.URL)) {
|
case item.Type == models.LegacyItemURL:
|
||||||
|
if !models.AllowedAddress(item.URL) {
|
||||||
report.Lines = append(report.Lines, fmt.Sprintf("%s: dropped (the url is not a path or an http(s) URL)", label))
|
report.Lines = append(report.Lines, fmt.Sprintf("%s: dropped (the url is not a path or an http(s) URL)", label))
|
||||||
report.Dropped++
|
report.Dropped++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
out = append(out, item)
|
keep(label, item.URL)
|
||||||
report.Kept++
|
case item.Type == "":
|
||||||
continue
|
report.Lines = append(report.Lines, fmt.Sprintf("%s: dropped (mapped to nothing)", label))
|
||||||
}
|
report.Dropped++
|
||||||
if droppedTypes[item.Type] {
|
case droppedTypes[item.Type]:
|
||||||
report.Lines = append(report.Lines, fmt.Sprintf("%s: dropped (static and CMS page types are not supported)", label))
|
report.Lines = append(report.Lines, fmt.Sprintf("%s: dropped (static and CMS page types are not supported)", label))
|
||||||
report.Dropped++
|
report.Dropped++
|
||||||
continue
|
default:
|
||||||
}
|
report.Lines = append(report.Lines, fmt.Sprintf("%s: dropped (the content types list their records themselves)", label))
|
||||||
if _, known := reg.Type(item.Type); !known {
|
|
||||||
report.Lines = append(report.Lines, fmt.Sprintf("%s: dropped (type '%s' is not registered; map it with --map %s=<type>)", label, item.Type, item.Type))
|
|
||||||
report.Dropped++
|
report.Dropped++
|
||||||
continue
|
|
||||||
}
|
}
|
||||||
values, cached := refs[item.Type]
|
|
||||||
if !cached {
|
|
||||||
set, err := signpost.ReferenceOptions(ctx, reg, item.Type)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if set.Applies {
|
|
||||||
values = []string{}
|
|
||||||
for _, o := range set.Options {
|
|
||||||
values = append(values, o.Value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
refs[item.Type] = values
|
|
||||||
}
|
|
||||||
if values != nil && !slices.Contains(values, models.Text(item.Reference)) {
|
|
||||||
report.Lines = append(report.Lines, fmt.Sprintf("%s: dropped (reference '%s' is not among the current references of '%s')", label, models.Text(item.Reference), item.Type))
|
|
||||||
report.Dropped++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
out = append(out, item)
|
|
||||||
report.Kept++
|
|
||||||
}
|
}
|
||||||
return out, nil
|
return out, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func describeItem(label string, item models.DefinitionItem) string {
|
func describeItem(label string, item models.LegacyItem) string {
|
||||||
s := fmt.Sprintf("item %s (type '%s'", label, item.Type)
|
s := fmt.Sprintf("item %s (type '%s'", label, item.Type)
|
||||||
if item.URL != nil && *item.URL != "" {
|
if item.URL != "" {
|
||||||
s += fmt.Sprintf(", url '%s'", *item.URL)
|
s += fmt.Sprintf(", url '%s'", item.URL)
|
||||||
}
|
}
|
||||||
if item.Reference != nil && *item.Reference != "" {
|
if item.Reference != "" {
|
||||||
s += fmt.Sprintf(", reference '%s'", *item.Reference)
|
s += fmt.Sprintf(", reference '%s'", item.Reference)
|
||||||
}
|
}
|
||||||
return s + ")"
|
return s + ")"
|
||||||
}
|
}
|
||||||
|
|
||||||
// readWinterSettings reads the exported settings object onto the PHP
|
// ignoredWinterSettings are the PHP settings of the PHP-parity format the
|
||||||
// defaults. A frontend_url that models.AllowedFrontendURL refuses is an
|
// per-type sitemap no longer reads.
|
||||||
// error; the value is quoted so its control characters are not printed raw.
|
var ignoredWinterSettings = map[string]bool{
|
||||||
func readWinterSettings(file string, report *WinterReport) (models.Settings, error) {
|
"updates_manifest_path": true, "enable_priority_tiers": true,
|
||||||
|
"priority_homepage": true, "priority_services": true, "priority_blog": true,
|
||||||
|
"priority_categories": true, "priority_legal": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
// readWinterSettings reads the exported settings object. A frontend_url
|
||||||
|
// that models.AllowedFrontendURL refuses is an error; the value is quoted so
|
||||||
|
// its control characters are not printed raw.
|
||||||
|
func readWinterSettings(file string, report *WinterReport) (winterSettings, error) {
|
||||||
raw, err := os.ReadFile(file)
|
raw, err := os.ReadFile(file)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return models.Settings{}, fmt.Errorf("File not found: %s", file)
|
return winterSettings{}, fmt.Errorf("File not found: %s", file)
|
||||||
}
|
}
|
||||||
var fields map[string]json.RawMessage
|
var fields map[string]json.RawMessage
|
||||||
if err := json.Unmarshal(exportedJSON(raw), &fields); err != nil {
|
if err := json.Unmarshal(models.LegacyJSON(raw), &fields); err != nil {
|
||||||
return models.Settings{}, fmt.Errorf("%s: the settings must be a JSON object: %w", file, err)
|
return winterSettings{}, fmt.Errorf("%s: the settings must be a JSON object: %w", file, err)
|
||||||
}
|
|
||||||
s := models.DefaultSettings()
|
|
||||||
texts := map[string]**string{
|
|
||||||
"frontend_url": &s.FrontendURL,
|
|
||||||
"frontend_default_locale": &s.FrontendDefaultLocale,
|
|
||||||
"updates_manifest_path": &s.UpdatesManifestPath,
|
|
||||||
models.PriorityHomepage: &s.PriorityHomepage,
|
|
||||||
models.PriorityServices: &s.PriorityServices,
|
|
||||||
models.PriorityBlog: &s.PriorityBlog,
|
|
||||||
models.PriorityCategories: &s.PriorityCategories,
|
|
||||||
models.PriorityLegal: &s.PriorityLegal,
|
|
||||||
}
|
}
|
||||||
|
var s winterSettings
|
||||||
keys := make([]string, 0, len(fields))
|
keys := make([]string, 0, len(fields))
|
||||||
for key := range fields {
|
for key := range fields {
|
||||||
keys = append(keys, key)
|
keys = append(keys, key)
|
||||||
@@ -467,22 +425,25 @@ func readWinterSettings(file string, report *WinterReport) (models.Settings, err
|
|||||||
sort.Strings(keys)
|
sort.Strings(keys)
|
||||||
for _, key := range keys {
|
for _, key := range keys {
|
||||||
value := fields[key]
|
value := fields[key]
|
||||||
if dest, ok := texts[key]; ok {
|
switch {
|
||||||
|
case key == "frontend_url" || key == "frontend_default_locale":
|
||||||
text, err := models.DecodeText(value)
|
text, err := models.DecodeText(value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return models.Settings{}, fmt.Errorf("%s: setting %s: %w", file, key, err)
|
return winterSettings{}, fmt.Errorf("%s: setting %s: %w", file, key, err)
|
||||||
}
|
}
|
||||||
*dest = text
|
if key == "frontend_url" {
|
||||||
continue
|
s.SiteURL = models.Text(text)
|
||||||
|
} else {
|
||||||
|
s.DefaultLocale = strings.TrimSpace(models.Text(text))
|
||||||
|
}
|
||||||
|
case ignoredWinterSettings[key]:
|
||||||
|
report.Lines = append(report.Lines, fmt.Sprintf("setting '%s' ignored (the per-type sitemaps do not use it)", key))
|
||||||
|
default:
|
||||||
|
report.Lines = append(report.Lines, fmt.Sprintf("setting '%s' ignored (not a sitemap setting of this port)", key))
|
||||||
}
|
}
|
||||||
if key == "enable_priority_tiers" {
|
|
||||||
s.EnablePriorityTiers = !phpEmpty(value)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
report.Lines = append(report.Lines, fmt.Sprintf("setting '%s' ignored (not a sitemap setting of this port)", key))
|
|
||||||
}
|
}
|
||||||
if url := models.Text(s.FrontendURL); !models.AllowedFrontendURL(url) {
|
if !models.AllowedFrontendURL(s.SiteURL) {
|
||||||
return models.Settings{}, fmt.Errorf("%s: setting frontend_url %q must be empty or an absolute http:// or https:// URL without whitespace, control characters, quotes or the characters <, > and &", file, url)
|
return winterSettings{}, fmt.Errorf("%s: setting frontend_url %q must be empty or an absolute http:// or https:// URL without whitespace, control characters, quotes or the characters <, > and &", file, s.SiteURL)
|
||||||
}
|
}
|
||||||
return s, nil
|
return s, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -50,7 +49,7 @@ func TestWinterSettingsFrontendURL(t *testing.T) {
|
|||||||
for _, dry := range []bool{false, true} {
|
for _, dry := range []bool{false, true} {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
out := bonfire.NewOutput(strings.NewReader(""), &buf, &buf)
|
out := bonfire.NewOutput(strings.NewReader(""), &buf, &buf)
|
||||||
report, err := ImportWinterFiles(context.Background(), nil, nil, WinterOptions{SettingsFile: file, DryRun: dry}, out)
|
report, err := ImportWinterFiles(context.Background(), nil, WinterOptions{SettingsFile: file, DryRun: dry}, out)
|
||||||
if err == nil || !strings.Contains(err.Error(), "setting frontend_url") {
|
if err == nil || !strings.Contains(err.Error(), "setting frontend_url") {
|
||||||
t.Errorf("ImportWinterFiles(%q, dry run %v) = %v, want an error naming setting frontend_url", value, dry, err)
|
t.Errorf("ImportWinterFiles(%q, dry run %v) = %v, want an error naming setting frontend_url", value, dry, err)
|
||||||
}
|
}
|
||||||
@@ -85,7 +84,7 @@ func TestWinterSettingsFrontendURL(t *testing.T) {
|
|||||||
t.Errorf("%s: readWinterSettings = %v", name, err)
|
t.Errorf("%s: readWinterSettings = %v", name, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if got := models.Text(s.FrontendURL); got != tc.want {
|
if got := s.SiteURL; got != tc.want {
|
||||||
t.Errorf("%s: frontend_url = %q, want %q", name, got, tc.want)
|
t.Errorf("%s: frontend_url = %q, want %q", name, got, tc.want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
59
console/rebuild.go
Normal file
59
console/rebuild.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
package console
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Rebuild is sitemap:rebuild [--queue]: it rebuilds the sitemap files now
|
||||||
|
// (classes.Rebuild), or with --queue dispatches the rebuild job for a
|
||||||
|
// worker. The scheduler runs it every night at 03:00.
|
||||||
|
func Rebuild(app *backpack.App) bonfire.Command {
|
||||||
|
return bonfire.Command{
|
||||||
|
Name: "sitemap:rebuild",
|
||||||
|
Description: "Rebuild the sitemap files from the content types and the additional addresses",
|
||||||
|
Long: `Reads the published records of every content type and the additional
|
||||||
|
addresses, writes them into the sitemap's address table and numbers the
|
||||||
|
files: existing addresses keep their files, new ones are appended, and only a
|
||||||
|
changed file size renumbers. It runs in this process and ends with
|
||||||
|
"Rebuilt the sitemaps: N addresses in N files (N added, N changed, N
|
||||||
|
removed)."
|
||||||
|
|
||||||
|
--queue dispatches the rebuild job instead, for a worker to run. The
|
||||||
|
scheduler runs this command every night at 03:00; record changes and a save
|
||||||
|
of the sitemap settings queue a rebuild too.`,
|
||||||
|
Flags: []bonfire.Flag{
|
||||||
|
{Name: "queue", Description: "Dispatch the rebuild job for a worker instead of rebuilding here", Bare: true},
|
||||||
|
},
|
||||||
|
Examples: []bonfire.Example{
|
||||||
|
{Command: "sitemap:rebuild", Description: "Rebuild the sitemap files now"},
|
||||||
|
{Command: "sitemap:rebuild --queue", Description: "Queue a rebuild for the worker"},
|
||||||
|
},
|
||||||
|
Run: func(ctx context.Context, in bonfire.Input, out bonfire.Output) error {
|
||||||
|
_, done, err := lookupDB(ctx, app)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer done()
|
||||||
|
if flagOn(in, "queue") {
|
||||||
|
id, err := classes.DispatchRebuild(ctx, app)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out.Success(fmt.Sprintf("Queued the sitemap rebuild (job %d).", id))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
res, err := classes.Rebuild(ctx, app)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
out.Success(fmt.Sprintf("Rebuilt the sitemaps: %d addresses in %d files (%d added, %d changed, %d removed).",
|
||||||
|
res.Listed, res.Files, len(res.Added), len(res.Changed), len(res.Removed)))
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
184
content_fixture_test.go
Normal file
184
content_fixture_test.go
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
package sitemap_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/party"
|
||||||
|
)
|
||||||
|
|
||||||
|
// contentPluginID is a fake content plugin with two content types whose
|
||||||
|
// records live in memory (contentStore), so a test sets exactly what the
|
||||||
|
// sitemap reads through signpost Records. It knows nothing about the
|
||||||
|
// sitemap plugin.
|
||||||
|
const contentPluginID = "acme.content"
|
||||||
|
|
||||||
|
// The fake content types: pages (/pages/<slug>, group pages) and offers
|
||||||
|
// (/offers/<slug>, group offers).
|
||||||
|
const (
|
||||||
|
pageType = "acme-page"
|
||||||
|
pageModel = "acme_pages"
|
||||||
|
offerType = "acme-offer"
|
||||||
|
offerModel = "acme_offers"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fakeRecord is one record of a fake content type. PublishedAt and Parents
|
||||||
|
// are the optional descriptor facts (the News sitemap, the HTML sitemap's
|
||||||
|
// tree).
|
||||||
|
type fakeRecord struct {
|
||||||
|
ID int
|
||||||
|
Published bool
|
||||||
|
LastMod time.Time
|
||||||
|
Locales []pact.ContentLocale
|
||||||
|
PublishedAt *time.Time
|
||||||
|
Parents []pact.ContentRef
|
||||||
|
}
|
||||||
|
|
||||||
|
// store holds the fake records per content type key.
|
||||||
|
type store struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
records map[string][]fakeRecord
|
||||||
|
}
|
||||||
|
|
||||||
|
var contentStore = &store{records: map[string][]fakeRecord{}}
|
||||||
|
|
||||||
|
// reset empties the store and clears it again when the test ends.
|
||||||
|
func (s *store) reset(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
s.mu.Lock()
|
||||||
|
s.records = map[string][]fakeRecord{}
|
||||||
|
s.mu.Unlock()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
s.mu.Lock()
|
||||||
|
s.records = map[string][]fakeRecord{}
|
||||||
|
s.mu.Unlock()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// put adds or replaces a record of typ.
|
||||||
|
func (s *store) put(typ string, rec fakeRecord) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
list := s.records[typ]
|
||||||
|
for i := range list {
|
||||||
|
if list[i].ID == rec.ID {
|
||||||
|
list[i] = rec
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.records[typ] = append(list, rec)
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove deletes a record of typ.
|
||||||
|
func (s *store) remove(typ string, id int) {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
s.records[typ] = slices.DeleteFunc(s.records[typ], func(r fakeRecord) bool { return r.ID == id })
|
||||||
|
}
|
||||||
|
|
||||||
|
// page answers one ContentList page of typ, by ascending ID.
|
||||||
|
func (s *store) page(typ string, in pact.ContentList) pact.ContentPage {
|
||||||
|
s.mu.Lock()
|
||||||
|
defer s.mu.Unlock()
|
||||||
|
list := slices.Clone(s.records[typ])
|
||||||
|
slices.SortFunc(list, func(a, b fakeRecord) int { return a.ID - b.ID })
|
||||||
|
after, _ := strconv.Atoi(in.After)
|
||||||
|
limit := in.Limit
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = 100
|
||||||
|
}
|
||||||
|
out := pact.ContentPage{Records: []pact.ContentRecord{}}
|
||||||
|
for _, r := range list {
|
||||||
|
if r.ID <= after {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if len(out.Records) == limit {
|
||||||
|
out.Next = strconv.Itoa(after)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
mod := r.LastMod
|
||||||
|
out.Records = append(out.Records, pact.ContentRecord{
|
||||||
|
ID: strconv.Itoa(r.ID),
|
||||||
|
Published: r.Published,
|
||||||
|
LastMod: &mod,
|
||||||
|
Locales: slices.Clone(r.Locales),
|
||||||
|
PublishedAt: r.PublishedAt,
|
||||||
|
Parents: slices.Clone(r.Parents),
|
||||||
|
})
|
||||||
|
after = r.ID
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// contentPlugin is acme.content.
|
||||||
|
type contentPlugin struct{}
|
||||||
|
|
||||||
|
func (contentPlugin) ID() string { return contentPluginID }
|
||||||
|
func (contentPlugin) Requires() []string { return nil }
|
||||||
|
func (contentPlugin) Register(*backpack.App) error { return nil }
|
||||||
|
func (contentPlugin) Boot(*backpack.App) error { return nil }
|
||||||
|
|
||||||
|
func (contentPlugin) MenuItemTypes() []pact.MenuItemType {
|
||||||
|
typ := func(key, label, model, pattern string) pact.MenuItemType {
|
||||||
|
return pact.MenuItemType{
|
||||||
|
Key: key,
|
||||||
|
Label: label,
|
||||||
|
DefaultPattern: pattern,
|
||||||
|
Placeholders: []string{"slug"},
|
||||||
|
Resolve: func(context.Context, pact.MenuItemResolve) (*pact.ResolvedMenuItem, error) {
|
||||||
|
return nil, nil
|
||||||
|
},
|
||||||
|
Content: &pact.ContentDescriptor{
|
||||||
|
Model: model,
|
||||||
|
Records: func(_ context.Context, in pact.ContentList) (pact.ContentPage, error) {
|
||||||
|
return contentStore.page(key, in), nil
|
||||||
|
},
|
||||||
|
Describe: func(context.Context, pact.ContentDescribe) (*pact.ContentRecord, error) {
|
||||||
|
return nil, nil
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return []pact.MenuItemType{
|
||||||
|
typ(pageType, "Pages", pageModel, "/pages/:slug"),
|
||||||
|
typ(offerType, "Offers", offerModel, "/offers/:slug"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ pact.HasMenuItemTypes = contentPlugin{}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
party.Register(contentPlugin{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// page1 is a published record in one locale at /pages/<slug>.
|
||||||
|
func page1(id int, slug string, mod time.Time) fakeRecord {
|
||||||
|
return fakeRecord{ID: id, Published: true, LastMod: mod, Locales: []pact.ContentLocale{{Locale: "en", URL: "/pages/" + slug, Title: "Page " + slug}}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// deleteRecord removes a record of typ from the store and fires
|
||||||
|
// pact.RecordDeleted for its model, as the admin does after a delete.
|
||||||
|
func (e *sitemapEnv) deleteRecord(t *testing.T, typ, model string, id int) {
|
||||||
|
t.Helper()
|
||||||
|
contentStore.remove(typ, id)
|
||||||
|
if err := e.app.Events.Fire(context.Background(), &pact.RecordDeleted{Model: model, ID: strconv.Itoa(id)}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// editRecord replaces a record of typ in the store and fires
|
||||||
|
// pact.RecordSaved for its model with the changed attributes, as the admin
|
||||||
|
// does after a save.
|
||||||
|
func (e *sitemapEnv) editRecord(t *testing.T, typ, model string, rec fakeRecord, changes ...pact.RecordChange) {
|
||||||
|
t.Helper()
|
||||||
|
contentStore.put(typ, rec)
|
||||||
|
if err := e.app.Events.Fire(context.Background(), &pact.RecordSaved{Model: model, ID: strconv.Itoa(rec.ID), Changes: changes}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
165
contract/contract.go
Normal file
165
contract/contract.go
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
// Package contract is the published seam of the golem15.sitemap plugin:
|
||||||
|
// the Filter another plugin implements to keep addresses out of the
|
||||||
|
// sitemaps or move them to another file group, and the Listing other
|
||||||
|
// plugins read to show the sitemap's addresses (an HTML sitemap, IndexNow).
|
||||||
|
//
|
||||||
|
// It is a package of its own so a plugin can import it without importing
|
||||||
|
// the sitemap plugin's root package, whose init registers the plugin. The
|
||||||
|
// sitemap plugin depends on no implementation: it looks a Filter up with
|
||||||
|
//
|
||||||
|
// f, ok := app.Lookup[contract.Filter]()
|
||||||
|
//
|
||||||
|
// and includes every published address when none is published. A plugin
|
||||||
|
// publishes one in its Register:
|
||||||
|
//
|
||||||
|
// app.Publish[contract.Filter](myFilter{})
|
||||||
|
package contract
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The reasons a Decision may give for leaving an address out. The sitemap
|
||||||
|
// counts excluded addresses by reason; another reason is counted under its
|
||||||
|
// own name.
|
||||||
|
const (
|
||||||
|
// ReasonNoindex is an address whose page is set to noindex.
|
||||||
|
ReasonNoindex = "noindex"
|
||||||
|
// ReasonCanonical is an address whose canonical URL points elsewhere.
|
||||||
|
ReasonCanonical = "canonical"
|
||||||
|
// ReasonRedirect is an address that redirects.
|
||||||
|
ReasonRedirect = "redirect"
|
||||||
|
// ReasonType is an address of a content type switched off in the
|
||||||
|
// sitemap settings; the sitemap sets it itself, a Filter need not.
|
||||||
|
ReasonType = "type"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Candidate is one address the sitemap would list: TypeKey is the content
|
||||||
|
// type key (a signpost menu item type, or "extra" for an additional address
|
||||||
|
// of the settings), RecordID the record's ID within it (for an additional
|
||||||
|
// address the hex SHA-256 of its path), Locale the locale ("" when the
|
||||||
|
// address has none) and URL its public path or absolute URL.
|
||||||
|
type Candidate struct {
|
||||||
|
TypeKey string
|
||||||
|
RecordID string
|
||||||
|
Locale string
|
||||||
|
URL string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decision is a Filter's answer for one Candidate. Exclude leaves the
|
||||||
|
// address out of the sitemap files, counted under Reason. Group, when not
|
||||||
|
// empty, puts the address in another file group: the files are then named
|
||||||
|
// sitemap-<group>-<n>.xml, so a Group must use lowercase letters, digits and
|
||||||
|
// hyphens (another value is ignored). LastMod, when set, is the first
|
||||||
|
// lastmod of an address the sitemap has not listed before; it never moves
|
||||||
|
// the lastmod of a listed address.
|
||||||
|
type Decision struct {
|
||||||
|
Exclude bool
|
||||||
|
Reason string
|
||||||
|
Group string
|
||||||
|
LastMod *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Group names a file group a Filter's decisions use: Key is the group as
|
||||||
|
// in Decision.Group, Titles its heading per locale for an HTML sitemap.
|
||||||
|
type Group struct {
|
||||||
|
Key string
|
||||||
|
Titles map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filter decides which addresses the sitemap lists. Decide receives one
|
||||||
|
// batch (a page of records of one content type, or the additional
|
||||||
|
// addresses) and answers one Decision per Candidate in the same order; an
|
||||||
|
// answer of another length or an error fails the rebuild, which keeps the
|
||||||
|
// files it served before. Groups lists the groups the Filter's decisions
|
||||||
|
// may name, with their titles.
|
||||||
|
type Filter interface {
|
||||||
|
Decide(ctx context.Context, batch []Candidate) ([]Decision, error)
|
||||||
|
Groups(ctx context.Context) ([]Group, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rebuilder asks the sitemap for a rebuild. RequestRebuild queues one
|
||||||
|
// debounced rebuild, the same one a record event queues: a request inside
|
||||||
|
// the debounce window joins the rebuild already queued. Another plugin
|
||||||
|
// calls it when something its Filter reads has changed (the SEO plugin's
|
||||||
|
// noindex paths). The sitemap plugin publishes it with
|
||||||
|
// app.Publish[contract.Rebuilder] in its Register; a plugin that finds none
|
||||||
|
// published (an older sitemap plugin) leaves the change to the next
|
||||||
|
// scheduled rebuild.
|
||||||
|
type Rebuilder interface {
|
||||||
|
RequestRebuild(ctx context.Context) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Listing is what the sitemap publishes for other plugins: its settings and
|
||||||
|
// the listed addresses of each group. The sitemap plugin publishes it with
|
||||||
|
// app.Publish[contract.Listing] in its Register.
|
||||||
|
type Listing interface {
|
||||||
|
Settings(ctx context.Context) (ListingSettings, error)
|
||||||
|
Entries(ctx context.Context, q EntriesQuery) (EntriesPage, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListingSettings are the sitemap's settings as other plugins need them.
|
||||||
|
// SiteURL is the absolute site address every address starts with ("" when
|
||||||
|
// none is configured), IndexURL the absolute address of the sitemap index,
|
||||||
|
// DefaultLocale the site's default locale ("" when not set) and Groups the
|
||||||
|
// file groups with listed addresses. HTMLEnabled, HTMLPaths (locale to
|
||||||
|
// path) and HTMLPageSize are the HTML sitemap's settings (the sitemap
|
||||||
|
// serves its data at /_sitemap/api/v1/html); KeyFile is the IndexNow key
|
||||||
|
// file name (<key>.txt, served at /_sitemap/indexnow/<key>.txt for the
|
||||||
|
// site root), "" while IndexNow is off. TypesOff lists the content types
|
||||||
|
// (signpost keys) switched off in the sitemap settings, whose addresses
|
||||||
|
// are left out with ReasonType.
|
||||||
|
type ListingSettings struct {
|
||||||
|
SiteURL string
|
||||||
|
IndexURL string
|
||||||
|
DefaultLocale string
|
||||||
|
Groups []GroupInfo
|
||||||
|
HTMLEnabled bool
|
||||||
|
HTMLPaths map[string]string
|
||||||
|
HTMLPageSize int
|
||||||
|
KeyFile string
|
||||||
|
TypesOff []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// GroupInfo is one file group: Key is the group (as Entries takes it), Slug
|
||||||
|
// the name part of its files (sitemap-<slug>-<n>.xml; today the same as
|
||||||
|
// Key), Titles its heading per locale and Count its listed addresses.
|
||||||
|
type GroupInfo struct {
|
||||||
|
Key string
|
||||||
|
Slug string
|
||||||
|
Titles map[string]string
|
||||||
|
Count int
|
||||||
|
}
|
||||||
|
|
||||||
|
// EntriesQuery asks for one page of a group's listed addresses. Locale,
|
||||||
|
// when set, keeps the addresses of that locale and those without one.
|
||||||
|
// After is the Next of the previous page ("" for the first) and Limit the
|
||||||
|
// page size (at most 1000; 0 means 100).
|
||||||
|
type EntriesQuery struct {
|
||||||
|
Group string
|
||||||
|
Locale string
|
||||||
|
After string
|
||||||
|
Limit int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entry is one listed address. URL is absolute (on ListingSettings.SiteURL)
|
||||||
|
// and LastMod its last real change, nil when unknown.
|
||||||
|
type Entry struct {
|
||||||
|
Group string
|
||||||
|
TypeKey string
|
||||||
|
RecordID string
|
||||||
|
Locale string
|
||||||
|
URL string
|
||||||
|
Title string
|
||||||
|
LastMod *time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// EntriesPage is one page of Entries in a stable order: Next is the After
|
||||||
|
// of the following page ("" on the last page) and Total the number of
|
||||||
|
// addresses the query matches across all pages.
|
||||||
|
type EntriesPage struct {
|
||||||
|
Entries []Entry
|
||||||
|
Next string
|
||||||
|
Total int
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
// Package controllers holds the sitemap plugin's admin controllers: the
|
||||||
|
// settings singleton.
|
||||||
package controllers
|
package controllers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -10,6 +12,6 @@ import (
|
|||||||
// a database handle or registry of its own.
|
// a database handle or registry of its own.
|
||||||
func AdminControllers(app func() *backpack.App) []pact.AdminController {
|
func AdminControllers(app func() *backpack.App) []pact.AdminController {
|
||||||
return []pact.AdminController{
|
return []pact.AdminController{
|
||||||
definitionsAdminController{app: app},
|
settingsAdminController{app: app},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
129
controllers/api/auth.go
Normal file
129
controllers/api/auth.go
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/controllers"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/wire"
|
||||||
|
)
|
||||||
|
|
||||||
|
// PermissionManage is the permission every management route requires: the
|
||||||
|
// sitemap settings permission of the admin screen.
|
||||||
|
const PermissionManage = controllers.PermissionAccessDefinitions
|
||||||
|
|
||||||
|
// tokenCover is the scope a personal API token must cover.
|
||||||
|
const tokenCover = "golem15.sitemap.*"
|
||||||
|
|
||||||
|
// maxBody caps a management request body.
|
||||||
|
const maxBody = 1 << 20
|
||||||
|
|
||||||
|
// The answers of the management API.
|
||||||
|
const (
|
||||||
|
errAuthenticationRequired = "Authentication required"
|
||||||
|
errInsufficientPerms = "Insufficient permissions"
|
||||||
|
errInternal = "Internal Server Error"
|
||||||
|
errInvalidBody = "The request body is invalid."
|
||||||
|
)
|
||||||
|
|
||||||
|
// ProblemsError is a refused write: phrase keys by field.
|
||||||
|
type ProblemsError struct {
|
||||||
|
Problems map[string][]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *ProblemsError) Error() string { return "golem15.sitemap: validation failed" }
|
||||||
|
|
||||||
|
// apiError is an error a handler answers with its own status and body.
|
||||||
|
type apiError struct {
|
||||||
|
Status int
|
||||||
|
Body any
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *apiError) Error() string { return http.StatusText(e.Status) }
|
||||||
|
|
||||||
|
// handler is a management endpoint: it returns the status and the body to
|
||||||
|
// answer, or an error the wrapper maps.
|
||||||
|
type handler func(ctx context.Context, app *backpack.App, r *http.Request) (int, any, error)
|
||||||
|
|
||||||
|
// manage wraps a management endpoint (D-10): it resolves the backend
|
||||||
|
// administrator from a backend JWT, a personal API token (covering
|
||||||
|
// golem15.sitemap.*) or the in-process MCP dispatch marker
|
||||||
|
// (cabana.ResolveBackend, so an MCP call runs as the linked
|
||||||
|
// administrator), refuses 401 without one and 403 without the sitemap
|
||||||
|
// permission, and answers a refused write 422
|
||||||
|
// {"error":"validation_failed","errors":{field:[message]}} in the request
|
||||||
|
// locale. Every answer carries X-Robots-Tag: noindex.
|
||||||
|
func manage(app func() *backpack.App, h handler) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("X-Robots-Tag", "noindex")
|
||||||
|
a := app()
|
||||||
|
if a == nil {
|
||||||
|
wire.WriteJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "The sitemap is not available"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out, principal, err := cabana.ResolveBackend(a, r, tokenCover)
|
||||||
|
if err != nil || principal == nil {
|
||||||
|
if errors.Is(err, cabana.ErrTokenScope) {
|
||||||
|
wire.WriteJSON(w, http.StatusForbidden, map[string]string{"error": errInsufficientPerms})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wire.WriteJSON(w, http.StatusUnauthorized, map[string]string{"error": errAuthenticationRequired})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !cabana.Allows(principal, []string{PermissionManage}) {
|
||||||
|
wire.WriteJSON(w, http.StatusForbidden, map[string]string{"error": errInsufficientPerms})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
status, body, err := h(out.Context(), a, out)
|
||||||
|
if err != nil {
|
||||||
|
writeError(w, out.Context(), a, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wire.WriteJSON(w, status, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeError maps a handler error to its answer.
|
||||||
|
func writeError(w http.ResponseWriter, ctx context.Context, app *backpack.App, err error) {
|
||||||
|
var api *apiError
|
||||||
|
var problems *ProblemsError
|
||||||
|
switch {
|
||||||
|
case errors.As(err, &api):
|
||||||
|
wire.WriteJSON(w, api.Status, api.Body)
|
||||||
|
case errors.As(err, &problems):
|
||||||
|
tr, _ := app.Lookup[*phrasebook.Translator]()
|
||||||
|
messages := map[string][]string{}
|
||||||
|
for field, keys := range problems.Problems {
|
||||||
|
for _, key := range keys {
|
||||||
|
messages[field] = append(messages[field], controllers.Phrase(ctx, tr, key, nil))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wire.WriteJSON(w, http.StatusUnprocessableEntity, map[string]any{"error": "validation_failed", "errors": messages})
|
||||||
|
default:
|
||||||
|
log.Error("golem15.sitemap: management API", "error", err)
|
||||||
|
wire.WriteJSON(w, http.StatusInternalServerError, map[string]any{"error": errInternal})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// decode reads a JSON body of at most maxBody bytes into v; an empty body
|
||||||
|
// leaves v as it is.
|
||||||
|
func decode(r *http.Request, v any) error {
|
||||||
|
if r.Body == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
dec := json.NewDecoder(io.LimitReader(r.Body, maxBody+1))
|
||||||
|
dec.DisallowUnknownFields()
|
||||||
|
if err := dec.Decode(v); err != nil {
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &apiError{Status: http.StatusUnprocessableEntity, Body: map[string]any{"error": errInvalidBody}}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
116
controllers/api/html.go
Normal file
116
controllers/api/html.go
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/wire"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GroupPattern is the {group} constraint of the HTML sitemap group route:
|
||||||
|
// a file group slug.
|
||||||
|
const GroupPattern = `[a-z0-9][a-z0-9-]{0,63}`
|
||||||
|
|
||||||
|
// localePattern is the form a locale query value must have.
|
||||||
|
var localePattern = regexp.MustCompile(`^[a-z]{2,3}([-_][A-Za-z0-9]{2,8})*$`)
|
||||||
|
|
||||||
|
// pagePattern is the form of the page query value: 1 to 6 digits.
|
||||||
|
var pagePattern = regexp.MustCompile(`^[0-9]{1,6}$`)
|
||||||
|
|
||||||
|
// htmlRequest checks the shared parts of an HTML sitemap request and
|
||||||
|
// returns the settings and database, or answers 404 (the HTML sitemap is
|
||||||
|
// off, a malformed locale) or 500 itself.
|
||||||
|
func htmlRequest(app func() *backpack.App, w http.ResponseWriter, r *http.Request) (classes.HTMLSitemap, bool) {
|
||||||
|
w.Header().Set("X-Robots-Tag", "noindex")
|
||||||
|
w.Header().Set("Cache-Control", "no-cache, private")
|
||||||
|
a := app()
|
||||||
|
if a == nil {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return classes.HTMLSitemap{}, false
|
||||||
|
}
|
||||||
|
if loc := r.URL.Query().Get("locale"); loc != "" && !localePattern.MatchString(loc) {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return classes.HTMLSitemap{}, false
|
||||||
|
}
|
||||||
|
db, ok := a.Lookup[*gorm.DB]()
|
||||||
|
if !ok || db == nil {
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return classes.HTMLSitemap{}, false
|
||||||
|
}
|
||||||
|
return classes.HTMLSitemap{App: a, DB: db.WithContext(r.Context())}, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTMLOverview serves GET /_sitemap/api/v1/html?locale=: the HTML sitemap
|
||||||
|
// overview (D-34; classes.HTMLSitemap.Overview). It lists exactly the
|
||||||
|
// addresses of the XML sitemaps and answers 404 while the HTML sitemap is
|
||||||
|
// off. Every answer carries X-Robots-Tag: noindex.
|
||||||
|
func HTMLOverview(app func() *backpack.App) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h, ok := htmlRequest(app, w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
settings, err := classes.LoadSettings(h.DB)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !settings.HTMLEnabled {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out, err := h.Overview(r.Context(), settings, r.URL.Query().Get("locale"))
|
||||||
|
if err != nil {
|
||||||
|
log.Error("golem15.sitemap: html overview", "error", err)
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wire.WriteJSON(w, http.StatusOK, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTMLGroup serves GET /_sitemap/api/v1/html/{group}?locale=&page=: one
|
||||||
|
// page (from 1, the default) of a group (classes.HTMLSitemap.Group). An
|
||||||
|
// unknown group, a page past the last, a malformed page or the HTML
|
||||||
|
// sitemap off answer 404.
|
||||||
|
func HTMLGroup(app func() *backpack.App) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h, ok := htmlRequest(app, w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page := 1
|
||||||
|
if raw := r.URL.Query().Get("page"); raw != "" {
|
||||||
|
n, err := strconv.Atoi(raw)
|
||||||
|
if !pagePattern.MatchString(raw) || err != nil || n < 1 {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
page = n
|
||||||
|
}
|
||||||
|
settings, err := classes.LoadSettings(h.DB)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !settings.HTMLEnabled {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
out, found, err := h.Group(r.Context(), settings, r.URL.Query().Get("locale"), r.PathValue("group"), page)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("golem15.sitemap: html group", "error", err)
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
wire.WriteJSON(w, http.StatusOK, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
49
controllers/api/indexnow.go
Normal file
49
controllers/api/indexnow.go
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
// Package api holds the sitemap plugin's HTTP handlers outside the admin:
|
||||||
|
// the IndexNow key file, the HTML sitemap API and the management API.
|
||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// KeyFilePattern is the {file} constraint of the key file route: an
|
||||||
|
// IndexNow key file name, <key>.txt.
|
||||||
|
const KeyFilePattern = `[A-Za-z0-9-]{8,128}\.txt`
|
||||||
|
|
||||||
|
// KeyFile serves GET /_sitemap/indexnow/{file}: the IndexNow key as
|
||||||
|
// text/plain when IndexNow is on and file is <key>.txt; any other name, a
|
||||||
|
// replaced key or IndexNow off answers 404 (D-31). The SEO layer serves it
|
||||||
|
// at the site root.
|
||||||
|
func KeyFile(app func() *backpack.App) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
a := app()
|
||||||
|
if a == nil {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db, ok := a.Lookup[*gorm.DB]()
|
||||||
|
if !ok || db == nil {
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
settings, err := classes.LoadSettings(db.WithContext(r.Context()))
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
key := classes.ActiveKey(settings)
|
||||||
|
if key == "" || r.PathValue("file") != classes.KeyFileName(key) {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-cache, private")
|
||||||
|
w.Header().Set("X-Robots-Tag", "noindex")
|
||||||
|
w.WriteHeader(http.StatusOK)
|
||||||
|
_, _ = w.Write([]byte(key))
|
||||||
|
}
|
||||||
|
}
|
||||||
7
controllers/api/logger.go
Normal file
7
controllers/api/logger.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import "git.golem15.com/golem15/summercms/modules/diary"
|
||||||
|
|
||||||
|
// log is the handlers' logger: its records carry component=sitemap, like
|
||||||
|
// the rest of the plugin (log.components.sitemap).
|
||||||
|
var log = diary.For("sitemap")
|
||||||
350
controllers/api/settings.go
Normal file
350
controllers/api/settings.go
Normal file
@@ -0,0 +1,350 @@
|
|||||||
|
package api
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/signpost"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// errUnknownType is the refusal of a types entry for a key no content type
|
||||||
|
// has.
|
||||||
|
const errUnknownType = "golem15.sitemap::lang.errors.type_unknown"
|
||||||
|
|
||||||
|
// TypeInput is the settings of one content type in UpdateSettingsInput:
|
||||||
|
// only the fields sent change.
|
||||||
|
type TypeInput struct {
|
||||||
|
Include *bool `json:"include,omitempty" jsonschema:"list the type's records in the sitemaps"`
|
||||||
|
Slug *string `json:"slug,omitempty" jsonschema:"the file name part of the type's files (sitemap-<slug>-<n>.xml): lowercase letters, digits and hyphens; empty for the default"`
|
||||||
|
Titles map[string]string `json:"titles,omitempty" jsonschema:"the type's heading in the HTML sitemap per locale"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateSettingsInput is the body of PUT /_sitemap/api/v1/settings: only
|
||||||
|
// the fields sent change, with the checks of the settings screen.
|
||||||
|
type UpdateSettingsInput struct {
|
||||||
|
SiteURL *string `json:"site_url,omitempty" jsonschema:"the public site address every sitemap address starts with, e.g. https://www.example.com; empty for the config value"`
|
||||||
|
FileSize *int `json:"file_size,omitempty" jsonschema:"addresses per sitemap file, 1 to 50000; a change renumbers every file"`
|
||||||
|
ExtraURLs *[]models.ExtraURL `json:"extra_urls,omitempty" jsonschema:"the additional addresses (url: a path or an absolute URL on the site; lastmod: optional YYYY-MM-DD); replaces the list"`
|
||||||
|
ImagesEnabled *bool `json:"images_enabled,omitempty" jsonschema:"list the pages' images in the sitemap-images files"`
|
||||||
|
NewsEnabled *bool `json:"news_enabled,omitempty" jsonschema:"serve the Google News sitemap sitemap-news.xml (only for sites accepted in Google News)"`
|
||||||
|
NewsPublication *string `json:"news_publication,omitempty" jsonschema:"the publication name as registered in Google News; empty for the site name"`
|
||||||
|
NewsSources *[]string `json:"news_sources,omitempty" jsonschema:"the article types and categories of the News sitemap, values of news_source_options (type:<key> or category:<key>:<id>); empty for every article type"`
|
||||||
|
IndexNowEnabled *bool `json:"indexnow_enabled,omitempty" jsonschema:"notify IndexNow engines of new, changed and removed addresses after each rebuild (production only); turning it on generates the key"`
|
||||||
|
IndexNowNewKey *bool `json:"indexnow_new_key,omitempty" jsonschema:"generate a new IndexNow key; the old key file stops working at once"`
|
||||||
|
HTMLEnabled *bool `json:"html_enabled,omitempty" jsonschema:"serve the HTML sitemap's data to the site"`
|
||||||
|
HTMLPaths map[string]string `json:"html_paths,omitempty" jsonschema:"the site's HTML sitemap address per locale, e.g. {\"pl\":\"/mapa-strony\"}; a blank value removes the locale"`
|
||||||
|
HTMLPageSize *int `json:"html_page_size,omitempty" jsonschema:"links per HTML sitemap page, 50 to 500"`
|
||||||
|
Types map[string]TypeInput `json:"types,omitempty" jsonschema:"content type settings by type key"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// settingsValues is the settings part of an answer.
|
||||||
|
func settingsValues(s models.Settings) map[string]any {
|
||||||
|
return map[string]any{
|
||||||
|
"site_url": models.Text(s.SiteURL),
|
||||||
|
"file_size": s.EffectiveFileSize(),
|
||||||
|
"default_locale": models.Text(s.DefaultLocale),
|
||||||
|
"extra_urls": nonNil(s.Extra()),
|
||||||
|
"images_enabled": s.ImagesEnabled,
|
||||||
|
"news_enabled": s.NewsEnabled,
|
||||||
|
"news_publication": models.Text(s.NewsPublication),
|
||||||
|
"news_sources": nonNil(s.Sources()),
|
||||||
|
"indexnow_enabled": s.IndexNowEnabled,
|
||||||
|
"html_enabled": s.HTMLEnabled,
|
||||||
|
"html_paths": s.EffectiveHTMLPaths(),
|
||||||
|
"html_page_size": s.EffectiveHTMLPageSize(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func nonNil[T any](s []T) []T {
|
||||||
|
if s == nil {
|
||||||
|
return []T{}
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// fileJSON is one file in an answer, with its public address.
|
||||||
|
type fileJSON struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
Count int `json:"count"`
|
||||||
|
LastMod *time.Time `json:"lastmod"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// settingsBody is the answer of the settings routes: the settings, the
|
||||||
|
// content types (label and settings by key), the files of the index, the
|
||||||
|
// addresses left out by reason, the rebuild state, the IndexNow state and
|
||||||
|
// the values news_sources takes.
|
||||||
|
func settingsBody(ctx context.Context, app *backpack.App, db *gorm.DB) (map[string]any, error) {
|
||||||
|
s, err := classes.LoadSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
site := classes.SiteURL(app, s)
|
||||||
|
reg, _ := app.Lookup[*signpost.Registry]()
|
||||||
|
tr, _ := app.Lookup[*phrasebook.Translator]()
|
||||||
|
types := map[string]any{}
|
||||||
|
if reg != nil {
|
||||||
|
rows, err := classes.LoadTypeSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, typ := range reg.ContentTypes() {
|
||||||
|
cfg := classes.EffectiveType(typ, rows)
|
||||||
|
label := typ.Label
|
||||||
|
if tr != nil {
|
||||||
|
label = tr.Get(ctx, typ.Label, nil)
|
||||||
|
}
|
||||||
|
titles := cfg.Titles
|
||||||
|
if titles == nil {
|
||||||
|
titles = map[string]string{}
|
||||||
|
}
|
||||||
|
types[typ.Key] = map[string]any{"label": label, "include": cfg.Include, "slug": cfg.Slug, "titles": titles}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
list, err := classes.SitemapFiles(db, app, s, time.Now().UTC())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
files := make([]fileJSON, 0, len(list))
|
||||||
|
for _, f := range list {
|
||||||
|
files = append(files, fileJSON{Name: f.Name, URL: site + "/" + f.Name, Count: f.Count, LastMod: f.LastMod})
|
||||||
|
}
|
||||||
|
leftOut, err := classes.LeftOut(db)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sources, err := classes.NewsSources(db, reg, models.Text(s.DefaultLocale))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
index := ""
|
||||||
|
if site != "" {
|
||||||
|
index = site + "/sitemap.xml"
|
||||||
|
}
|
||||||
|
return map[string]any{
|
||||||
|
"settings": settingsValues(s),
|
||||||
|
"types": types,
|
||||||
|
"index_url": index,
|
||||||
|
"files": files,
|
||||||
|
"left_out": leftOut,
|
||||||
|
"built_at": s.BuiltAt,
|
||||||
|
"building": classes.Building(s.RebuildRequestedAt, s.BuiltAt, time.Now()),
|
||||||
|
"indexnow": classes.LoadIndexNowStatus(db, app, s),
|
||||||
|
"news_source_options": sources,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// database returns the application's database bound to ctx.
|
||||||
|
func database(ctx context.Context, app *backpack.App) (*gorm.DB, error) {
|
||||||
|
db, ok := app.Lookup[*gorm.DB]()
|
||||||
|
if !ok || db == nil {
|
||||||
|
return nil, classes.ErrNoDatabase
|
||||||
|
}
|
||||||
|
return db.WithContext(ctx), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ShowSettings serves GET /_sitemap/api/v1/settings: the sitemap settings,
|
||||||
|
// the content types, the files with their address counts, the left-out
|
||||||
|
// counts, the IndexNow key and last notification (settingsBody).
|
||||||
|
func ShowSettings(app func() *backpack.App) http.HandlerFunc {
|
||||||
|
return manage(app, func(ctx context.Context, a *backpack.App, _ *http.Request) (int, any, error) {
|
||||||
|
db, err := database(ctx, a)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
body, err := settingsBody(ctx, a, db)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
return http.StatusOK, map[string]any{"data": body}, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateSettings serves PUT /_sitemap/api/v1/settings: the fields sent
|
||||||
|
// change with the checks of the settings screen (422 validation_failed
|
||||||
|
// names the refused fields, types.<key>.<field> for a content type), the
|
||||||
|
// IndexNow key is generated as on the screen and a rebuild is queued once
|
||||||
|
// the change commits. It answers like ShowSettings.
|
||||||
|
func UpdateSettings(app func() *backpack.App) http.HandlerFunc {
|
||||||
|
return manage(app, func(ctx context.Context, a *backpack.App, r *http.Request) (int, any, error) {
|
||||||
|
var in UpdateSettingsInput
|
||||||
|
if err := decode(r, &in); err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
gdb, err := database(ctx, a)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
err = lagoon.Transaction(ctx, gdb, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
return applySettings(ctx, a, tx, in)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
body, err := settingsBody(ctx, a, gdb)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
return http.StatusOK, map[string]any{"data": body}, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// applySettings writes in inside tx: the settings columns sent, the HTML
|
||||||
|
// sitemap addresses merged per locale, the content types, the IndexNow
|
||||||
|
// key, then queues a rebuild after the commit.
|
||||||
|
func applySettings(ctx context.Context, app *backpack.App, tx *gorm.DB, in UpdateSettingsInput) error {
|
||||||
|
if err := tx.Exec(`INSERT INTO golem15_sitemap_settings (id) VALUES (1) ON CONFLICT (id) DO NOTHING`).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Exec(`SELECT id FROM golem15_sitemap_settings WHERE id = 1 FOR UPDATE`).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s, err := classes.LoadSettings(tx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
columns := map[string]any{}
|
||||||
|
if in.SiteURL != nil {
|
||||||
|
v := strings.TrimSpace(*in.SiteURL)
|
||||||
|
s.SiteURL = &v
|
||||||
|
columns["site_url"] = v
|
||||||
|
}
|
||||||
|
if in.FileSize != nil {
|
||||||
|
s.FileSize = *in.FileSize
|
||||||
|
columns["file_size"] = *in.FileSize
|
||||||
|
}
|
||||||
|
if in.ExtraURLs != nil {
|
||||||
|
s.ExtraURLs = lagoon.Jsonable[[]models.ExtraURL]{Data: nonNil(*in.ExtraURLs), Valid: true}
|
||||||
|
columns["extra_urls"] = s.ExtraURLs
|
||||||
|
}
|
||||||
|
if in.ImagesEnabled != nil {
|
||||||
|
s.ImagesEnabled = *in.ImagesEnabled
|
||||||
|
columns["images_enabled"] = *in.ImagesEnabled
|
||||||
|
}
|
||||||
|
if in.NewsEnabled != nil {
|
||||||
|
s.NewsEnabled = *in.NewsEnabled
|
||||||
|
columns["news_enabled"] = *in.NewsEnabled
|
||||||
|
}
|
||||||
|
if in.NewsPublication != nil {
|
||||||
|
v := strings.TrimSpace(*in.NewsPublication)
|
||||||
|
s.NewsPublication = &v
|
||||||
|
columns["news_publication"] = v
|
||||||
|
}
|
||||||
|
if in.NewsSources != nil {
|
||||||
|
list := []string{}
|
||||||
|
for _, v := range *in.NewsSources {
|
||||||
|
if v = strings.TrimSpace(v); v != "" {
|
||||||
|
list = append(list, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.NewsSources = lagoon.Jsonable[[]string]{Data: list, Valid: true}
|
||||||
|
columns["news_sources"] = s.NewsSources
|
||||||
|
}
|
||||||
|
if in.IndexNowEnabled != nil {
|
||||||
|
s.IndexNowEnabled = *in.IndexNowEnabled
|
||||||
|
columns["indexnow_enabled"] = *in.IndexNowEnabled
|
||||||
|
}
|
||||||
|
if in.HTMLEnabled != nil {
|
||||||
|
s.HTMLEnabled = *in.HTMLEnabled
|
||||||
|
columns["html_enabled"] = *in.HTMLEnabled
|
||||||
|
}
|
||||||
|
if in.HTMLPageSize != nil {
|
||||||
|
s.HTMLPageSize = *in.HTMLPageSize
|
||||||
|
columns["html_page_size"] = *in.HTMLPageSize
|
||||||
|
}
|
||||||
|
problems := s.Problems()
|
||||||
|
delete(problems, "html_path")
|
||||||
|
var paths map[string]string
|
||||||
|
if in.HTMLPaths != nil {
|
||||||
|
merged, bad := classes.MergeHTMLPaths(tx, in.HTMLPaths)
|
||||||
|
if bad {
|
||||||
|
problems["html_paths"] = []string{models.HTMLPathProblem}
|
||||||
|
}
|
||||||
|
paths = merged
|
||||||
|
}
|
||||||
|
var reg *signpost.Registry
|
||||||
|
if app != nil {
|
||||||
|
reg, _ = app.Lookup[*signpost.Registry]()
|
||||||
|
}
|
||||||
|
values, names := map[string]any{}, map[string]string{}
|
||||||
|
for key, t := range in.Types {
|
||||||
|
if reg == nil {
|
||||||
|
problems["types."+key] = []string{errUnknownType}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := reg.ContentType(key); !ok {
|
||||||
|
problems["types."+key] = []string{errUnknownType}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
base := classes.TypeFieldBase(key)
|
||||||
|
names[base+"include"], names[base+"slug"], names[base+"title"] = "types."+key+".include", "types."+key+".slug", "types."+key+".titles"
|
||||||
|
if t.Include != nil {
|
||||||
|
values[base+"include"] = *t.Include
|
||||||
|
}
|
||||||
|
if t.Slug != nil {
|
||||||
|
values[base+"slug"] = *t.Slug
|
||||||
|
}
|
||||||
|
if t.Titles != nil {
|
||||||
|
values[base+"title"] = t.Titles
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(problems) > 0 {
|
||||||
|
return &ProblemsError{Problems: problems}
|
||||||
|
}
|
||||||
|
if len(columns) > 0 {
|
||||||
|
if err := tx.Model(&models.Settings{}).Where("id = ?", 1).Updates(columns).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if paths != nil {
|
||||||
|
if err := classes.StoreHTMLPaths(tx, paths); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if reg != nil && len(values) > 0 {
|
||||||
|
refusals, err := classes.SaveTypeSettings(tx, reg.ContentTypes(), values)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(refusals) > 0 {
|
||||||
|
out := map[string][]string{}
|
||||||
|
for field, keys := range refusals {
|
||||||
|
if name, ok := names[field]; ok {
|
||||||
|
field = name
|
||||||
|
}
|
||||||
|
out[field] = keys
|
||||||
|
}
|
||||||
|
return &ProblemsError{Problems: out}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if _, err := classes.EnsureKey(tx, s.IndexNowEnabled, in.IndexNowNewKey != nil && *in.IndexNowNewKey); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return classes.RequestRebuild(ctx, app, tx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rebuild serves POST /_sitemap/api/v1/rebuild: it queues a rebuild of the
|
||||||
|
// sitemap files now (the settings screen then shows files.building) and
|
||||||
|
// answers 202 {"data":{"queued":true}}.
|
||||||
|
func Rebuild(app func() *backpack.App) http.HandlerFunc {
|
||||||
|
return manage(app, func(ctx context.Context, a *backpack.App, _ *http.Request) (int, any, error) {
|
||||||
|
gdb, err := database(ctx, a)
|
||||||
|
if err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
if err := lagoon.Transaction(ctx, gdb, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
|
return classes.RequestRebuild(ctx, a, tx)
|
||||||
|
}); err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
return http.StatusAccepted, map[string]any{"data": map[string]any{"queued": true}}, nil
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,162 +0,0 @@
|
|||||||
// Package controllers holds the sitemap plugin's admin controllers.
|
|
||||||
package controllers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/pact"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/signpost"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// DefinitionsControllerID is the cabana controller id of the sitemap
|
|
||||||
// definition form.
|
|
||||||
DefinitionsControllerID = "golem15.sitemap.definitions"
|
|
||||||
// PermissionAccessDefinitions is Definitions::$requiredPermissions.
|
|
||||||
PermissionAccessDefinitions = "golem15.sitemap.access_definitions"
|
|
||||||
)
|
|
||||||
|
|
||||||
// typeURLLabel is the label of the built-in url item type.
|
|
||||||
const typeURLLabel = "golem15.sitemap::lang.item.url"
|
|
||||||
|
|
||||||
// The phrase keys of the item row refusals.
|
|
||||||
const (
|
|
||||||
errURLScheme = "golem15.sitemap::lang.errors.url_scheme"
|
|
||||||
errURLPattern = "golem15.sitemap::lang.errors.url_pattern"
|
|
||||||
errReference = "golem15.sitemap::lang.item.reference_required"
|
|
||||||
)
|
|
||||||
|
|
||||||
// definitionsAdminController edits the one sitemap definition of the
|
|
||||||
// application (theme default): a singleton form whose items are a repeater
|
|
||||||
// with a type dropdown (url plus the registry types) and a reference
|
|
||||||
// dropdown that depends on it.
|
|
||||||
type definitionsAdminController struct {
|
|
||||||
app func() *backpack.App
|
|
||||||
}
|
|
||||||
|
|
||||||
func (definitionsAdminController) ID() string { return DefinitionsControllerID }
|
|
||||||
|
|
||||||
func (definitionsAdminController) ModelName() string { return `Golem15\Sitemap\Models\Definition` }
|
|
||||||
|
|
||||||
func (definitionsAdminController) ConfigDir() string { return "controllers/definitions" }
|
|
||||||
|
|
||||||
func (definitionsAdminController) RequiredPermissions() []string {
|
|
||||||
return []string{PermissionAccessDefinitions}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (definitionsAdminController) NewRecord() any { return &models.Definition{} }
|
|
||||||
|
|
||||||
// The singleton record is the definition with the fixed theme key, created
|
|
||||||
// with no items when there is none (PHP index(): firstOrCreate, then the
|
|
||||||
// update form).
|
|
||||||
func (definitionsAdminController) SingletonRecord(_ context.Context, db *gorm.DB) (any, error) {
|
|
||||||
if db == nil {
|
|
||||||
return nil, errors.New("golem15.sitemap: database is not configured")
|
|
||||||
}
|
|
||||||
var defs []models.Definition
|
|
||||||
if err := db.Where("theme = ?", models.DefinitionTheme).Order("id ASC").Limit(1).Find(&defs).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if len(defs) > 0 {
|
|
||||||
return &defs[0], nil
|
|
||||||
}
|
|
||||||
theme := models.DefinitionTheme
|
|
||||||
def := &models.Definition{Theme: &theme}
|
|
||||||
def.SetItems(nil)
|
|
||||||
if err := db.Create(def).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return def, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c definitionsAdminController) registry() *signpost.Registry {
|
|
||||||
if c.app == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
app := c.app()
|
|
||||||
if app == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
reg, _ := app.Lookup[*signpost.Registry]()
|
|
||||||
return reg
|
|
||||||
}
|
|
||||||
|
|
||||||
// DropdownOptions serves the item type dropdown: url, then every registry
|
|
||||||
// type in registry order with its label (PHP getTypeOptions).
|
|
||||||
func (c definitionsAdminController) DropdownOptions(string) []pact.Option {
|
|
||||||
out := []pact.Option{{Value: models.ItemTypeURL, Label: typeURLLabel}}
|
|
||||||
for _, t := range c.registry().Types() {
|
|
||||||
out = append(out, pact.Option{Value: t.Key, Label: t.Label})
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// DependentOptions serves the reference dropdown of an item row: the
|
|
||||||
// references of the row's type through signpost.ReferenceOptions; url and a
|
|
||||||
// type without references answer Applies false.
|
|
||||||
func (c definitionsAdminController) DependentOptions(ctx context.Context, _ string, values map[string]any) (pact.DependentOptionSet, error) {
|
|
||||||
typ, _ := values["type"].(string)
|
|
||||||
return signpost.ReferenceOptions(ctx, c.registry(), typ)
|
|
||||||
}
|
|
||||||
|
|
||||||
// FormBeforeCreate checks the item rows (see checkItems).
|
|
||||||
func (c definitionsAdminController) FormBeforeCreate(_ context.Context, model any) error {
|
|
||||||
return c.checkItems(model)
|
|
||||||
}
|
|
||||||
|
|
||||||
// FormBeforeUpdate checks the item rows (see checkItems).
|
|
||||||
func (c definitionsAdminController) FormBeforeUpdate(_ context.Context, model any) error {
|
|
||||||
return c.checkItems(model)
|
|
||||||
}
|
|
||||||
|
|
||||||
// checkItems refuses, per row, a url outside classes.AllowedItemURL
|
|
||||||
// (data.<i>.url), a URL pattern that is not a path
|
|
||||||
// (signpost.ValidItemPattern, data.<i>.urlPattern) and a missing reference
|
|
||||||
// for a registry type that takes one (data.<i>.reference). The PHP plugin
|
|
||||||
// checked none of them: a javascript: URL would reach <loc>, which
|
|
||||||
// sitemap.xsl renders as a link, and a row without its reference resolves to
|
|
||||||
// nothing and is left out of the sitemap without a word.
|
|
||||||
func (c definitionsAdminController) checkItems(model any) error {
|
|
||||||
def, ok := model.(*models.Definition)
|
|
||||||
if !ok || def == nil {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
reg := c.registry()
|
|
||||||
details := map[string]any{}
|
|
||||||
for i, item := range def.Items() {
|
|
||||||
if item.Type != models.ItemTypeURL {
|
|
||||||
if t, known := reg.Type(item.Type); known && t.References != nil && strings.TrimSpace(models.Text(item.Reference)) == "" {
|
|
||||||
details[fmt.Sprintf("data.%d.reference", i)] = []string{errReference}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !classes.AllowedItemURL(models.Text(item.URL)) {
|
|
||||||
details[fmt.Sprintf("data.%d.url", i)] = []string{errURLScheme}
|
|
||||||
}
|
|
||||||
if p := models.Text(item.URLPattern); p != "" && !signpost.ValidItemPattern(p) {
|
|
||||||
details[fmt.Sprintf("data.%d.urlPattern", i)] = []string{errURLPattern}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(details) > 0 {
|
|
||||||
return &cabana.ValidationError{Details: details}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
_ pact.AdminController = definitionsAdminController{}
|
|
||||||
_ pact.AdminPermissioned = definitionsAdminController{}
|
|
||||||
_ pact.AdminRecordSource = definitionsAdminController{}
|
|
||||||
_ pact.AdminSingleton = definitionsAdminController{}
|
|
||||||
_ pact.DropdownOptionsProvider = definitionsAdminController{}
|
|
||||||
_ pact.DependentOptionsProvider = definitionsAdminController{}
|
|
||||||
_ pact.FormBeforeCreate = definitionsAdminController{}
|
|
||||||
_ pact.FormBeforeUpdate = definitionsAdminController{}
|
|
||||||
)
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
# ===================================
|
|
||||||
# Form Behavior Config
|
|
||||||
# ===================================
|
|
||||||
|
|
||||||
# Record name
|
|
||||||
name: golem15.sitemap::lang.definition.title
|
|
||||||
|
|
||||||
# Model Form Field configuration
|
|
||||||
form: ~/plugins/golem15/sitemap/models/definition/fields.yaml
|
|
||||||
|
|
||||||
# Model Class name
|
|
||||||
modelClass: Golem15\Sitemap\Models\Definition
|
|
||||||
|
|
||||||
# Default redirect location
|
|
||||||
defaultRedirect: system/settings
|
|
||||||
|
|
||||||
# Update page
|
|
||||||
update:
|
|
||||||
redirect: golem15/sitemap/definitions
|
|
||||||
redirectClose: system/settings
|
|
||||||
|
|
||||||
messages:
|
|
||||||
update: golem15.sitemap::lang.definition.title
|
|
||||||
saved: backend::lang.messages.form.saved
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package controllers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
|
||||||
)
|
|
||||||
|
|
||||||
func ptr(s string) *string { return &s }
|
|
||||||
|
|
||||||
// TestCheckItems pins the CR-01 save check: per row, a url outside
|
|
||||||
// classes.AllowedItemURL and a URL pattern that is not a path are refused
|
|
||||||
// under data.<i>.url and data.<i>.urlPattern.
|
|
||||||
func TestCheckItems(t *testing.T) {
|
|
||||||
c := definitionsAdminController{}
|
|
||||||
def := &models.Definition{}
|
|
||||||
def.SetItems([]models.DefinitionItem{
|
|
||||||
{Type: models.ItemTypeURL, URL: ptr("/about")},
|
|
||||||
{Type: models.ItemTypeURL, URL: ptr("javascript://%0aalert(1)%0a//x")},
|
|
||||||
{Type: "acme-post", URLPattern: ptr("//evil.test/:slug")},
|
|
||||||
{Type: "acme-post", URLPattern: ptr("/blog/:slug")},
|
|
||||||
})
|
|
||||||
err := c.checkItems(def)
|
|
||||||
var verr *cabana.ValidationError
|
|
||||||
if !errors.As(err, &verr) {
|
|
||||||
t.Fatalf("checkItems = %v, want a validation error", err)
|
|
||||||
}
|
|
||||||
if len(verr.Details) != 2 || verr.Details["data.1.url"] == nil || verr.Details["data.2.urlPattern"] == nil {
|
|
||||||
t.Fatalf("details = %v", verr.Details)
|
|
||||||
}
|
|
||||||
|
|
||||||
ok := &models.Definition{}
|
|
||||||
ok.SetItems([]models.DefinitionItem{{Type: models.ItemTypeURL, URL: ptr("https://example.test/")}})
|
|
||||||
if err := c.checkItems(ok); err != nil {
|
|
||||||
t.Fatalf("a valid definition was refused: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
410
controllers/settings.go
Normal file
410
controllers/settings.go
Normal file
@@ -0,0 +1,410 @@
|
|||||||
|
package controllers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/contract"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/signpost"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// SettingsControllerID is the cabana controller id of the sitemap
|
||||||
|
// settings singleton (UI-SPEC C26), linked from the sitemap settings
|
||||||
|
// tile.
|
||||||
|
SettingsControllerID = "golem15.sitemap.settings"
|
||||||
|
// PermissionAccessDefinitions guards the sitemap settings. The code is
|
||||||
|
// the Phase 17 (and WinterCMS) one, so existing roles keep their access.
|
||||||
|
PermissionAccessDefinitions = "golem15.sitemap.access_definitions"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The reasons the files partial counts as "left out", in display order
|
||||||
|
// (P33-11). A deleted or unpublished address is a hole, not left out.
|
||||||
|
var leftOutReasons = []string{contract.ReasonNoindex, contract.ReasonCanonical, contract.ReasonRedirect, contract.ReasonType, models.ReasonDuplicate}
|
||||||
|
|
||||||
|
// settingsAdminController edits the sitemap settings singleton: Files,
|
||||||
|
// Content types (added by the plugin's own form extension) and Additional
|
||||||
|
// addresses. A save dispatches a rebuild.
|
||||||
|
type settingsAdminController struct {
|
||||||
|
app func() *backpack.App
|
||||||
|
}
|
||||||
|
|
||||||
|
func (settingsAdminController) ID() string { return SettingsControllerID }
|
||||||
|
func (settingsAdminController) ModelName() string { return `Golem15\Sitemap\Models\Settings` }
|
||||||
|
func (settingsAdminController) ConfigDir() string { return "controllers/settings" }
|
||||||
|
func (settingsAdminController) NewRecord() any { return &models.Settings{} }
|
||||||
|
func (settingsAdminController) RequiredPermissions() []string {
|
||||||
|
return []string{PermissionAccessDefinitions}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SingletonRecord returns settings row 1, creating it with the defaults
|
||||||
|
// when the migration's row is gone (safe against a concurrent first
|
||||||
|
// request through ON CONFLICT DO NOTHING).
|
||||||
|
func (settingsAdminController) SingletonRecord(_ context.Context, db *gorm.DB) (any, error) {
|
||||||
|
if db == nil {
|
||||||
|
return nil, errors.New("golem15.sitemap: database is not configured")
|
||||||
|
}
|
||||||
|
var rows []models.Settings
|
||||||
|
if err := db.Where("id = ?", 1).Limit(1).Find(&rows).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if len(rows) > 0 {
|
||||||
|
return &rows[0], nil
|
||||||
|
}
|
||||||
|
if err := db.Exec(`INSERT INTO golem15_sitemap_settings (id) VALUES (1) ON CONFLICT (id) DO NOTHING`).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := db.Where("id = ?", 1).Limit(1).Find(&rows).Error; err != nil || len(rows) == 0 {
|
||||||
|
return nil, errors.New("golem15.sitemap: settings row is missing")
|
||||||
|
}
|
||||||
|
return &rows[0], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormBeforeUpdate refuses the settings Problems finds (UI-SPEC C26:
|
||||||
|
// errors.frontend_url on site_url, errors.file_size, errors.url_scheme and
|
||||||
|
// errors.lastmod on an additional address).
|
||||||
|
func (settingsAdminController) FormBeforeUpdate(_ context.Context, model any) error {
|
||||||
|
s, ok := model.(*models.Settings)
|
||||||
|
if !ok || s == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return s.Validate()
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormBeforeCreate checks a created row like an update.
|
||||||
|
func (c settingsAdminController) FormBeforeCreate(ctx context.Context, model any) error {
|
||||||
|
return c.FormBeforeUpdate(ctx, model)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormVirtualFields names indexnow_new_key, the "generate a new key on
|
||||||
|
// save" checkbox, which is no column.
|
||||||
|
func (settingsAdminController) FormVirtualFields() []string {
|
||||||
|
return []string{"indexnow_new_key"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormAfterUpdate generates the IndexNow key (on the first save with
|
||||||
|
// IndexNow on, or a new one when indexnow_new_key is checked) and
|
||||||
|
// dispatches a rebuild once the save commits (C26: saving the form rebuilds
|
||||||
|
// the files now). A queue error is logged and never fails the save.
|
||||||
|
func (c settingsAdminController) FormAfterUpdate(ctx context.Context, model any) error {
|
||||||
|
app := appOf(c.app)
|
||||||
|
tx, err := database(ctx, c.app)
|
||||||
|
if err != nil || app == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if s, ok := model.(*models.Settings); ok && s != nil {
|
||||||
|
values, _ := cabana.VirtualFieldsFromContext(ctx)
|
||||||
|
if _, err := classes.EnsureKey(tx, s.IndexNowEnabled, boolOf(values["indexnow_new_key"])); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return classes.RequestRebuild(ctx, app, tx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// boolOf reads a submitted checkbox value.
|
||||||
|
func boolOf(v any) bool {
|
||||||
|
switch b := v.(type) {
|
||||||
|
case bool:
|
||||||
|
return b
|
||||||
|
case string:
|
||||||
|
return b == "1" || strings.EqualFold(b, "true") || strings.EqualFold(b, "on")
|
||||||
|
case float64:
|
||||||
|
return b != 0
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormAfterCreate dispatches a rebuild like an update.
|
||||||
|
func (c settingsAdminController) FormAfterCreate(ctx context.Context, model any) error {
|
||||||
|
return c.FormAfterUpdate(ctx, model)
|
||||||
|
}
|
||||||
|
|
||||||
|
// filesView is the view model of the S1 partial sitemap_files.
|
||||||
|
type filesView struct {
|
||||||
|
Building bool
|
||||||
|
Empty bool
|
||||||
|
Files []fileRow
|
||||||
|
LeftOut []reasonRow
|
||||||
|
Note string
|
||||||
|
}
|
||||||
|
|
||||||
|
// fileRow is one row of the S1 files table: the index first, then each
|
||||||
|
// file. URL is the backend route that serves it.
|
||||||
|
type fileRow struct {
|
||||||
|
Name string
|
||||||
|
URL string
|
||||||
|
Count int
|
||||||
|
LastMod string
|
||||||
|
}
|
||||||
|
|
||||||
|
// reasonRow is one row of the S1 left-out table.
|
||||||
|
type reasonRow struct {
|
||||||
|
Label string
|
||||||
|
Count int
|
||||||
|
}
|
||||||
|
|
||||||
|
// PartialData serves the S1 files partial: the index and its files with
|
||||||
|
// their address counts and newest lastmod, the left-out counts by reason
|
||||||
|
// and the index note; files.empty before the first build and
|
||||||
|
// files.building while a rebuild asked for from the admin runs.
|
||||||
|
func (c settingsAdminController) PartialData(ctx context.Context, name string, _ any) (any, error) {
|
||||||
|
switch name {
|
||||||
|
case "sitemap_files":
|
||||||
|
return c.filesData(ctx)
|
||||||
|
case "news_sources":
|
||||||
|
return c.newsSourcesData(ctx)
|
||||||
|
case "indexnow_status":
|
||||||
|
return c.indexNowData(ctx)
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// indexNowView is the view model of the S2 partial indexnow_status.
|
||||||
|
type indexNowView struct {
|
||||||
|
Key string
|
||||||
|
Last string
|
||||||
|
Callout string
|
||||||
|
Severity string
|
||||||
|
}
|
||||||
|
|
||||||
|
// indexNowData serves S2 (UI-SPEC C26): indexnow.key or indexnow.no_key,
|
||||||
|
// indexnow.last or indexnow.never, and the callout of the last answer: 403
|
||||||
|
// err_key (warning), 422 err_host (warning), 429 err_rate with the next
|
||||||
|
// attempt (plain) while one is pending.
|
||||||
|
func (c settingsAdminController) indexNowData(ctx context.Context) (any, error) {
|
||||||
|
app := appOf(c.app)
|
||||||
|
db, err := database(ctx, c.app)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
settings, err := classes.LoadSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
st := classes.LoadIndexNowStatus(db, app, settings)
|
||||||
|
tr := translator(c.app)
|
||||||
|
view := indexNowView{}
|
||||||
|
if st.Key == "" {
|
||||||
|
view.Key = Phrase(ctx, tr, "golem15.sitemap::lang.indexnow.no_key", nil)
|
||||||
|
} else {
|
||||||
|
view.Key = Phrase(ctx, tr, "golem15.sitemap::lang.indexnow.key", map[string]string{"key": st.Key, "url": st.KeyURL})
|
||||||
|
}
|
||||||
|
if st.LastAt == nil {
|
||||||
|
view.Last = Phrase(ctx, tr, "golem15.sitemap::lang.indexnow.never", nil)
|
||||||
|
} else {
|
||||||
|
view.Last = Phrase(ctx, tr, "golem15.sitemap::lang.indexnow.last", map[string]string{
|
||||||
|
"time": formatTime(st.LastAt), "count": strconv.Itoa(st.LastCount), "status": strconv.Itoa(st.LastStatus),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
switch st.LastStatus {
|
||||||
|
case http.StatusForbidden:
|
||||||
|
view.Callout, view.Severity = Phrase(ctx, tr, "golem15.sitemap::lang.indexnow.err_key", map[string]string{"url": st.KeyURL}), "warning"
|
||||||
|
case http.StatusUnprocessableEntity:
|
||||||
|
view.Callout, view.Severity = Phrase(ctx, tr, "golem15.sitemap::lang.indexnow.err_host", nil), "warning"
|
||||||
|
case http.StatusTooManyRequests:
|
||||||
|
if st.RetryAt != nil {
|
||||||
|
view.Callout = Phrase(ctx, tr, "golem15.sitemap::lang.indexnow.err_rate", map[string]string{"time": formatTime(st.RetryAt)})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return view, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// sourceRow is one row of the news_sources partial: the value to enter and
|
||||||
|
// what it lists.
|
||||||
|
type sourceRow struct {
|
||||||
|
Value string
|
||||||
|
Label string
|
||||||
|
}
|
||||||
|
|
||||||
|
// newsSourcesView is the view model of the news_sources partial.
|
||||||
|
type newsSourcesView struct {
|
||||||
|
Rows []sourceRow
|
||||||
|
}
|
||||||
|
|
||||||
|
// newsSourcesData lists the values the news_sources taglist takes
|
||||||
|
// (classes.NewsSources): each article type, then the categories its
|
||||||
|
// listed articles name, labelled "<type>: <title>".
|
||||||
|
func (c settingsAdminController) newsSourcesData(ctx context.Context) (any, error) {
|
||||||
|
app := appOf(c.app)
|
||||||
|
db, err := database(ctx, c.app)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
settings, err := classes.LoadSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var reg *signpost.Registry
|
||||||
|
if app != nil {
|
||||||
|
reg, _ = app.Lookup[*signpost.Registry]()
|
||||||
|
}
|
||||||
|
sources, err := classes.NewsSources(db, reg, models.Text(settings.DefaultLocale))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tr := translator(c.app)
|
||||||
|
label := func(key string) string {
|
||||||
|
if reg != nil {
|
||||||
|
if typ, ok := reg.ContentType(key); ok && typ.Label != "" {
|
||||||
|
return Phrase(ctx, tr, typ.Label, nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return key
|
||||||
|
}
|
||||||
|
view := newsSourcesView{}
|
||||||
|
for _, src := range sources {
|
||||||
|
row := sourceRow{Value: src.Value}
|
||||||
|
if src.ID == "" {
|
||||||
|
row.Label = Phrase(ctx, tr, "golem15.sitemap::lang.news.source_type", map[string]string{"type": label(src.Type)})
|
||||||
|
} else {
|
||||||
|
title := src.Title
|
||||||
|
if title == "" {
|
||||||
|
title = src.ID
|
||||||
|
}
|
||||||
|
row.Label = label(src.Type) + ": " + title
|
||||||
|
}
|
||||||
|
view.Rows = append(view.Rows, row)
|
||||||
|
}
|
||||||
|
return view, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// filesData is the view of the S1 files partial.
|
||||||
|
func (c settingsAdminController) filesData(ctx context.Context) (any, error) {
|
||||||
|
app := appOf(c.app)
|
||||||
|
db, err := database(ctx, c.app)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
settings, err := classes.LoadSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
site := classes.SiteURL(app, settings)
|
||||||
|
view := filesView{Building: classes.Building(settings.RebuildRequestedAt, settings.BuiltAt, time.Now())}
|
||||||
|
files, err := classes.SitemapFiles(db, app, settings, time.Now().UTC())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// The partial kit links only root-relative addresses, so a file links
|
||||||
|
// to the backend route that serves it; the note names the public index.
|
||||||
|
link := func(name string) string {
|
||||||
|
if name == "sitemap.xml" {
|
||||||
|
return "/sitemap.xml"
|
||||||
|
}
|
||||||
|
return "/_sitemap/files/" + name
|
||||||
|
}
|
||||||
|
if len(files) == 0 {
|
||||||
|
view.Empty = true
|
||||||
|
} else {
|
||||||
|
index := fileRow{Name: "sitemap.xml", URL: link("sitemap.xml")}
|
||||||
|
var newest *time.Time
|
||||||
|
for _, f := range files {
|
||||||
|
// The index counts addresses; the image and News files list
|
||||||
|
// some of them again.
|
||||||
|
if !strings.HasPrefix(f.Name, "sitemap-"+classes.ImagesGroup+"-") && f.Name != classes.NewsFile {
|
||||||
|
index.Count += f.Count
|
||||||
|
}
|
||||||
|
if f.LastMod != nil && (newest == nil || f.LastMod.After(*newest)) {
|
||||||
|
newest = f.LastMod
|
||||||
|
}
|
||||||
|
view.Files = append(view.Files, fileRow{Name: f.Name, URL: link(f.Name), Count: f.Count, LastMod: formatTime(f.LastMod)})
|
||||||
|
}
|
||||||
|
index.LastMod = formatTime(newest)
|
||||||
|
view.Files = append([]fileRow{index}, view.Files...)
|
||||||
|
}
|
||||||
|
byReason, err := classes.LeftOut(db)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
tr := translator(c.app)
|
||||||
|
for _, reason := range leftOutReasons {
|
||||||
|
if n := byReason[reason]; n > 0 {
|
||||||
|
view.LeftOut = append(view.LeftOut, reasonRow{Label: Phrase(ctx, tr, "golem15.sitemap::lang.files.reason_"+reason, nil), Count: n})
|
||||||
|
delete(byReason, reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for reason, n := range byReason {
|
||||||
|
view.LeftOut = append(view.LeftOut, reasonRow{Label: reason, Count: n})
|
||||||
|
}
|
||||||
|
indexURL := "/sitemap.xml"
|
||||||
|
if site != "" {
|
||||||
|
indexURL = site + "/sitemap.xml"
|
||||||
|
}
|
||||||
|
view.Note = Phrase(ctx, tr, "golem15.sitemap::lang.files.index_note", map[string]string{"url": indexURL})
|
||||||
|
return view, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatTime renders a lastmod for the files table, "" when unknown.
|
||||||
|
func formatTime(t *time.Time) string {
|
||||||
|
if t == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return t.UTC().Format("2006-01-02 15:04 UTC")
|
||||||
|
}
|
||||||
|
|
||||||
|
// appOf calls the lazy app accessor.
|
||||||
|
func appOf(app func() *backpack.App) *backpack.App {
|
||||||
|
if app == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return app()
|
||||||
|
}
|
||||||
|
|
||||||
|
// translator returns the application's translator, nil when none.
|
||||||
|
func translator(app func() *backpack.App) *phrasebook.Translator {
|
||||||
|
a := appOf(app)
|
||||||
|
if a == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
tr, _ := a.Lookup[*phrasebook.Translator]()
|
||||||
|
return tr
|
||||||
|
}
|
||||||
|
|
||||||
|
// database returns the write transaction of ctx, else the app database.
|
||||||
|
func database(ctx context.Context, app func() *backpack.App) (*gorm.DB, error) {
|
||||||
|
if tx, ok := cabana.TxFromContext(ctx); ok && tx != nil {
|
||||||
|
return tx, nil
|
||||||
|
}
|
||||||
|
a := appOf(app)
|
||||||
|
if a == nil {
|
||||||
|
return nil, errors.New("golem15.sitemap: app is not booted")
|
||||||
|
}
|
||||||
|
db, ok := a.Lookup[*gorm.DB]()
|
||||||
|
if !ok || db == nil {
|
||||||
|
return nil, errors.New("golem15.sitemap: database is not configured")
|
||||||
|
}
|
||||||
|
return db.WithContext(ctx), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Phrase translates key with params in the request locale; without a
|
||||||
|
// translator it returns the key.
|
||||||
|
func Phrase(ctx context.Context, tr *phrasebook.Translator, key string, params map[string]string) string {
|
||||||
|
if tr == nil {
|
||||||
|
return key
|
||||||
|
}
|
||||||
|
return tr.Get(ctx, key, params)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
_ pact.AdminController = settingsAdminController{}
|
||||||
|
_ pact.AdminPermissioned = settingsAdminController{}
|
||||||
|
_ pact.AdminRecordSource = settingsAdminController{}
|
||||||
|
_ pact.AdminSingleton = settingsAdminController{}
|
||||||
|
_ pact.AdminPartialData = settingsAdminController{}
|
||||||
|
_ pact.FormBeforeCreate = settingsAdminController{}
|
||||||
|
_ pact.FormBeforeUpdate = settingsAdminController{}
|
||||||
|
_ pact.FormAfterCreate = settingsAdminController{}
|
||||||
|
_ pact.FormAfterUpdate = settingsAdminController{}
|
||||||
|
_ pact.FormVirtualFields = settingsAdminController{}
|
||||||
|
)
|
||||||
15
controllers/settings/_indexnow_status.htm
Normal file
15
controllers/settings/_indexnow_status.htm
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<div class="summer-callout" role="status">
|
||||||
|
<p class="summer-callout__text">{{ .Data.Key }}</p>
|
||||||
|
<p class="summer-callout__text">{{ .Data.Last }}</p>
|
||||||
|
</div>
|
||||||
|
{{- if .Data.Callout -}}
|
||||||
|
{{- if eq .Data.Severity "warning" -}}
|
||||||
|
<div class="summer-callout summer-callout--warning" role="alert">
|
||||||
|
<p class="summer-callout__text">{{ .Data.Callout }}</p>
|
||||||
|
</div>
|
||||||
|
{{- else -}}
|
||||||
|
<div class="summer-callout" role="status">
|
||||||
|
<p class="summer-callout__text">{{ .Data.Callout }}</p>
|
||||||
|
</div>
|
||||||
|
{{- end -}}
|
||||||
|
{{- end -}}
|
||||||
19
controllers/settings/_news_sources.htm
Normal file
19
controllers/settings/_news_sources.htm
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
{{- if .Data.Rows -}}
|
||||||
|
<section>
|
||||||
|
<h4>{{ trans "golem15.sitemap::lang.news.sources" }}</h4>
|
||||||
|
<div class="summer-table-wrap">
|
||||||
|
<table class="summer-table">
|
||||||
|
<thead><tr><th>{{ trans "golem15.sitemap::lang.news.source_value" }}</th><th>{{ trans "golem15.sitemap::lang.news.source_label" }}</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{{- range .Data.Rows -}}
|
||||||
|
<tr><td><code>{{ .Value }}</code></td><td>{{ .Label }}</td></tr>
|
||||||
|
{{- end -}}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{{- else -}}
|
||||||
|
<div class="summer-callout" role="status">
|
||||||
|
<p class="summer-callout__text">{{ trans "golem15.sitemap::lang.news.none" }}</p>
|
||||||
|
</div>
|
||||||
|
{{- end -}}
|
||||||
42
controllers/settings/_sitemap_files.htm
Normal file
42
controllers/settings/_sitemap_files.htm
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
{{- if .Data.Building -}}
|
||||||
|
<div class="summer-callout" role="status">
|
||||||
|
<p class="summer-callout__text">{{ trans "golem15.sitemap::lang.files.building" }}</p>
|
||||||
|
</div>
|
||||||
|
{{- end -}}
|
||||||
|
{{- if .Data.Empty -}}
|
||||||
|
<div class="summer-callout" role="status">
|
||||||
|
<p class="summer-callout__text">{{ trans "golem15.sitemap::lang.files.empty" }}</p>
|
||||||
|
</div>
|
||||||
|
{{- else -}}
|
||||||
|
<section>
|
||||||
|
<h4>{{ trans "golem15.sitemap::lang.files.label" }}</h4>
|
||||||
|
<div class="summer-table-wrap">
|
||||||
|
<table class="summer-table">
|
||||||
|
<thead><tr><th>{{ trans "golem15.sitemap::lang.files.file" }}</th><th class="summer-table__num">{{ trans "golem15.sitemap::lang.files.file_urls" }}</th><th>{{ trans "golem15.sitemap::lang.files.file_lastmod" }}</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{{- range .Data.Files -}}
|
||||||
|
<tr><td>{{ if .URL }}<a href="{{ .URL }}"><code>{{ .Name }}</code></a>{{ else }}<code>{{ .Name }}</code>{{ end }}</td><td class="summer-table__num">{{ .Count }}</td><td>{{ .LastMod }}</td></tr>
|
||||||
|
{{- end -}}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{{- end -}}
|
||||||
|
{{- if .Data.LeftOut -}}
|
||||||
|
<section>
|
||||||
|
<h4>{{ trans "golem15.sitemap::lang.files.left_out" }}</h4>
|
||||||
|
<div class="summer-table-wrap">
|
||||||
|
<table class="summer-table">
|
||||||
|
<thead><tr><th>{{ trans "golem15.sitemap::lang.files.left_out_reason" }}</th><th class="summer-table__num">{{ trans "golem15.sitemap::lang.files.left_out_count" }}</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{{- range .Data.LeftOut -}}
|
||||||
|
<tr><td>{{ .Label }}</td><td class="summer-table__num">{{ .Count }}</td></tr>
|
||||||
|
{{- end -}}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
{{- end -}}
|
||||||
|
<div class="summer-callout" role="note">
|
||||||
|
<p class="summer-callout__text">{{ .Data.Note }}</p>
|
||||||
|
</div>
|
||||||
20
controllers/settings/config_form.yaml
Normal file
20
controllers/settings/config_form.yaml
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
# ===================================
|
||||||
|
# Form Behavior Config
|
||||||
|
# ===================================
|
||||||
|
#
|
||||||
|
# The sitemap settings singleton (UI-SPEC C26), linked from the sitemap
|
||||||
|
# settings tile. The plugin's form extension adds the Content types tab
|
||||||
|
# after Files.
|
||||||
|
|
||||||
|
name: golem15.sitemap::lang.settings.label
|
||||||
|
form: ~/plugins/golem15/sitemap/models/settings/fields.yaml
|
||||||
|
modelClass: Golem15\Sitemap\Models\Settings
|
||||||
|
defaultRedirect: system/settings
|
||||||
|
|
||||||
|
update:
|
||||||
|
redirect: golem15/sitemap/settings
|
||||||
|
redirectClose: system/settings
|
||||||
|
|
||||||
|
messages:
|
||||||
|
update: golem15.sitemap::lang.settings.label
|
||||||
|
saved: backend::lang.messages.form.saved
|
||||||
219
extensions_settings.go
Normal file
219
extensions_settings.go
Normal file
@@ -0,0 +1,219 @@
|
|||||||
|
package sitemap
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/controllers"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/phrasebook"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/signpost"
|
||||||
|
"github.com/goccy/go-yaml"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The settings form's tab keys: the Content types tab follows Files; the
|
||||||
|
// HTML sitemap tab's address field is added after html_enabled.
|
||||||
|
const (
|
||||||
|
TabFiles = "golem15.sitemap::lang.settings.tab_files"
|
||||||
|
TabTypes = "golem15.sitemap::lang.settings.tab_types"
|
||||||
|
TabHTML = "golem15.sitemap::lang.settings.tab_html"
|
||||||
|
)
|
||||||
|
|
||||||
|
// htmlPathField is the HTML sitemap address field: translatable, stored
|
||||||
|
// as a locale map in html_paths by the plugin's form extension (the
|
||||||
|
// settings row has no translation writer of its own).
|
||||||
|
const htmlPathField = "html_path"
|
||||||
|
|
||||||
|
// AdminActionExtensions extends the plugin's own settings singleton: the
|
||||||
|
// Content types tab (one block per signpost content type, in registration
|
||||||
|
// order; none without content types) and the HTML sitemap address.
|
||||||
|
func (p *Plugin) AdminActionExtensions() []pact.AdminActionExtension {
|
||||||
|
var types []pact.MenuItemType
|
||||||
|
if reg := p.registry(); reg != nil {
|
||||||
|
types = reg.ContentTypes()
|
||||||
|
}
|
||||||
|
form := p.typeSettingsTab(types)
|
||||||
|
if form == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return []pact.AdminActionExtension{{Controller: controllers.SettingsControllerID, Form: form}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *Plugin) registry() *signpost.Registry {
|
||||||
|
if p == nil || p.app == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
reg, _ := p.app.Lookup[*signpost.Registry]()
|
||||||
|
return reg
|
||||||
|
}
|
||||||
|
|
||||||
|
// typeSettingsDocument is the fields document of the extension (UI-SPEC
|
||||||
|
// C26): per type, the include switch (labelled with the type's label), the
|
||||||
|
// file name and the HTML sitemap heading on the Content types tab, then
|
||||||
|
// the HTML sitemap address after html_enabled.
|
||||||
|
func typeSettingsDocument(types []pact.MenuItemType) ([]byte, error) {
|
||||||
|
fields := yaml.MapSlice{}
|
||||||
|
for _, typ := range types {
|
||||||
|
base := classes.TypeFieldBase(typ.Key)
|
||||||
|
label := typ.Label
|
||||||
|
if strings.TrimSpace(label) == "" {
|
||||||
|
label = typ.Key
|
||||||
|
}
|
||||||
|
fields = append(fields,
|
||||||
|
yaml.MapItem{Key: base + "include", Value: yaml.MapSlice{
|
||||||
|
{Key: "label", Value: label},
|
||||||
|
{Key: "comment", Value: "golem15.sitemap::lang.settings.type_include"},
|
||||||
|
{Key: "type", Value: "switch"},
|
||||||
|
{Key: "span", Value: "left"},
|
||||||
|
{Key: "tab", Value: TabTypes},
|
||||||
|
}},
|
||||||
|
yaml.MapItem{Key: base + "slug", Value: yaml.MapSlice{
|
||||||
|
{Key: "label", Value: "golem15.sitemap::lang.settings.type_slug"},
|
||||||
|
{Key: "comment", Value: "golem15.sitemap::lang.settings.type_slug_comment"},
|
||||||
|
{Key: "type", Value: "text"},
|
||||||
|
{Key: "span", Value: "right"},
|
||||||
|
{Key: "tab", Value: TabTypes},
|
||||||
|
}},
|
||||||
|
yaml.MapItem{Key: base + "title", Value: yaml.MapSlice{
|
||||||
|
{Key: "label", Value: "golem15.sitemap::lang.settings.type_title"},
|
||||||
|
{Key: "comment", Value: "golem15.sitemap::lang.settings.type_title_comment"},
|
||||||
|
{Key: "type", Value: "mltext"},
|
||||||
|
{Key: "span", Value: "full"},
|
||||||
|
{Key: "tab", Value: TabTypes},
|
||||||
|
}},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
fields = append(fields, yaml.MapItem{Key: htmlPathField, Value: yaml.MapSlice{
|
||||||
|
{Key: "label", Value: "golem15.sitemap::lang.settings.html_path"},
|
||||||
|
{Key: "comment", Value: "golem15.sitemap::lang.settings.html_path_comment"},
|
||||||
|
{Key: "type", Value: "mltext"},
|
||||||
|
{Key: "span", Value: "left"},
|
||||||
|
{Key: "tab", Value: TabHTML},
|
||||||
|
{Key: "after", Value: "html_enabled"},
|
||||||
|
}})
|
||||||
|
doc := yaml.MapSlice{}
|
||||||
|
if len(types) > 0 {
|
||||||
|
doc = append(doc, yaml.MapItem{Key: "tabs", Value: []yaml.MapSlice{{{Key: "name", Value: TabTypes}, {Key: "after", Value: TabFiles}}}})
|
||||||
|
}
|
||||||
|
return yaml.Marshal(append(doc, yaml.MapItem{Key: "fields", Value: fields}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// typeSettingsTab is the plugin's form extension on its own settings
|
||||||
|
// controller: the Content types tab, loaded from and saved to
|
||||||
|
// golem15_sitemap_types, and the HTML sitemap address (html_paths).
|
||||||
|
func (p *Plugin) typeSettingsTab(types []pact.MenuItemType) *pact.AdminFormExtension {
|
||||||
|
doc, err := typeSettingsDocument(types)
|
||||||
|
if err != nil {
|
||||||
|
pluginLog.Error("golem15.sitemap: content types tab", "error", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &pact.AdminFormExtension{
|
||||||
|
FieldsYAML: doc,
|
||||||
|
Permissions: []string{controllers.PermissionAccessDefinitions},
|
||||||
|
Load: func(ctx context.Context, in pact.AdminFormLoad) (map[string]any, error) {
|
||||||
|
rows, err := classes.LoadTypeSettings(in.DB.WithContext(ctx))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out := map[string]any{}
|
||||||
|
for _, typ := range types {
|
||||||
|
cfg := classes.EffectiveType(typ, rows)
|
||||||
|
base := classes.TypeFieldBase(typ.Key)
|
||||||
|
out[base+"include"] = cfg.Include
|
||||||
|
out[base+"slug"] = cfg.Slug
|
||||||
|
// Only stored headings (L2 WR-05): a type without one loads
|
||||||
|
// empty, so a save that did not touch it stores none and each
|
||||||
|
// locale's HTML sitemap keeps the label translated into it.
|
||||||
|
titles := cfg.Titles
|
||||||
|
if titles == nil {
|
||||||
|
titles = map[string]string{}
|
||||||
|
}
|
||||||
|
out[base+"title"] = titles
|
||||||
|
}
|
||||||
|
settings, err := classes.LoadSettings(in.DB.WithContext(ctx))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
out[htmlPathField] = settings.EffectiveHTMLPaths()
|
||||||
|
return out, nil
|
||||||
|
},
|
||||||
|
Save: func(ctx context.Context, in pact.AdminFormSave) (pact.AdminFormSaveResult, error) {
|
||||||
|
if err := saveTypeSettings(ctx, in, types); err != nil {
|
||||||
|
return pact.AdminFormSaveResult{}, err
|
||||||
|
}
|
||||||
|
return pact.AdminFormSaveResult{}, saveHTMLPaths(in)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// saveTypeSettings stores the submitted Content types values
|
||||||
|
// (classes.SaveTypeSettings).
|
||||||
|
func saveTypeSettings(_ context.Context, in pact.AdminFormSave, types []pact.MenuItemType) error {
|
||||||
|
refusals, err := classes.SaveTypeSettings(in.DB, types, in.Values)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(refusals) > 0 {
|
||||||
|
return pact.AdminFormErrors(refusals)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// saveHTMLPaths stores a submitted HTML sitemap address: the locales sent
|
||||||
|
// replace theirs in html_paths (a blank one removes it), the others keep
|
||||||
|
// theirs. An address that models.ValidHTMLPath refuses is refused with
|
||||||
|
// errors.html_path.
|
||||||
|
func saveHTMLPaths(in pact.AdminFormSave) error {
|
||||||
|
raw, sent := in.Values[htmlPathField]
|
||||||
|
if !sent {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
paths := map[string]string{}
|
||||||
|
switch v := raw.(type) {
|
||||||
|
case map[string]string:
|
||||||
|
paths = v
|
||||||
|
case map[string]any:
|
||||||
|
for k, s := range v {
|
||||||
|
text, _ := s.(string)
|
||||||
|
paths[k] = text
|
||||||
|
}
|
||||||
|
}
|
||||||
|
merged, problem := classes.MergeHTMLPaths(in.DB, paths)
|
||||||
|
if problem {
|
||||||
|
return pact.AdminFormErrors{htmlPathField: {models.HTMLPathProblem}}
|
||||||
|
}
|
||||||
|
return classes.StoreHTMLPaths(in.DB, merged)
|
||||||
|
}
|
||||||
|
|
||||||
|
// translator returns the application's translator, nil when none.
|
||||||
|
func (p *Plugin) translator() *phrasebook.Translator {
|
||||||
|
if p == nil || p.app == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
tr, _ := p.app.Lookup[*phrasebook.Translator]()
|
||||||
|
return tr
|
||||||
|
}
|
||||||
|
|
||||||
|
// defaultLocale is the site's default content locale: the translation
|
||||||
|
// writer's default, else app.locale, else en.
|
||||||
|
func (p *Plugin) defaultLocale(ctx context.Context, db *gorm.DB) string {
|
||||||
|
if p != nil && p.app != nil {
|
||||||
|
if w, ok := p.app.Lookup[cabana.TranslationWriter](); ok && w != nil {
|
||||||
|
if code, err := w.DefaultLocale(ctx, db); err == nil && code != "" {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if p.app.Config != nil {
|
||||||
|
if code := strings.TrimSpace(p.app.Config.String("app.locale")); code != "" {
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "en"
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ pact.HasAdminActionExtensions = (*Plugin)(nil)
|
||||||
77
filter_fixture_test.go
Normal file
77
filter_fixture_test.go
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
package sitemap_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/contract"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/party"
|
||||||
|
)
|
||||||
|
|
||||||
|
// filterPluginID is a fake plugin that publishes a contract.Filter, as the
|
||||||
|
// SEO plugin does: it imports only the contract package.
|
||||||
|
const filterPluginID = "acme.filter"
|
||||||
|
|
||||||
|
// fakeFilter excludes addresses containing "noindex" (reason noindex) and
|
||||||
|
// puts addresses containing "promo" into the group offers. It records the
|
||||||
|
// batches it was asked; hook, when set, runs at the start of every Decide
|
||||||
|
// (a test blocks a rebuild there).
|
||||||
|
type fakeFilter struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
batches [][]contract.Candidate
|
||||||
|
hook func()
|
||||||
|
}
|
||||||
|
|
||||||
|
// setHook sets the Decide hook for one test.
|
||||||
|
func (f *fakeFilter) setHook(t interface{ Cleanup(func()) }, fn func()) {
|
||||||
|
f.mu.Lock()
|
||||||
|
f.hook = fn
|
||||||
|
f.mu.Unlock()
|
||||||
|
t.Cleanup(func() {
|
||||||
|
f.mu.Lock()
|
||||||
|
f.hook = nil
|
||||||
|
f.mu.Unlock()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeFilter) Decide(_ context.Context, batch []contract.Candidate) ([]contract.Decision, error) {
|
||||||
|
f.mu.Lock()
|
||||||
|
f.batches = append(f.batches, append([]contract.Candidate(nil), batch...))
|
||||||
|
hook := f.hook
|
||||||
|
f.mu.Unlock()
|
||||||
|
if hook != nil {
|
||||||
|
hook()
|
||||||
|
}
|
||||||
|
out := make([]contract.Decision, len(batch))
|
||||||
|
for i, c := range batch {
|
||||||
|
switch {
|
||||||
|
case strings.Contains(c.URL, "noindex"):
|
||||||
|
out[i] = contract.Decision{Exclude: true, Reason: contract.ReasonNoindex}
|
||||||
|
case strings.Contains(c.URL, "promo"):
|
||||||
|
out[i] = contract.Decision{Group: "offers"}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeFilter) Groups(context.Context) ([]contract.Group, error) {
|
||||||
|
return []contract.Group{{Key: "offers", Titles: map[string]string{"en": "Offers", "pl": "Oferty"}}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var theFilter = &fakeFilter{}
|
||||||
|
|
||||||
|
// filterPlugin is acme.filter.
|
||||||
|
type filterPlugin struct{}
|
||||||
|
|
||||||
|
func (filterPlugin) ID() string { return filterPluginID }
|
||||||
|
func (filterPlugin) Requires() []string { return nil }
|
||||||
|
func (filterPlugin) Register(app *backpack.App) error {
|
||||||
|
return app.Publish[contract.Filter](theFilter)
|
||||||
|
}
|
||||||
|
func (filterPlugin) Boot(*backpack.App) error { return nil }
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
party.Register(filterPlugin{})
|
||||||
|
}
|
||||||
17
go.mod
17
go.mod
@@ -3,8 +3,9 @@ module git.golem15.com/golem15/sm-sitemap-plugin
|
|||||||
go 1.27.0
|
go 1.27.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
git.golem15.com/golem15/summercms v0.4.0
|
git.golem15.com/golem15/summercms v0.6.1
|
||||||
github.com/go-gormigrate/gormigrate/v2 v2.1.7
|
github.com/go-gormigrate/gormigrate/v2 v2.1.7
|
||||||
|
github.com/goccy/go-yaml v1.19.2
|
||||||
github.com/jackc/pgx/v5 v5.10.0
|
github.com/jackc/pgx/v5 v5.10.0
|
||||||
github.com/testcontainers/testcontainers-go v0.44.0
|
github.com/testcontainers/testcontainers-go v0.44.0
|
||||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0
|
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0
|
||||||
@@ -14,7 +15,6 @@ require (
|
|||||||
require (
|
require (
|
||||||
charm.land/bubbles/v2 v2.2.1 // indirect
|
charm.land/bubbles/v2 v2.2.1 // indirect
|
||||||
charm.land/bubbletea/v2 v2.1.0 // indirect
|
charm.land/bubbletea/v2 v2.1.0 // indirect
|
||||||
charm.land/fang/v2 v2.0.1 // indirect
|
|
||||||
charm.land/huh/v2 v2.0.3 // indirect
|
charm.land/huh/v2 v2.0.3 // indirect
|
||||||
charm.land/lipgloss/v2 v2.0.6 // indirect
|
charm.land/lipgloss/v2 v2.0.6 // indirect
|
||||||
dario.cat/mergo v1.0.2 // indirect
|
dario.cat/mergo v1.0.2 // indirect
|
||||||
@@ -48,7 +48,6 @@ require (
|
|||||||
github.com/charmbracelet/harmonica v0.2.0 // indirect
|
github.com/charmbracelet/harmonica v0.2.0 // indirect
|
||||||
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 // indirect
|
github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 // indirect
|
||||||
github.com/charmbracelet/x/ansi v0.11.9 // indirect
|
github.com/charmbracelet/x/ansi v0.11.9 // indirect
|
||||||
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444 // indirect
|
|
||||||
github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect
|
github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect
|
||||||
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
|
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
|
||||||
github.com/charmbracelet/x/term v0.2.2 // indirect
|
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||||
@@ -77,8 +76,8 @@ require (
|
|||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/go-playground/validator/v10 v10.30.4 // indirect
|
github.com/go-playground/validator/v10 v10.30.4 // indirect
|
||||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||||
|
github.com/google/jsonschema-go v0.4.3 // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/google/wire v0.7.0 // indirect
|
github.com/google/wire v0.7.0 // indirect
|
||||||
github.com/googleapis/gax-go/v2 v2.19.0 // indirect
|
github.com/googleapis/gax-go/v2 v2.19.0 // indirect
|
||||||
@@ -116,11 +115,8 @@ require (
|
|||||||
github.com/moby/sys/user v0.4.0 // indirect
|
github.com/moby/sys/user v0.4.0 // indirect
|
||||||
github.com/moby/sys/userns v0.1.0 // indirect
|
github.com/moby/sys/userns v0.1.0 // indirect
|
||||||
github.com/moby/term v0.5.2 // indirect
|
github.com/moby/term v0.5.2 // indirect
|
||||||
|
github.com/modelcontextprotocol/go-sdk v1.8.0 // indirect
|
||||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||||
github.com/muesli/mango v0.1.0 // indirect
|
|
||||||
github.com/muesli/mango-cobra v1.2.0 // indirect
|
|
||||||
github.com/muesli/mango-pflag v0.1.0 // indirect
|
|
||||||
github.com/muesli/roff v0.1.0 // indirect
|
|
||||||
github.com/nicksnyder/go-i18n/v2 v2.6.1 // indirect
|
github.com/nicksnyder/go-i18n/v2 v2.6.1 // indirect
|
||||||
github.com/opencontainers/go-digest v1.0.0 // indirect
|
github.com/opencontainers/go-digest v1.0.0 // indirect
|
||||||
github.com/opencontainers/image-spec v1.1.1 // indirect
|
github.com/opencontainers/image-spec v1.1.1 // indirect
|
||||||
@@ -133,6 +129,8 @@ require (
|
|||||||
github.com/riverqueue/river/rivershared v0.47.0 // indirect
|
github.com/riverqueue/river/rivershared v0.47.0 // indirect
|
||||||
github.com/riverqueue/river/rivertype v0.47.0 // indirect
|
github.com/riverqueue/river/rivertype v0.47.0 // indirect
|
||||||
github.com/rivo/uniseg v0.4.7 // indirect
|
github.com/rivo/uniseg v0.4.7 // indirect
|
||||||
|
github.com/segmentio/asm v1.1.3 // indirect
|
||||||
|
github.com/segmentio/encoding v0.5.4 // indirect
|
||||||
github.com/shirou/gopsutil/v4 v4.26.6 // indirect
|
github.com/shirou/gopsutil/v4 v4.26.6 // indirect
|
||||||
github.com/sirupsen/logrus v1.9.4 // indirect
|
github.com/sirupsen/logrus v1.9.4 // indirect
|
||||||
github.com/spf13/cobra v1.10.2 // indirect
|
github.com/spf13/cobra v1.10.2 // indirect
|
||||||
@@ -146,6 +144,7 @@ require (
|
|||||||
github.com/tklauser/numcpus v0.12.0 // indirect
|
github.com/tklauser/numcpus v0.12.0 // indirect
|
||||||
github.com/wneessen/go-mail v0.8.1 // indirect
|
github.com/wneessen/go-mail v0.8.1 // indirect
|
||||||
github.com/xo/terminfo v1.0.0 // indirect
|
github.com/xo/terminfo v1.0.0 // indirect
|
||||||
|
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
|
||||||
github.com/yuin/goldmark v1.8.6 // indirect
|
github.com/yuin/goldmark v1.8.6 // indirect
|
||||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||||
@@ -161,10 +160,12 @@ require (
|
|||||||
golang.org/x/crypto v0.57.0 // indirect
|
golang.org/x/crypto v0.57.0 // indirect
|
||||||
golang.org/x/image v0.46.0 // indirect
|
golang.org/x/image v0.46.0 // indirect
|
||||||
golang.org/x/net v0.58.0 // indirect
|
golang.org/x/net v0.58.0 // indirect
|
||||||
|
golang.org/x/oauth2 v0.36.0 // indirect
|
||||||
golang.org/x/sync v0.23.0 // indirect
|
golang.org/x/sync v0.23.0 // indirect
|
||||||
golang.org/x/sys v0.48.0 // indirect
|
golang.org/x/sys v0.48.0 // indirect
|
||||||
golang.org/x/term v0.46.0 // indirect
|
golang.org/x/term v0.46.0 // indirect
|
||||||
golang.org/x/text v0.42.0 // indirect
|
golang.org/x/text v0.42.0 // indirect
|
||||||
|
golang.org/x/time v0.15.0 // indirect
|
||||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
|
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
|
||||||
google.golang.org/api v0.272.0 // indirect
|
google.golang.org/api v0.272.0 // indirect
|
||||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 // indirect
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20260316180232-0b37fe3546d5 // indirect
|
||||||
|
|||||||
24
go.sum
24
go.sum
@@ -4,8 +4,6 @@ charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU=
|
|||||||
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc=
|
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc=
|
||||||
charm.land/bubbletea/v2 v2.1.0 h1:A9fj9h5LFrvQhQHFNggp8K8rvY6CUfgn9dMbb6p2HIw=
|
charm.land/bubbletea/v2 v2.1.0 h1:A9fj9h5LFrvQhQHFNggp8K8rvY6CUfgn9dMbb6p2HIw=
|
||||||
charm.land/bubbletea/v2 v2.1.0/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
|
charm.land/bubbletea/v2 v2.1.0/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
|
||||||
charm.land/fang/v2 v2.0.1 h1:zQCM8JQJ1JnQX/66B5jlCYBUxL2as5JXQZ2KJ6EL0mY=
|
|
||||||
charm.land/fang/v2 v2.0.1/go.mod h1:S1GmkpcvK+OB5w9caywUnJcsMew45Ot8FXqoz8ALrII=
|
|
||||||
charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=
|
charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=
|
||||||
charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=
|
charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=
|
||||||
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
|
charm.land/lipgloss/v2 v2.0.6 h1:EaGKeuA8FvF+v2BT5VmZd2LoYLaMZJXA5n34th8nCIQ=
|
||||||
@@ -110,8 +108,6 @@ github.com/charmbracelet/x/conpty v0.1.1 h1:s1bUxjoi7EpqiXysVtC+a8RrvPPNcNvAjfi4
|
|||||||
github.com/charmbracelet/x/conpty v0.1.1/go.mod h1:OmtR77VODEFbiTzGE9G1XiRJAga6011PIm4u5fTNZpk=
|
github.com/charmbracelet/x/conpty v0.1.1/go.mod h1:OmtR77VODEFbiTzGE9G1XiRJAga6011PIm4u5fTNZpk=
|
||||||
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA=
|
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86 h1:JSt3B+U9iqk37QUU2Rvb6DSBYRLtWqFqfxf8l5hOZUA=
|
||||||
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0=
|
github.com/charmbracelet/x/errors v0.0.0-20240508181413-e8d8b6e2de86/go.mod h1:2P0UgXMEa6TsToMSuFqKFQR+fZTO9CNGUNokkPatT/0=
|
||||||
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444 h1:IJDiTgVE56gkAGfq0lBEloWgkXMk4hl/bmuPoicI4R0=
|
|
||||||
github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444/go.mod h1:T9jr8CzFpjhFVHjNjKwbAD7KwBNyFnj2pntAO7F2zw0=
|
|
||||||
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=
|
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA=
|
||||||
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I=
|
github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f/go.mod h1:IfZAMTHB6XkZSeXUqriemErjAWCCzT0LwjKFYCZyw0I=
|
||||||
github.com/charmbracelet/x/exp/ordered v0.1.0 h1:55/qLwjIh0gL0Vni+QAWk7T/qRVP6sBf+2agPBgnOFE=
|
github.com/charmbracelet/x/exp/ordered v0.1.0 h1:55/qLwjIh0gL0Vni+QAWk7T/qRVP6sBf+2agPBgnOFE=
|
||||||
@@ -203,6 +199,8 @@ github.com/google/go-replayers/grpcreplay v1.3.0 h1:1Keyy0m1sIpqstQmgz307zhiJ1pV
|
|||||||
github.com/google/go-replayers/grpcreplay v1.3.0/go.mod h1:v6NgKtkijC0d3e3RW8il6Sy5sqRVUwoQa4mHOGEy8DI=
|
github.com/google/go-replayers/grpcreplay v1.3.0/go.mod h1:v6NgKtkijC0d3e3RW8il6Sy5sqRVUwoQa4mHOGEy8DI=
|
||||||
github.com/google/go-replayers/httpreplay v1.2.0 h1:VM1wEyyjaoU53BwrOnaf9VhAyQQEEioJvFYxYcLRKzk=
|
github.com/google/go-replayers/httpreplay v1.2.0 h1:VM1wEyyjaoU53BwrOnaf9VhAyQQEEioJvFYxYcLRKzk=
|
||||||
github.com/google/go-replayers/httpreplay v1.2.0/go.mod h1:WahEFFZZ7a1P4VM1qEeHy+tME4bwyqPcwWbNlUI1Mcg=
|
github.com/google/go-replayers/httpreplay v1.2.0/go.mod h1:WahEFFZZ7a1P4VM1qEeHy+tME4bwyqPcwWbNlUI1Mcg=
|
||||||
|
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
|
||||||
|
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||||
github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc=
|
github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc=
|
||||||
github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0=
|
github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0=
|
||||||
github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
|
github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0=
|
||||||
@@ -293,16 +291,10 @@ github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g
|
|||||||
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
|
github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28=
|
||||||
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
||||||
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
|
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
|
||||||
|
github.com/modelcontextprotocol/go-sdk v1.8.0 h1:KIvahhYqwtbeniWVPs3TcXEA7b8jEtwfBpOTAI+Urx4=
|
||||||
|
github.com/modelcontextprotocol/go-sdk v1.8.0/go.mod h1:dL7u98E/zjJTGzEq+j30jQ8K2k1mb6LeAH4inEcSGts=
|
||||||
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
||||||
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
||||||
github.com/muesli/mango v0.1.0 h1:DZQK45d2gGbql1arsYA4vfg4d7I9Hfx5rX/GCmzsAvI=
|
|
||||||
github.com/muesli/mango v0.1.0/go.mod h1:5XFpbC8jY5UUv89YQciiXNlbi+iJgt29VDC5xbzrLL4=
|
|
||||||
github.com/muesli/mango-cobra v1.2.0 h1:DQvjzAM0PMZr85Iv9LIMaYISpTOliMEg+uMFtNbYvWg=
|
|
||||||
github.com/muesli/mango-cobra v1.2.0/go.mod h1:vMJL54QytZAJhCT13LPVDfkvCUJ5/4jNUKF/8NC2UjA=
|
|
||||||
github.com/muesli/mango-pflag v0.1.0 h1:UADqbYgpUyRoBja3g6LUL+3LErjpsOwaC9ywvBWe7Sg=
|
|
||||||
github.com/muesli/mango-pflag v0.1.0/go.mod h1:YEQomTxaCUp8PrbhFh10UfbhbQrM/xJ4i2PB8VTLLW0=
|
|
||||||
github.com/muesli/roff v0.1.0 h1:YD0lalCotmYuF5HhZliKWlIx7IEhiXeSfq7hNjFqGF8=
|
|
||||||
github.com/muesli/roff v0.1.0/go.mod h1:pjAHQM9hdUUwm/krAfrLGgJkXJ+YuhtsfZ42kieB2Ig=
|
|
||||||
github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ=
|
github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ=
|
||||||
github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA=
|
github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA=
|
||||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||||
@@ -333,6 +325,10 @@ github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUc
|
|||||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||||
|
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
|
||||||
|
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
|
||||||
|
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
|
||||||
|
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
|
||||||
github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs=
|
github.com/shirou/gopsutil/v4 v4.26.6 h1:Mzr/npDtQC/xpeEuQKHZt8Zo9CmPvhTj8nkR8w5TLDs=
|
||||||
github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
|
github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
|
||||||
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
|
github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w=
|
||||||
@@ -373,6 +369,8 @@ github.com/wneessen/go-mail v0.8.1 h1:tVcncj02/QySVFw3zr/kXOzZcuFQqBNT6K+Rbgm/pc
|
|||||||
github.com/wneessen/go-mail v0.8.1/go.mod h1:dWZ61zadzCIyvB4y1/YzC5O7MrbbzBfPkARmbosdf8w=
|
github.com/wneessen/go-mail v0.8.1/go.mod h1:dWZ61zadzCIyvB4y1/YzC5O7MrbbzBfPkARmbosdf8w=
|
||||||
github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY=
|
github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY=
|
||||||
github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
github.com/xo/terminfo v1.0.0/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||||
|
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||||
|
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||||
github.com/yuin/goldmark v1.8.6 h1:d0VcaP1sx9GkFVkoW+KtggpGi2KZ965i14b0+bDQST4=
|
github.com/yuin/goldmark v1.8.6 h1:d0VcaP1sx9GkFVkoW+KtggpGi2KZ965i14b0+bDQST4=
|
||||||
github.com/yuin/goldmark v1.8.6/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
github.com/yuin/goldmark v1.8.6/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
||||||
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
|
||||||
@@ -436,6 +434,8 @@ golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
|||||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||||
|
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
|
||||||
|
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
||||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY=
|
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY=
|
||||||
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
|
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
|
||||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||||
|
|||||||
229
import_test.go
229
import_test.go
@@ -6,54 +6,58 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/console"
|
"git.golem15.com/golem15/sm-sitemap-plugin/console"
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
"git.golem15.com/golem15/summercms/modules/signpost"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestImportWinter pins sitemap:import-winter on Postgres (D-12): type maps
|
// storedExtra reads the additional addresses of settings row 1.
|
||||||
// and drops with their report lines, the reference check, --theme with
|
func (e *sitemapEnv) storedExtra(t *testing.T) []models.ExtraURL {
|
||||||
// several exported definitions, --dry-run writing nothing, the refusal of a
|
t.Helper()
|
||||||
// second copy without --force and the replacement with it, the settings
|
s, err := classes.LoadSettings(e.gdb)
|
||||||
// upsert onto row 1 with PHP defaults for missing keys, and the refusals for
|
if err != nil {
|
||||||
// missing, empty and malformed exports.
|
t.Fatal(err)
|
||||||
func TestImportWinter(t *testing.T) {
|
|
||||||
e := bootSitemap(t)
|
|
||||||
ctx := context.Background()
|
|
||||||
reg, ok := e.app.Lookup[*signpost.Registry]()
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("signpost registry is not published")
|
|
||||||
}
|
}
|
||||||
|
return s.Extra()
|
||||||
|
}
|
||||||
|
|
||||||
|
// extraURLs lists the addresses of rows.
|
||||||
|
func extraURLs(rows []models.ExtraURL) string {
|
||||||
|
out := make([]string, 0, len(rows))
|
||||||
|
for _, r := range rows {
|
||||||
|
out = append(out, r.URL)
|
||||||
|
}
|
||||||
|
return strings.Join(out, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestImportWinter pins sitemap:import-winter on Postgres (D-32): the url
|
||||||
|
// items of a WinterCMS definition become the additional addresses (static
|
||||||
|
// and CMS page items through --page-url, types renamed by --map first),
|
||||||
|
// every other item is dropped and listed, --theme picks a definition,
|
||||||
|
// --dry-run writes nothing, stored addresses are replaced only with
|
||||||
|
// --force, and frontend_url and frontend_default_locale become site_url and
|
||||||
|
// default_locale while the PHP-parity keys are reported as ignored; missing,
|
||||||
|
// empty and malformed exports and an unsafe frontend_url are refused.
|
||||||
|
func TestImportWinter(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
ctx := context.Background()
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
row := func(id int, theme string, items string) string {
|
row := func(id int, theme string, items string) string {
|
||||||
quoted, _ := json.Marshal(items)
|
quoted, _ := json.Marshal(items)
|
||||||
return `{"id": ` + string(rune('0'+id)) + `, "theme": "` + theme + `", "data": ` + string(quoted) + "}\n"
|
return `{"id": ` + string(rune('0'+id)) + `, "theme": "` + theme + `", "data": ` + string(quoted) + "}\n"
|
||||||
}
|
}
|
||||||
items := `[{"type":"url","url":"/"},` +
|
items := `[{"type":"url","url":"/","changefreq":"always","priority":"1.0"},` +
|
||||||
`{"type":"old-posts","reference":null,"nesting":"1"},` +
|
`{"type":"blog-posts","reference":null,"nesting":"1","cmsPage":"blog/post"},` +
|
||||||
`{"type":"acme-post","reference":"7"},` +
|
`{"type":"acme-post","reference":"7"},` +
|
||||||
`{"type":"acme-post","reference":"8"},` +
|
|
||||||
`{"type":"gone-type","reference":"1"},` +
|
|
||||||
`{"type":"static-page","reference":"about"},` +
|
`{"type":"static-page","reference":"about"},` +
|
||||||
`{"type":"remove-me"}]`
|
`{"type":"cms-page","reference":"news"},` +
|
||||||
|
`{"type":"remove-me"},` +
|
||||||
|
`{"type":"url","url":"javascript://%0aalert(1)%0a//x"},` +
|
||||||
|
`{"type":"url","url":"/"}]`
|
||||||
defs := writeFile(t, dir, "definitions.jsonl", row(1, "main", items)+"\n"+row(2, "other", `[{"type":"url","url":"/other"}]`))
|
defs := writeFile(t, dir, "definitions.jsonl", row(1, "main", items)+"\n"+row(2, "other", `[{"type":"url","url":"/other"}]`))
|
||||||
stored := func(t *testing.T) []models.DefinitionItem {
|
|
||||||
t.Helper()
|
|
||||||
var rows []models.Definition
|
|
||||||
if err := e.gdb.Where("theme = ?", models.DefinitionTheme).Find(&rows).Error; err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(rows) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if len(rows) != 1 {
|
|
||||||
t.Fatalf("%d definitions", len(rows))
|
|
||||||
}
|
|
||||||
return rows[0].Items()
|
|
||||||
}
|
|
||||||
run := func(opts console.WinterOptions) (console.WinterReport, string, error) {
|
run := func(opts console.WinterOptions) (console.WinterReport, string, error) {
|
||||||
out, buf := testOutput()
|
out, buf := testOutput()
|
||||||
report, err := console.ImportWinterFiles(ctx, e.gdb, reg, opts, out)
|
report, err := console.ImportWinterFiles(ctx, e.gdb, opts, out)
|
||||||
return report, buf.String(), err
|
return report, buf.String(), err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,18 +80,22 @@ func TestImportWinter(t *testing.T) {
|
|||||||
t.Fatalf("%s: err = %v, want %q\n%s", name, err, tc.want, out)
|
t.Fatalf("%s: err = %v, want %q\n%s", name, err, tc.want, out)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if got := stored(t); got != nil {
|
if got := e.storedExtra(t); len(got) != 0 {
|
||||||
t.Fatalf("a refused import wrote %+v", got)
|
t.Fatalf("a refused import wrote %+v", got)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
opts := console.WinterOptions{DefinitionsFile: defs, Theme: "main", Maps: map[string]string{"old-posts": "acme-list", "remove-me": ""}}
|
opts := console.WinterOptions{DefinitionsFile: defs, Theme: "main", Maps: map[string]string{"remove-me": ""}, PageURLs: map[string]string{"news": "/news"}}
|
||||||
wantLines := []string{
|
wantLines := []string{
|
||||||
"item 1 (type 'old-posts'): type 'old-posts' mapped to 'acme-list'",
|
"item 1 (type 'blog-posts'): cmsPage 'blog/post' dropped (CMS pages are not supported)",
|
||||||
"item 3 (type 'acme-post', reference '8'): dropped (reference '8' is not among the current references of 'acme-post')",
|
"item 1 (type 'blog-posts'): dropped (the content types list their records themselves)",
|
||||||
"item 4 (type 'gone-type', reference '1'): dropped (type 'gone-type' is not registered; map it with --map gone-type=<type>)",
|
"item 2 (type 'acme-post', reference '7'): dropped (the content types list their records themselves)",
|
||||||
"item 5 (type 'static-page', reference 'about'): dropped (static and CMS page types are not supported)",
|
"item 3 (type 'static-page', reference 'about'): dropped (static and CMS page types are not supported)",
|
||||||
"item 6 (type 'remove-me'): dropped (mapped to nothing)",
|
"item 4 (type 'cms-page', reference 'news'): copied as an additional address '/news'",
|
||||||
|
"item 5 (type 'remove-me'): type 'remove-me' mapped to ''",
|
||||||
|
"item 5 (type 'remove-me'): dropped (mapped to nothing)",
|
||||||
|
"item 6 (type 'url', url 'javascript://%0aalert(1)%0a//x'): dropped (the url is not a path or an http(s) URL)",
|
||||||
|
"item 7 (type 'url', url '/'): dropped (address '/' is already listed)",
|
||||||
}
|
}
|
||||||
|
|
||||||
t.Run("dry run writes nothing", func(t *testing.T) {
|
t.Run("dry run writes nothing", func(t *testing.T) {
|
||||||
@@ -97,7 +105,7 @@ func TestImportWinter(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("dry run: %v\n%s", err, out)
|
t.Fatalf("dry run: %v\n%s", err, out)
|
||||||
}
|
}
|
||||||
if report.Kept != 3 || report.Dropped != 4 || report.Remapped != 2 {
|
if report.Kept != 2 || report.Dropped != 6 || report.Remapped != 2 {
|
||||||
t.Fatalf("report = %+v\n%s", report, out)
|
t.Fatalf("report = %+v\n%s", report, out)
|
||||||
}
|
}
|
||||||
for _, line := range wantLines {
|
for _, line := range wantLines {
|
||||||
@@ -105,10 +113,10 @@ func TestImportWinter(t *testing.T) {
|
|||||||
t.Errorf("output lacks %q:\n%s", line, out)
|
t.Errorf("output lacks %q:\n%s", line, out)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !strings.Contains(out, "Dry run: 3 items kept, 2 remapped, 4 dropped.") || !strings.Contains(out, "Dry run complete (no changes made).") {
|
if !strings.Contains(out, "Dry run: 2 items kept, 2 remapped, 6 dropped.") || !strings.Contains(out, "Dry run complete (no changes made).") {
|
||||||
t.Fatalf("dry run output:\n%s", out)
|
t.Fatalf("dry run output:\n%s", out)
|
||||||
}
|
}
|
||||||
if got := stored(t); got != nil {
|
if got := e.storedExtra(t); len(got) != 0 {
|
||||||
t.Fatalf("the dry run wrote %+v", got)
|
t.Fatalf("the dry run wrote %+v", got)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -118,32 +126,30 @@ func TestImportWinter(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("import: %v\n%s", err, out)
|
t.Fatalf("import: %v\n%s", err, out)
|
||||||
}
|
}
|
||||||
got := stored(t)
|
if got := extraURLs(e.storedExtra(t)); report.Kept != 2 || got != "/ /news" {
|
||||||
if report.Kept != 3 || len(got) != 3 || got[0].Type != "url" || got[1].Type != "acme-list" || !got[1].Nesting || got[2].Type != "acme-post" || models.Text(got[2].Reference) != "7" {
|
t.Fatalf("copied = %q (report %+v)", got, report)
|
||||||
t.Fatalf("copied = %+v (report %+v)", got, report)
|
|
||||||
}
|
}
|
||||||
if !strings.Contains(out, "Definition copied: 3 items kept, 2 remapped, 4 dropped.") || !strings.Contains(out, "theme 'main'") {
|
if !strings.Contains(out, "Definition copied: 2 items kept, 2 remapped, 6 dropped.") || !strings.Contains(out, "theme 'main'") {
|
||||||
t.Fatalf("output:\n%s", out)
|
t.Fatalf("output:\n%s", out)
|
||||||
}
|
}
|
||||||
other := console.WinterOptions{DefinitionsFile: defs, Theme: "other"}
|
other := console.WinterOptions{DefinitionsFile: defs, Theme: "other"}
|
||||||
if _, out, err := run(other); err == nil || !strings.Contains(err.Error(), "already has 3 items; rerun with --force") {
|
if _, out, err := run(other); err == nil || !strings.Contains(err.Error(), "already has 2 additional addresses; rerun with --force") {
|
||||||
t.Fatalf("second copy: %v\n%s", err, out)
|
t.Fatalf("second copy: %v\n%s", err, out)
|
||||||
}
|
}
|
||||||
// A dry run over existing items warns instead of failing.
|
|
||||||
dry := other
|
dry := other
|
||||||
dry.DryRun = true
|
dry.DryRun = true
|
||||||
if _, out, err := run(dry); err != nil || !strings.Contains(out, "already has 3 items") {
|
if _, out, err := run(dry); err != nil || !strings.Contains(out, "already has 2 additional addresses") {
|
||||||
t.Fatalf("dry run over items: %v\n%s", err, out)
|
t.Fatalf("dry run over addresses: %v\n%s", err, out)
|
||||||
}
|
}
|
||||||
if len(stored(t)) != 3 {
|
if got := extraURLs(e.storedExtra(t)); got != "/ /news" {
|
||||||
t.Fatal("a refused copy changed the definition")
|
t.Fatalf("a refused copy changed the addresses: %q", got)
|
||||||
}
|
}
|
||||||
other.Force = true
|
other.Force = true
|
||||||
if _, out, err := run(other); err != nil {
|
if _, out, err := run(other); err != nil {
|
||||||
t.Fatalf("--force: %v\n%s", err, out)
|
t.Fatalf("--force: %v\n%s", err, out)
|
||||||
}
|
}
|
||||||
if got := stored(t); len(got) != 1 || models.Text(got[0].URL) != "/other" {
|
if got := extraURLs(e.storedExtra(t)); got != "/other" {
|
||||||
t.Fatalf("after --force = %+v", got)
|
t.Fatalf("after --force = %q", got)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -152,70 +158,42 @@ func TestImportWinter(t *testing.T) {
|
|||||||
if _, out, err := run(console.WinterOptions{DefinitionsFile: raw, Force: true}); err != nil {
|
if _, out, err := run(console.WinterOptions{DefinitionsFile: raw, Force: true}); err != nil {
|
||||||
t.Fatalf("raw JSON data: %v\n%s", err, out)
|
t.Fatalf("raw JSON data: %v\n%s", err, out)
|
||||||
}
|
}
|
||||||
if got := stored(t); len(got) != 1 || models.Text(got[0].URL) != "/raw" {
|
if got := extraURLs(e.storedExtra(t)); got != "/raw" {
|
||||||
t.Fatalf("raw data = %+v", got)
|
t.Fatalf("raw data = %q", got)
|
||||||
}
|
}
|
||||||
null := writeFile(t, dir, "null.jsonl", `{"id":6,"theme":"t","data":null}`)
|
null := writeFile(t, dir, "null.jsonl", `{"id":6,"theme":"t","data":null}`)
|
||||||
if report, out, err := run(console.WinterOptions{DefinitionsFile: null, Force: true}); err != nil || report.Kept != 0 {
|
if report, out, err := run(console.WinterOptions{DefinitionsFile: null, Force: true}); err != nil || report.Kept != 0 {
|
||||||
t.Fatalf("null data: %+v %v\n%s", report, err, out)
|
t.Fatalf("null data: %+v %v\n%s", report, err, out)
|
||||||
}
|
}
|
||||||
if got := stored(t); len(got) != 0 {
|
if got := e.storedExtra(t); len(got) != 0 {
|
||||||
t.Fatalf("null data stored %+v", got)
|
t.Fatalf("null data stored %+v", got)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("url and pattern checks", func(t *testing.T) {
|
t.Run("settings", func(t *testing.T) {
|
||||||
bad := writeFile(t, dir, "bad-urls.jsonl", row(7, "t", `[{"type":"url","url":"javascript://%0aalert(1)%0a//x"},`+
|
first := writeFile(t, dir, "settings.json", `{"frontend_url":"https://www.example.test","frontend_default_locale":"pl","enable_priority_tiers":"1","priority_blog":0.7,"unknown":"x"}`)
|
||||||
`{"type":"url","url":"/ok"},`+
|
|
||||||
`{"type":"acme-post","reference":"7","urlPattern":"//evil.test/:slug"}]`))
|
|
||||||
report, out, err := run(console.WinterOptions{DefinitionsFile: bad, Force: true})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("import: %v\n%s", err, out)
|
|
||||||
}
|
|
||||||
if report.Kept != 2 || report.Dropped != 1 {
|
|
||||||
t.Fatalf("report = %+v\n%s", report, out)
|
|
||||||
}
|
|
||||||
for _, line := range []string{
|
|
||||||
"item 0 (type 'url', url 'javascript://%0aalert(1)%0a//x'): dropped (the url is not a path or an http(s) URL)",
|
|
||||||
"item 2 (type 'acme-post', reference '7'): urlPattern '//evil.test/:slug' cleared (not a path starting with a single /)",
|
|
||||||
} {
|
|
||||||
if !strings.Contains(out, line) {
|
|
||||||
t.Errorf("output lacks %q:\n%s", line, out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
got := stored(t)
|
|
||||||
if len(got) != 2 || models.Text(got[0].URL) != "/ok" || got[1].URLPattern != nil {
|
|
||||||
t.Fatalf("stored = %+v", got)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("settings upsert", func(t *testing.T) {
|
|
||||||
first := writeFile(t, dir, "settings.json", `{"frontend_url":"https://www.example.test","enable_priority_tiers":"1","priority_blog":0.7,"unknown":"x"}`)
|
|
||||||
report, out, err := run(console.WinterOptions{SettingsFile: first})
|
report, out, err := run(console.WinterOptions{SettingsFile: first})
|
||||||
if err != nil || !report.Settings || !strings.Contains(out, "setting 'unknown' ignored") || !strings.Contains(out, "Settings copied.") {
|
if err != nil || !report.Settings || !strings.Contains(out, "setting 'unknown' ignored (not a sitemap setting of this port)") ||
|
||||||
|
!strings.Contains(out, "setting 'priority_blog' ignored (the per-type sitemaps do not use it)") || !strings.Contains(out, "Settings copied.") {
|
||||||
t.Fatalf("settings: %+v %v\n%s", report, err, out)
|
t.Fatalf("settings: %+v %v\n%s", report, err, out)
|
||||||
}
|
}
|
||||||
second := writeFile(t, dir, "settings2.json", `"{\"frontend_url\":\"https://other.example.test\",\"enable_priority_tiers\":\"0\"}"`)
|
s, err := classes.LoadSettings(e.gdb)
|
||||||
|
if err != nil || models.Text(s.SiteURL) != "https://www.example.test" || models.Text(s.DefaultLocale) != "pl" {
|
||||||
|
t.Fatalf("copied settings = %+v %v", s, err)
|
||||||
|
}
|
||||||
|
second := writeFile(t, dir, "settings2.json", `"{\"frontend_url\":\"https://other.example.test\"}"`)
|
||||||
if _, out, err := run(console.WinterOptions{SettingsFile: second}); err != nil {
|
if _, out, err := run(console.WinterOptions{SettingsFile: second}); err != nil {
|
||||||
t.Fatalf("second settings: %v\n%s", err, out)
|
t.Fatalf("second settings: %v\n%s", err, out)
|
||||||
}
|
}
|
||||||
var rows []models.Settings
|
if s, _ = classes.LoadSettings(e.gdb); models.Text(s.SiteURL) != "https://other.example.test" || s.DefaultLocale != nil {
|
||||||
if err := e.gdb.Find(&rows).Error; err != nil {
|
t.Fatalf("second settings = %+v", s)
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(rows) != 1 || rows[0].ID != 1 || models.Text(rows[0].FrontendURL) != "https://other.example.test" || rows[0].EnablePriorityTiers || rows[0].Priority(models.PriorityBlog) != "0.6" {
|
|
||||||
t.Fatalf("settings rows = %+v", rows)
|
|
||||||
}
|
}
|
||||||
dry := writeFile(t, dir, "settings3.json", `{"frontend_url":"https://dry.example.test"}`)
|
dry := writeFile(t, dir, "settings3.json", `{"frontend_url":"https://dry.example.test"}`)
|
||||||
if _, out, err := run(console.WinterOptions{SettingsFile: dry, DryRun: true}); err != nil || !strings.Contains(out, "Dry run: the settings would be copied.") {
|
if _, out, err := run(console.WinterOptions{SettingsFile: dry, DryRun: true}); err != nil || !strings.Contains(out, "Dry run: the settings would be copied.") {
|
||||||
t.Fatalf("settings dry run: %v\n%s", err, out)
|
t.Fatalf("settings dry run: %v\n%s", err, out)
|
||||||
}
|
}
|
||||||
if err := e.gdb.Find(&rows).Error; err != nil || models.Text(rows[0].FrontendURL) != "https://other.example.test" {
|
// T-17-15: an unsafe frontend_url stops the import, also as a dry
|
||||||
t.Fatalf("the dry run changed the settings: %+v %v", rows, err)
|
// run, and the row keeps its value.
|
||||||
}
|
|
||||||
|
|
||||||
// T-17-15: a frontend_url that is not a plain http(s) URL stops the
|
|
||||||
// import, also as a dry run, and the row keeps its value.
|
|
||||||
quoted, _ := json.Marshal(map[string]string{"frontend_url": `https://x"/><y a="`})
|
quoted, _ := json.Marshal(map[string]string{"frontend_url": `https://x"/><y a="`})
|
||||||
unsafe := writeFile(t, dir, "settings4.json", string(quoted))
|
unsafe := writeFile(t, dir, "settings4.json", string(quoted))
|
||||||
for _, dryRun := range []bool{false, true} {
|
for _, dryRun := range []bool{false, true} {
|
||||||
@@ -223,9 +201,56 @@ func TestImportWinter(t *testing.T) {
|
|||||||
if err == nil || !strings.Contains(err.Error(), "frontend_url") || report.Settings {
|
if err == nil || !strings.Contains(err.Error(), "frontend_url") || report.Settings {
|
||||||
t.Fatalf("unsafe frontend_url (dry run %v): %+v %v\n%s", dryRun, report, err, out)
|
t.Fatalf("unsafe frontend_url (dry run %v): %+v %v\n%s", dryRun, report, err, out)
|
||||||
}
|
}
|
||||||
if err := e.gdb.Find(&rows).Error; err != nil || len(rows) != 1 || models.Text(rows[0].FrontendURL) != "https://other.example.test" {
|
}
|
||||||
t.Fatalf("a refused import (dry run %v) changed the settings: %+v %v", dryRun, rows, err)
|
if s, _ = classes.LoadSettings(e.gdb); models.Text(s.SiteURL) != "https://other.example.test" {
|
||||||
}
|
t.Fatalf("a refused or dry import changed the settings: %+v", s)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestImportFile pins sitemap:import: a JSON list of addresses replaces the
|
||||||
|
// additional addresses (or is appended, skipping listed ones), lastmod is
|
||||||
|
// kept, changefreq and priority are ignored, and a missing url, an unsafe
|
||||||
|
// url or a bad lastmod stops the import before anything is written.
|
||||||
|
func TestImportFile(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
dir := t.TempDir()
|
||||||
|
manifest := writeFile(t, dir, "urls.json", `[{"url":"/x","changefreq":"daily","lastmod":"2026-10-01"},{"url":"/y","priority":"0.9"}]`)
|
||||||
|
out, buf := testOutput()
|
||||||
|
if err := console.ImportFile(ctx, e.gdb, manifest, "", false, out); err != nil {
|
||||||
|
t.Fatalf("sitemap:import: %v", err)
|
||||||
|
}
|
||||||
|
got := e.storedExtra(t)
|
||||||
|
if extraURLs(got) != "/x /y" || got[0].LastMod != "2026-10-01" || got[1].LastMod != "" {
|
||||||
|
t.Fatalf("imported = %+v", got)
|
||||||
|
}
|
||||||
|
if !strings.Contains(buf.String(), "Imported 2 addresses into the sitemap's additional addresses.") {
|
||||||
|
t.Fatalf("output:\n%s", buf.String())
|
||||||
|
}
|
||||||
|
more := writeFile(t, dir, "more.json", `[{"url":"/y"},{"url":"https://www.example.test/z"}]`)
|
||||||
|
out, buf = testOutput()
|
||||||
|
if err := console.ImportFile(ctx, e.gdb, more, "main", true, out); err != nil {
|
||||||
|
t.Fatalf("--append: %v", err)
|
||||||
|
}
|
||||||
|
if got := extraURLs(e.storedExtra(t)); got != "/x /y https://www.example.test/z" {
|
||||||
|
t.Fatalf("appended = %q", got)
|
||||||
|
}
|
||||||
|
if !strings.Contains(buf.String(), "Imported 1 addresses") || !strings.Contains(buf.String(), "Kept 2 existing addresses.") || !strings.Contains(buf.String(), "Theme 'main' was given") {
|
||||||
|
t.Fatalf("--append output:\n%s", buf.String())
|
||||||
|
}
|
||||||
|
for name, c := range map[string]struct{ body, want string }{
|
||||||
|
"missing url": {`[{"url":"/a"},{"changefreq":"daily"}]`, "Entry 1 is missing a 'url' field"},
|
||||||
|
"unsafe url": {`[{"url":"javascript:alert(1)"}]`, "Entry 0 has a url that is not a path or an http(s) URL"},
|
||||||
|
"bad lastmod": {`[{"url":"/a","lastmod":"soon"}]`, "Entry 0 has a lastmod that is not a date"},
|
||||||
|
"not a list": {`5`, "Invalid JSON"},
|
||||||
|
} {
|
||||||
|
file := writeFile(t, dir, strings.ReplaceAll(name, " ", "-")+".json", c.body)
|
||||||
|
if err := console.ImportFile(ctx, e.gdb, file, "", false, out); err == nil || !strings.Contains(err.Error(), c.want) {
|
||||||
|
t.Fatalf("%s: %v", name, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := extraURLs(e.storedExtra(t)); got != "/x /y https://www.example.test/z" {
|
||||||
|
t.Fatalf("a refused import changed the addresses: %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
38
jobs.go
Normal file
38
jobs.go
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
package sitemap
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/conga"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Jobs registers the rebuild job (classes.RebuildKind) and the IndexNow
|
||||||
|
// job (classes.IndexNowKind, five attempts: 429 and 5xx answers retry) on
|
||||||
|
// conga.
|
||||||
|
func (p *Plugin) Jobs() []pact.Job {
|
||||||
|
return []pact.Job{
|
||||||
|
conga.Job(p.rebuild, conga.MaxAttempts(3)),
|
||||||
|
conga.Job(p.indexNow, conga.MaxAttempts(classes.IndexNowAttempts)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// indexNow sends one IndexNow request (classes.SendIndexNow).
|
||||||
|
func (p *Plugin) indexNow(ctx context.Context, args classes.IndexNowArgs) error {
|
||||||
|
return classes.SendIndexNow(ctx, p.app, args)
|
||||||
|
}
|
||||||
|
|
||||||
|
// rebuild runs one rebuild of the slot table. It ends the debounce window
|
||||||
|
// first, so record events during the rebuild queue the next one.
|
||||||
|
func (p *Plugin) rebuild(ctx context.Context, _ classes.RebuildArgs) error {
|
||||||
|
if err := classes.ClearPending(ctx, p.app); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
res, err := classes.Rebuild(ctx, p.app)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
pluginLog.Info("golem15.sitemap: rebuilt", "listed", res.Listed, "files", res.Files, "added", len(res.Added), "changed", len(res.Changed), "removed", len(res.Removed))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -1,69 +1,92 @@
|
|||||||
plugin:
|
plugin:
|
||||||
name: Sitemap
|
name: Sitemap
|
||||||
description: Generate a sitemap.xml file for your website.
|
description: XML sitemaps per content type, with stable files, real lastmod and hreflang.
|
||||||
permissions:
|
permissions:
|
||||||
access_settings: Access sitemap configuration settings
|
access_definitions: Manage the sitemap settings
|
||||||
access_definitions: Access sitemap definitions page
|
|
||||||
item:
|
|
||||||
location: 'Location:'
|
|
||||||
priority: Priority
|
|
||||||
changefreq: Change frequency
|
|
||||||
always: always
|
|
||||||
hourly: hourly
|
|
||||||
daily: daily
|
|
||||||
weekly: weekly
|
|
||||||
monthly: monthly
|
|
||||||
yearly: yearly
|
|
||||||
never: never
|
|
||||||
editor_title: Edit Sitemap Item
|
|
||||||
type: Type
|
|
||||||
allow_nested_items: Allow nested items
|
|
||||||
allow_nested_items_comment: Nested items could be generated dynamically by static page and some other item types
|
|
||||||
url: URL
|
|
||||||
reference: Reference
|
|
||||||
title_required: The title is required
|
|
||||||
unknown_type: Unknown item type
|
|
||||||
unnamed: Unnamed item
|
|
||||||
add_item: Add item
|
|
||||||
new_item: New item
|
|
||||||
reference_required: The item reference is required.
|
|
||||||
url_required: The URL is required
|
|
||||||
url_pattern: URL Pattern
|
|
||||||
url_pattern_comment: Use :placeholder syntax, e.g. /blog/:slug
|
|
||||||
url_pattern_required: Please enter a URL pattern
|
|
||||||
page: Page
|
|
||||||
check: Check
|
|
||||||
definition: Definition
|
|
||||||
save_definition: Saving Definition...
|
|
||||||
load_indicator: Emptying Definition...
|
|
||||||
empty_confirm: Empty this definition?
|
|
||||||
errors:
|
errors:
|
||||||
url_scheme: Use a path such as /about, or a link that starts with http:// or https://.
|
url_scheme: Use a path such as /about, or a link that starts with http:// or https://.
|
||||||
url_pattern: Use a path that starts with a single /, for example /blog/:slug.
|
|
||||||
frontend_url: 'Use a full address that starts with http:// or https://, without spaces, quotes or the characters < > &. Leave it empty to keep the backend URL.'
|
frontend_url: 'Use a full address that starts with http:// or https://, without spaces, quotes or the characters < > &. Leave it empty to keep the backend URL.'
|
||||||
definition:
|
file_size: Enter a whole number from 1 to 50 000.
|
||||||
not_found: No sitemap definition was found. Try creating one first.
|
slug: Use lowercase letters, digits and hyphens, e.g. posts.
|
||||||
title: Sitemap definition
|
slug_taken: Another content type already uses this file name.
|
||||||
view: View sitemap.xml
|
html_path: Start the address with / and use a path only, e.g. /mapa-strony.
|
||||||
|
page_size: Enter a whole number from 50 to 500.
|
||||||
|
lastmod: 'Enter a date as YYYY-MM-DD, e.g. 2026-10-28, or leave it empty.'
|
||||||
|
news_publication: Enter at most 255 characters, without line breaks.
|
||||||
|
news_source: 'Use the values listed under the field: type:<type key> or category:<type key>:<id>.'
|
||||||
|
type_unknown: There is no content type with this key.
|
||||||
settings:
|
settings:
|
||||||
label: Sitemap settings
|
label: Sitemaps
|
||||||
description: Frontend URL, locale and priority options.
|
description: XML sitemaps per content type, images, News, IndexNow and the HTML sitemap.
|
||||||
category: CMS
|
category: CMS
|
||||||
frontend_url: Frontend URL
|
tab_files: Files
|
||||||
frontend_url_comment: The public URL of the frontend app (e.g. https://www.example.com). When set, sitemap URLs use this domain instead of the backend URL.
|
tab_types: Content types
|
||||||
frontend_default_locale: Frontend Default Locale
|
tab_extra: Additional addresses
|
||||||
frontend_default_locale_comment: The unprefixed locale on the frontend (e.g. pl for a prefix_except_default strategy). Other locales get a /{code}/ prefix in sitemap URLs.
|
tab_media: Images and News
|
||||||
updates_manifest_path: Updates Manifest Path
|
tab_indexnow: IndexNow
|
||||||
updates_manifest_path_comment: Absolute path to a JSON file mapping URL path => ISO 8601 last-modified date, produced by the frontend build. Used as the <lastmod> for URL items that have no date of their own (e.g. static pages). When empty or unreadable, those items omit <lastmod>. Dynamic sets keep their own dates.
|
tab_html: HTML sitemap
|
||||||
enable_priority_tiers: Enable Priority Tiers
|
site_url: Site address
|
||||||
enable_priority_tiers_comment: When enabled, priorities are auto-assigned based on the URL path rules in the config, overriding per-item priorities. When disabled, per-item priorities are used.
|
site_url_comment: The public address of the site, e.g. https://www.example.com. Every address in the sitemaps starts with it.
|
||||||
priority_homepage: Homepage Priority
|
file_size: Addresses per file
|
||||||
priority_homepage_comment: Used for URLs that match the homepage tier rules in the config. Default 1.0. Applies only when priority tiers are enabled.
|
file_size_comment: 1000 by default, at most 50 000. Smaller files are easier to monitor one by one in Google Search Console. A change renumbers every file.
|
||||||
priority_services: Services & Work Priority
|
type_include: Include this content type in the sitemaps.
|
||||||
priority_services_comment: Used for URLs that match the services tier rules in the config. Default 0.8. Applies only when priority tiers are enabled.
|
type_slug: File name
|
||||||
priority_blog: Blog Posts Priority
|
type_slug_comment: Files are named sitemap-<name>-1.xml, sitemap-<name>-2.xml and so on.
|
||||||
priority_blog_comment: Used for URLs that match the blog tier rules in the config. Default 0.6. Applies only when priority tiers are enabled.
|
type_title: Heading in the HTML sitemap
|
||||||
priority_categories: Categories & Hub Pages Priority
|
type_title_comment: "Leave empty to show the content type's name in each language's HTML sitemap."
|
||||||
priority_categories_comment: Used for URLs that match the categories tier rules in the config. Default 0.4. Applies only when priority tiers are enabled.
|
extra_urls: Additional addresses
|
||||||
priority_legal: Legal Pages Priority
|
extra_urls_add: Add address
|
||||||
priority_legal_comment: Used for URLs that match the legal tier rules in the config. Default 0.2. Applies only when priority tiers are enabled.
|
extra_urls_comment: Addresses that no content type lists, e.g. the site's static pages. They go into the sitemap-pages files.
|
||||||
|
extra_url: Address
|
||||||
|
extra_url_lastmod: Last modified
|
||||||
|
extra_url_lastmod_comment: 'Optional, as YYYY-MM-DD, e.g. 2026-10-28.'
|
||||||
|
images_enabled: Image sitemap
|
||||||
|
images_enabled_comment: Lists the featured image and the images in the content of every listed page, in the sitemap-images files.
|
||||||
|
news_enabled: Google News sitemap
|
||||||
|
news_enabled_comment: Only for sites accepted in Google News. Lists articles published in the last two days.
|
||||||
|
news_publication: Publication name
|
||||||
|
news_publication_comment: 'As registered in Google News. Empty: the site name.'
|
||||||
|
news_sources: Types and categories
|
||||||
|
news_sources_comment: 'Articles of these types or categories go into the News sitemap. Empty: every article type.'
|
||||||
|
indexnow_enabled: IndexNow
|
||||||
|
indexnow_enabled_comment: Tells Bing, Yandex and other IndexNow engines about new, changed and deleted addresses right away. Google does not use IndexNow.
|
||||||
|
indexnow_new_key: Generate a new key on save
|
||||||
|
indexnow_new_key_comment: The old key file stops working at once. Use it only when the key leaked.
|
||||||
|
html_enabled: HTML sitemap
|
||||||
|
html_enabled_comment: A page for visitors that lists every indexable address, linked from the site footer.
|
||||||
|
html_path: Address
|
||||||
|
html_path_comment: The site's sitemap page uses this address. Change it in the site as well.
|
||||||
|
html_page_size: Links per page
|
||||||
|
html_page_size_comment: Larger groups are split into numbered pages. Default 150.
|
||||||
|
files:
|
||||||
|
label: Files
|
||||||
|
file: File
|
||||||
|
file_urls: Addresses
|
||||||
|
file_lastmod: Last modified
|
||||||
|
left_out: Left out of the sitemaps
|
||||||
|
left_out_reason: Reason
|
||||||
|
left_out_count: Addresses
|
||||||
|
reason_noindex: noindex
|
||||||
|
reason_canonical: Canonical URL points elsewhere
|
||||||
|
reason_redirect: Address redirects
|
||||||
|
reason_type: Content type turned off
|
||||||
|
reason_duplicate: Already listed by a content type
|
||||||
|
index_note: Search engines read the index at :url, and robots.txt points to it. The files are rebuilt after content changes and every night; saving this form rebuilds them now.
|
||||||
|
empty: No files yet. They are built within a few minutes after the first save.
|
||||||
|
building: Rebuilding now. Reload the page in a minute.
|
||||||
|
news:
|
||||||
|
sources: Values for Types and categories
|
||||||
|
source_value: Value
|
||||||
|
source_label: Articles
|
||||||
|
source_type: 'Every article of :type'
|
||||||
|
none: No content type publishes articles yet.
|
||||||
|
indexnow:
|
||||||
|
key: 'Key: :key, served at :url'
|
||||||
|
no_key: A key is generated when you turn IndexNow on and save.
|
||||||
|
last: 'Last notification: :time, :count addresses, answer :status.'
|
||||||
|
never: No notification sent yet.
|
||||||
|
err_key: The engines could not read the key file at :url. Check that the site serves it.
|
||||||
|
err_host: The engines refused the addresses because they do not match the site address.
|
||||||
|
err_rate: 'Too many notifications; the next attempt is at :time.'
|
||||||
|
jobs:
|
||||||
|
rebuild: Rebuild the sitemaps
|
||||||
|
|||||||
@@ -1,69 +1,92 @@
|
|||||||
plugin:
|
plugin:
|
||||||
name: Mapa strony
|
name: Mapy witryny
|
||||||
description: Generuje plik sitemap.xml dla Twojej strony.
|
description: Mapy XML według typów treści, ze stałymi plikami, prawdziwym lastmod i hreflang.
|
||||||
permissions:
|
permissions:
|
||||||
access_settings: Zarządzaj ustawieniami wtyczki
|
access_definitions: Zarządzaj ustawieniami map witryny
|
||||||
access_definitions: Zarządzaj definicją mapy strony
|
|
||||||
item:
|
|
||||||
location: 'Lokacja:'
|
|
||||||
priority: Priorytet
|
|
||||||
changefreq: Częstotliwość zmian
|
|
||||||
always: cały czas
|
|
||||||
hourly: co godzinę
|
|
||||||
daily: codziennie
|
|
||||||
weekly: co tydzień
|
|
||||||
monthly: co miesiąc
|
|
||||||
yearly: co rok
|
|
||||||
never: nigdy
|
|
||||||
editor_title: Edytuj pozycję mapy
|
|
||||||
type: Typ
|
|
||||||
allow_nested_items: Pozwól na zagnieżdżanie pozycji
|
|
||||||
allow_nested_items_comment: Zagnieżdżone pozycje mogą zostać wygenerowane dynamicznie przez statyczne strony i niektóre rodzaje typów pozycji.
|
|
||||||
url: URL
|
|
||||||
reference: Odnośnik
|
|
||||||
title_required: Tytuł jest wymagany
|
|
||||||
unknown_type: Nieznany typ pozycji
|
|
||||||
unnamed: Pozycja bez nazwy
|
|
||||||
add_item: Dodaj pozycję
|
|
||||||
new_item: Nowa pozycja
|
|
||||||
reference_required: Odnośnik dla pozycji jest wymagany.
|
|
||||||
url_required: Adres URL jest wymagany
|
|
||||||
url_pattern: Wzorzec URL
|
|
||||||
url_pattern_comment: Użyj składni :placeholder, np. /blog/:slug
|
|
||||||
url_pattern_required: Podaj wzorzec URL
|
|
||||||
page: Strona
|
|
||||||
check: Sprawdź
|
|
||||||
definition: Definicja
|
|
||||||
save_definition: Zapisywanie definicji...
|
|
||||||
load_indicator: Czyszczenie definicji...
|
|
||||||
empty_confirm: Wyczyścić tę definicję?
|
|
||||||
errors:
|
errors:
|
||||||
url_scheme: Podaj ścieżkę, np. /o-nas, albo link zaczynający się od http:// lub https://.
|
url_scheme: Podaj ścieżkę, np. /o-nas, albo link zaczynający się od http:// lub https://.
|
||||||
url_pattern: Podaj ścieżkę zaczynającą się od jednego /, np. /blog/:slug.
|
|
||||||
frontend_url: 'Podaj pełny adres zaczynający się od http:// lub https://, bez spacji, cudzysłowów i znaków < > &. Zostaw puste, aby zachować adres backendu.'
|
frontend_url: 'Podaj pełny adres zaczynający się od http:// lub https://, bez spacji, cudzysłowów i znaków < > &. Zostaw puste, aby zachować adres backendu.'
|
||||||
definition:
|
file_size: Wpisz liczbę całkowitą od 1 do 50 000.
|
||||||
not_found: Nie znaleziono definicji mapy strony. Musisz ją utworzyć.
|
slug: Użyj małych liter, cyfr i łączników, np. posts.
|
||||||
title: Definicja mapy strony
|
slug_taken: Inny typ treści już używa tej nazwy pliku.
|
||||||
view: Zobacz sitemap.xml
|
html_path: Zacznij adres od / i użyj samej ścieżki, np. /mapa-strony.
|
||||||
|
page_size: Wpisz liczbę całkowitą od 50 do 500.
|
||||||
|
lastmod: 'Wpisz datę w formacie RRRR-MM-DD, np. 2026-10-28, albo zostaw puste.'
|
||||||
|
news_publication: Wpisz najwyżej 255 znaków, bez podziału wiersza.
|
||||||
|
news_source: 'Użyj wartości z listy pod polem: type:<klucz typu> albo category:<klucz typu>:<id>.'
|
||||||
|
type_unknown: Nie ma typu treści o tym kluczu.
|
||||||
settings:
|
settings:
|
||||||
label: Ustawienia mapy strony
|
label: Mapy witryny
|
||||||
description: Adres frontendu, język i priorytety.
|
description: Mapy XML według typów treści, obrazy, News, IndexNow i mapa HTML.
|
||||||
category: CMS
|
category: CMS
|
||||||
frontend_url: Adres URL frontendu
|
tab_files: Pliki
|
||||||
frontend_url_comment: Publiczny adres aplikacji frontendowej (np. https://www.example.com). Gdy jest ustawiony, adresy w mapie strony używają tej domeny zamiast adresu backendu.
|
tab_types: Typy treści
|
||||||
frontend_default_locale: Domyślny język frontendu
|
tab_extra: Dodatkowe adresy
|
||||||
frontend_default_locale_comment: Język bez prefiksu na frontendzie (np. pl przy strategii prefix_except_default). Pozostałe języki dostają w mapie strony prefiks /{kod}/.
|
tab_media: Obrazy i News
|
||||||
updates_manifest_path: Ścieżka manifestu aktualizacji
|
tab_indexnow: IndexNow
|
||||||
updates_manifest_path_comment: Bezwzględna ścieżka do pliku JSON, który mapuje ścieżkę URL na datę ostatniej zmiany ISO 8601, tworzonego przez build frontendu. Służy jako <lastmod> dla pozycji URL bez własnej daty (np. stron statycznych). Gdy jest pusta lub plik jest nieczytelny, te pozycje nie mają <lastmod>. Zestawy dynamiczne zachowują własne daty.
|
tab_html: Mapa HTML
|
||||||
enable_priority_tiers: Włącz poziomy priorytetów
|
site_url: Adres witryny
|
||||||
enable_priority_tiers_comment: Po włączeniu priorytety są nadawane według reguł ścieżek URL z konfiguracji i zastępują priorytety pozycji. Po wyłączeniu używane są priorytety pozycji.
|
site_url_comment: Publiczny adres witryny, np. https://www.example.com. Od niego zaczyna się każdy adres w mapach.
|
||||||
priority_homepage: Priorytet strony głównej
|
file_size: Adresów w pliku
|
||||||
priority_homepage_comment: Dla adresów pasujących do reguł poziomu strony głównej z konfiguracji. Domyślnie 1.0. Działa tylko przy włączonych poziomach priorytetów.
|
file_size_comment: Domyślnie 1000, najwyżej 50 000. Mniejsze pliki łatwiej monitorować pojedynczo w Google Search Console. Zmiana przenumerowuje wszystkie pliki.
|
||||||
priority_services: Priorytet usług i realizacji
|
type_include: Uwzględniaj ten typ treści w mapach witryny.
|
||||||
priority_services_comment: Dla adresów pasujących do reguł poziomu usług z konfiguracji. Domyślnie 0.8. Działa tylko przy włączonych poziomach priorytetów.
|
type_slug: Nazwa pliku
|
||||||
priority_blog: Priorytet wpisów bloga
|
type_slug_comment: Pliki nazywają się sitemap-<nazwa>-1.xml, sitemap-<nazwa>-2.xml i tak dalej.
|
||||||
priority_blog_comment: Dla adresów pasujących do reguł poziomu bloga z konfiguracji. Domyślnie 0.6. Działa tylko przy włączonych poziomach priorytetów.
|
type_title: Nagłówek grupy w mapie HTML
|
||||||
priority_categories: Priorytet kategorii i stron zbiorczych
|
type_title_comment: "Puste pole: mapa HTML w każdym języku pokazuje nazwę typu treści w tym języku."
|
||||||
priority_categories_comment: Dla adresów pasujących do reguł poziomu kategorii z konfiguracji. Domyślnie 0.4. Działa tylko przy włączonych poziomach priorytetów.
|
extra_urls: Dodatkowe adresy
|
||||||
priority_legal: Priorytet stron prawnych
|
extra_urls_add: Dodaj adres
|
||||||
priority_legal_comment: Dla adresów pasujących do reguł poziomu stron prawnych z konfiguracji. Domyślnie 0.2. Działa tylko przy włączonych poziomach priorytetów.
|
extra_urls_comment: Adresy, których nie podaje żaden typ treści, np. statyczne strony witryny. Trafiają do plików sitemap-pages.
|
||||||
|
extra_url: Adres
|
||||||
|
extra_url_lastmod: Ostatnia zmiana
|
||||||
|
extra_url_lastmod_comment: 'Opcjonalnie, w formacie RRRR-MM-DD, np. 2026-10-28.'
|
||||||
|
images_enabled: Mapa obrazów
|
||||||
|
images_enabled_comment: Wypisuje obraz wyróżniający i obrazy w treści każdej podanej strony, w plikach sitemap-images.
|
||||||
|
news_enabled: Mapa Google News
|
||||||
|
news_enabled_comment: Tylko dla witryn przyjętych do Google News. Wypisuje artykuły opublikowane w ciągu ostatnich dwóch dni.
|
||||||
|
news_publication: Nazwa publikacji
|
||||||
|
news_publication_comment: 'Tak jak w Google News. Puste: nazwa witryny.'
|
||||||
|
news_sources: Typy i kategorie
|
||||||
|
news_sources_comment: 'Artykuły tych typów lub kategorii trafiają do mapy News. Puste: każdy typ artykułów.'
|
||||||
|
indexnow_enabled: IndexNow
|
||||||
|
indexnow_enabled_comment: Od razu informuje Bing, Yandex i inne wyszukiwarki IndexNow o nowych, zmienionych i usuniętych adresach. Google nie korzysta z IndexNow.
|
||||||
|
indexnow_new_key: Wygeneruj nowy klucz przy zapisie
|
||||||
|
indexnow_new_key_comment: Stary plik klucza od razu przestaje działać. Używaj tylko, gdy klucz wyciekł.
|
||||||
|
html_enabled: Mapa witryny HTML
|
||||||
|
html_enabled_comment: Strona dla odwiedzających z listą wszystkich indeksowalnych adresów, linkowana ze stopki witryny.
|
||||||
|
html_path: Adres
|
||||||
|
html_path_comment: Strona mapy witryny używa tego adresu. Zmień go także w witrynie.
|
||||||
|
html_page_size: Linków na stronie
|
||||||
|
html_page_size_comment: Większe grupy są dzielone na numerowane strony. Domyślnie 150.
|
||||||
|
files:
|
||||||
|
label: Pliki
|
||||||
|
file: Plik
|
||||||
|
file_urls: Adresy
|
||||||
|
file_lastmod: Ostatnia zmiana
|
||||||
|
left_out: Pominięte w mapach witryny
|
||||||
|
left_out_reason: Powód
|
||||||
|
left_out_count: Adresy
|
||||||
|
reason_noindex: noindex
|
||||||
|
reason_canonical: Adres kanoniczny wskazuje inny adres
|
||||||
|
reason_redirect: Adres przekierowuje
|
||||||
|
reason_type: Wyłączony typ treści
|
||||||
|
reason_duplicate: Już na liście typu treści
|
||||||
|
index_note: Wyszukiwarki czytają indeks pod :url, a robots.txt go wskazuje. Pliki są odbudowywane po zmianach treści i co noc; zapisanie tego formularza odbudowuje je od razu.
|
||||||
|
empty: Nie ma jeszcze plików. Powstaną w ciągu kilku minut po pierwszym zapisie.
|
||||||
|
building: Trwa odbudowa. Odśwież stronę za minutę.
|
||||||
|
news:
|
||||||
|
sources: Wartości pola Typy i kategorie
|
||||||
|
source_value: Wartość
|
||||||
|
source_label: Artykuły
|
||||||
|
source_type: 'Wszystkie artykuły: :type'
|
||||||
|
none: Żaden typ treści nie publikuje jeszcze artykułów.
|
||||||
|
indexnow:
|
||||||
|
key: 'Klucz: :key, udostępniany pod :url'
|
||||||
|
no_key: Klucz zostanie wygenerowany po włączeniu IndexNow i zapisie.
|
||||||
|
last: 'Ostatnie powiadomienie: :time, adresy: :count, odpowiedź :status.'
|
||||||
|
never: Nie wysłano jeszcze powiadomienia.
|
||||||
|
err_key: Wyszukiwarki nie mogły odczytać pliku klucza pod :url. Sprawdź, czy witryna go udostępnia.
|
||||||
|
err_host: Wyszukiwarki odrzuciły adresy, bo nie pasują do adresu witryny.
|
||||||
|
err_rate: 'Zbyt wiele powiadomień; następna próba: :time.'
|
||||||
|
jobs:
|
||||||
|
rebuild: Odbudowa map witryny
|
||||||
|
|||||||
27
listeners.go
Normal file
27
listeners.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package sitemap
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
)
|
||||||
|
|
||||||
|
// listen subscribes to the framework's record events (D-92): a saved
|
||||||
|
// record of a content type moves the lastmod of its addresses when the
|
||||||
|
// save changed something real, a deleted one leaves the files, and both
|
||||||
|
// queue a debounced rebuild (classes.RecordSaved, classes.RecordDeleted).
|
||||||
|
// Listener errors are logged by the bus and never fail the write that
|
||||||
|
// fired them.
|
||||||
|
func (p *Plugin) listen(app *backpack.App) {
|
||||||
|
if app == nil || app.Events == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
app.Events.Listen("golem15.sitemap", func(ctx context.Context, ev *pact.RecordSaved) error {
|
||||||
|
return classes.RecordSaved(ctx, p.app, ev)
|
||||||
|
})
|
||||||
|
app.Events.Listen("golem15.sitemap", func(ctx context.Context, ev *pact.RecordDeleted) error {
|
||||||
|
return classes.RecordDeleted(ctx, p.app, ev)
|
||||||
|
})
|
||||||
|
}
|
||||||
13
manifest_test.go
Normal file
13
manifest_test.go
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
package sitemap
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/kiosk"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestPluginManifest fails when plugin.yaml is missing or no longer matches
|
||||||
|
// what `summer plugin:manifest` derives from this repository.
|
||||||
|
func TestPluginManifest(t *testing.T) {
|
||||||
|
kiosk.CheckT(t, ".")
|
||||||
|
}
|
||||||
55
mcp.go
Normal file
55
mcp.go
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
package sitemap
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
apicontrollers "git.golem15.com/golem15/sm-sitemap-plugin/controllers/api"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ pact.HasMCP = (*Plugin)(nil)
|
||||||
|
|
||||||
|
// mcpGuard is the guard every sitemap tool runs as: the backend account
|
||||||
|
// linked to the MCP user. The routes resolve that administrator themselves.
|
||||||
|
const mcpGuard = "backend"
|
||||||
|
|
||||||
|
// MCP declares the sitemap tools (D-10, UI-SPEC MCP parity): reading and
|
||||||
|
// changing the settings screen's values (with the file list, the IndexNow
|
||||||
|
// key and status) and queueing a rebuild, each bound to a /_sitemap/api/v1
|
||||||
|
// management route, run as the backend account linked to the MCP user and
|
||||||
|
// listed only when that account has the sitemap permission. pier prefixes
|
||||||
|
// them with sitemap_.
|
||||||
|
func (p *Plugin) MCP() pact.MCP {
|
||||||
|
return pact.MCP{Tools: []pact.MCPTool{
|
||||||
|
{
|
||||||
|
Name: "get_settings",
|
||||||
|
Title: "Show the sitemap settings",
|
||||||
|
Description: "Shows the sitemap settings (site address, file size, additional addresses, image and News sitemaps, IndexNow, HTML sitemap), the content types with their file names and headings, the files of the index with their address counts, the addresses left out by reason, the IndexNow key and last notification, and the values the News sources take.",
|
||||||
|
Guard: mcpGuard,
|
||||||
|
Method: http.MethodGet,
|
||||||
|
Path: "/_sitemap/api/v1/settings",
|
||||||
|
Input: struct{}{},
|
||||||
|
Permissions: []string{apicontrollers.PermissionManage},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "update_settings",
|
||||||
|
Title: "Update the sitemap settings",
|
||||||
|
Description: "Changes the sitemap settings sent and, under types, the settings of content types by key, with the checks of the settings screen. Turning IndexNow on generates its key; indexnow_new_key replaces it. The sitemaps are rebuilt afterwards.",
|
||||||
|
Guard: mcpGuard,
|
||||||
|
Method: http.MethodPut,
|
||||||
|
Path: "/_sitemap/api/v1/settings",
|
||||||
|
Input: apicontrollers.UpdateSettingsInput{},
|
||||||
|
Permissions: []string{apicontrollers.PermissionManage},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "rebuild",
|
||||||
|
Title: "Rebuild the sitemaps",
|
||||||
|
Description: "Queues a rebuild of the sitemap files now, as a settings save does; get_settings shows building until it has run.",
|
||||||
|
Guard: mcpGuard,
|
||||||
|
Method: http.MethodPost,
|
||||||
|
Path: "/_sitemap/api/v1/rebuild",
|
||||||
|
Input: struct{}{},
|
||||||
|
Permissions: []string{apicontrollers.PermissionManage},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
}
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
package models
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
|
||||||
)
|
|
||||||
|
|
||||||
// DefinitionTheme is the fixed theme key of the one sitemap definition of an
|
|
||||||
// application (D-11). The theme column stays so the table matches PHP; the
|
|
||||||
// import commands write this key whatever the PHP theme was.
|
|
||||||
const DefinitionTheme = "default"
|
|
||||||
|
|
||||||
// Definition is a sitemap definition stored on golem15_sitemap_definitions,
|
|
||||||
// the PHP Golem15\Sitemap\Models\Definition. Data holds the items as JSON
|
|
||||||
// text (PHP $jsonable data).
|
|
||||||
type Definition struct {
|
|
||||||
ID uint `gorm:"column:id;primaryKey"`
|
|
||||||
Theme *string `gorm:"column:theme"`
|
|
||||||
Data lagoon.Jsonable[DefinitionItems] `gorm:"column:data"`
|
|
||||||
CreatedAt *time.Time `gorm:"column:created_at"`
|
|
||||||
UpdatedAt *time.Time `gorm:"column:updated_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (Definition) TableName() string { return "golem15_sitemap_definitions" }
|
|
||||||
|
|
||||||
// MorphName is the PHP class string of the model.
|
|
||||||
func (Definition) MorphName() string { return `Golem15\Sitemap\Models\Definition` }
|
|
||||||
|
|
||||||
// Fillable is exactly theme and data, the PHP $fillable with $guarded = ['*']
|
|
||||||
// (MassAssignmentTest).
|
|
||||||
func (Definition) Fillable() []string { return []string{"theme", "data"} }
|
|
||||||
|
|
||||||
// Rules is empty: the PHP model validated nothing. The admin form checks
|
|
||||||
// each item row's reference against its type.
|
|
||||||
func (Definition) Rules() map[string]string { return map[string]string{} }
|
|
||||||
|
|
||||||
// Items returns the stored items.
|
|
||||||
func (d Definition) Items() []DefinitionItem { return d.Data.Get() }
|
|
||||||
|
|
||||||
// SetItems stores items as the definition's data.
|
|
||||||
func (d *Definition) SetItems(items []DefinitionItem) {
|
|
||||||
d.Data = lagoon.Jsonable[DefinitionItems]{Data: DefinitionItems(items), Valid: true}
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
Register(Definition{})
|
|
||||||
}
|
|
||||||
@@ -1,69 +0,0 @@
|
|||||||
# ===================================
|
|
||||||
# Form Field Definitions
|
|
||||||
# ===================================
|
|
||||||
#
|
|
||||||
# The WinterCMS form was one tab holding the SitemapItems widget. Here the
|
|
||||||
# items are a repeater on data; each row is one DefinitionItem. The CMS page
|
|
||||||
# field is not ported: items are URLs or registry types.
|
|
||||||
|
|
||||||
fields:
|
|
||||||
data:
|
|
||||||
label: golem15.sitemap::lang.item.definition
|
|
||||||
type: repeater
|
|
||||||
prompt: golem15.sitemap::lang.item.add_item
|
|
||||||
titleFrom: url
|
|
||||||
form:
|
|
||||||
fields:
|
|
||||||
type:
|
|
||||||
label: golem15.sitemap::lang.item.type
|
|
||||||
type: dropdown
|
|
||||||
options: getTypeOptions
|
|
||||||
span: left
|
|
||||||
reference:
|
|
||||||
label: golem15.sitemap::lang.item.reference
|
|
||||||
type: dropdown
|
|
||||||
dependsOn: type
|
|
||||||
emptyOption: backend::lang.form.none
|
|
||||||
span: right
|
|
||||||
url:
|
|
||||||
label: golem15.sitemap::lang.item.url
|
|
||||||
type: text
|
|
||||||
span: left
|
|
||||||
urlPattern:
|
|
||||||
label: golem15.sitemap::lang.item.url_pattern
|
|
||||||
comment: golem15.sitemap::lang.item.url_pattern_comment
|
|
||||||
type: text
|
|
||||||
span: right
|
|
||||||
priority:
|
|
||||||
label: golem15.sitemap::lang.item.priority
|
|
||||||
type: dropdown
|
|
||||||
span: left
|
|
||||||
options:
|
|
||||||
'0.1': '0.1'
|
|
||||||
'0.2': '0.2'
|
|
||||||
'0.3': '0.3'
|
|
||||||
'0.4': '0.4'
|
|
||||||
'0.5': '0.5'
|
|
||||||
'0.6': '0.6'
|
|
||||||
'0.7': '0.7'
|
|
||||||
'0.8': '0.8'
|
|
||||||
'0.9': '0.9'
|
|
||||||
'1.0': '1.0'
|
|
||||||
changefreq:
|
|
||||||
label: golem15.sitemap::lang.item.changefreq
|
|
||||||
type: dropdown
|
|
||||||
span: right
|
|
||||||
options:
|
|
||||||
always: golem15.sitemap::lang.item.always
|
|
||||||
hourly: golem15.sitemap::lang.item.hourly
|
|
||||||
daily: golem15.sitemap::lang.item.daily
|
|
||||||
weekly: golem15.sitemap::lang.item.weekly
|
|
||||||
monthly: golem15.sitemap::lang.item.monthly
|
|
||||||
yearly: golem15.sitemap::lang.item.yearly
|
|
||||||
never: golem15.sitemap::lang.item.never
|
|
||||||
nesting:
|
|
||||||
label: golem15.sitemap::lang.item.allow_nested_items
|
|
||||||
comment: golem15.sitemap::lang.item.allow_nested_items_comment
|
|
||||||
type: checkbox
|
|
||||||
default: true
|
|
||||||
span: full
|
|
||||||
@@ -1,255 +0,0 @@
|
|||||||
package models
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ItemTypeURL is the built-in item type of an explicit URL. Every other
|
|
||||||
// item type is a menu item type of the framework's registry (signpost).
|
|
||||||
const ItemTypeURL = "url"
|
|
||||||
|
|
||||||
// DefinitionItem is one sitemap definition item, the PHP
|
|
||||||
// Golem15\Sitemap\Classes\DefinitionItem. Type is "url" or a registry menu
|
|
||||||
// item type key; URL is the address of a url item; Reference is the record a
|
|
||||||
// registry item points at; URLPattern overrides the type's URL pattern;
|
|
||||||
// Nesting asks a registry item for its sub-items; Priority and Changefreq
|
|
||||||
// are written to the sitemap as they are stored.
|
|
||||||
//
|
|
||||||
// Text fields are pointers so a stored JSON null stays null on the next
|
|
||||||
// save. Decoding is tolerant of what PHP stored: numbers and booleans are
|
|
||||||
// accepted for text fields, strings and numbers for Nesting, and unknown keys
|
|
||||||
// (cmsPage, code, exists, fillable and any other) are ignored. Encoding
|
|
||||||
// writes the PHP toArray key set: changefreq, priority, nesting, type, url,
|
|
||||||
// reference, cmsPage (always null, CMS pages are not supported) and
|
|
||||||
// urlPattern.
|
|
||||||
type DefinitionItem struct {
|
|
||||||
Type string
|
|
||||||
URL *string
|
|
||||||
Reference *string
|
|
||||||
URLPattern *string
|
|
||||||
Nesting bool
|
|
||||||
Priority *string
|
|
||||||
Changefreq *string
|
|
||||||
}
|
|
||||||
|
|
||||||
// Text returns the value of a text field, "" for null.
|
|
||||||
func Text(p *string) string {
|
|
||||||
if p == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return *p
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnmarshalJSON decodes one stored item tolerantly. A missing type is the
|
|
||||||
// PHP default "url"; a null type is "".
|
|
||||||
func (d *DefinitionItem) UnmarshalJSON(raw []byte) error {
|
|
||||||
if bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
|
|
||||||
// PHP initFromArray kept a default item for a null entry.
|
|
||||||
*d = DefinitionItem{Type: ItemTypeURL}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
var fields map[string]json.RawMessage
|
|
||||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
|
||||||
dec.UseNumber()
|
|
||||||
if err := dec.Decode(&fields); err != nil {
|
|
||||||
return fmt.Errorf("sitemap definition item: %w", err)
|
|
||||||
}
|
|
||||||
item := DefinitionItem{Type: ItemTypeURL}
|
|
||||||
if v, ok := fields["type"]; ok {
|
|
||||||
s, err := DecodeText(v)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("sitemap definition item type: %w", err)
|
|
||||||
}
|
|
||||||
item.Type = Text(s)
|
|
||||||
}
|
|
||||||
for key, dest := range map[string]**string{
|
|
||||||
"url": &item.URL,
|
|
||||||
"reference": &item.Reference,
|
|
||||||
"urlPattern": &item.URLPattern,
|
|
||||||
"priority": &item.Priority,
|
|
||||||
"changefreq": &item.Changefreq,
|
|
||||||
} {
|
|
||||||
v, ok := fields[key]
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
s, err := DecodeText(v)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("sitemap definition item %s: %w", key, err)
|
|
||||||
}
|
|
||||||
*dest = s
|
|
||||||
}
|
|
||||||
if v, ok := fields["nesting"]; ok {
|
|
||||||
b, err := decodeTruthy(v)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("sitemap definition item nesting: %w", err)
|
|
||||||
}
|
|
||||||
item.Nesting = b
|
|
||||||
}
|
|
||||||
*d = item
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON writes the PHP toArray key set in its order.
|
|
||||||
func (d DefinitionItem) MarshalJSON() ([]byte, error) {
|
|
||||||
var b bytes.Buffer
|
|
||||||
b.WriteByte('{')
|
|
||||||
write := func(key string, v any, last bool) error {
|
|
||||||
kb, _ := json.Marshal(key)
|
|
||||||
b.Write(kb)
|
|
||||||
b.WriteByte(':')
|
|
||||||
vb, err := json.Marshal(v)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
b.Write(vb)
|
|
||||||
if !last {
|
|
||||||
b.WriteByte(',')
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
for _, f := range []struct {
|
|
||||||
key string
|
|
||||||
v any
|
|
||||||
}{
|
|
||||||
{"changefreq", d.Changefreq},
|
|
||||||
{"priority", d.Priority},
|
|
||||||
{"nesting", d.Nesting},
|
|
||||||
{"type", d.Type},
|
|
||||||
{"url", d.URL},
|
|
||||||
{"reference", d.Reference},
|
|
||||||
{"cmsPage", nil},
|
|
||||||
} {
|
|
||||||
if err := write(f.key, f.v, false); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := write("urlPattern", d.URLPattern, true); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
b.WriteByte('}')
|
|
||||||
return b.Bytes(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DefinitionItems is the stored item list of a definition. It decodes a
|
|
||||||
// JSON array, and a JSON object (a PHP array whose keys were not sequential)
|
|
||||||
// in key order.
|
|
||||||
type DefinitionItems []DefinitionItem
|
|
||||||
|
|
||||||
// UnmarshalJSON accepts a JSON array or object of items; null is no items.
|
|
||||||
func (l *DefinitionItems) UnmarshalJSON(raw []byte) error {
|
|
||||||
raw = bytes.TrimSpace(raw)
|
|
||||||
if len(raw) == 0 || bytes.Equal(raw, []byte("null")) {
|
|
||||||
*l = nil
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if raw[0] == '[' {
|
|
||||||
var items []DefinitionItem
|
|
||||||
if err := json.Unmarshal(raw, &items); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
*l = items
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if raw[0] != '{' {
|
|
||||||
return fmt.Errorf("sitemap definition data must be a list of items")
|
|
||||||
}
|
|
||||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
|
||||||
if _, err := dec.Token(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var items []DefinitionItem
|
|
||||||
for dec.More() {
|
|
||||||
if _, err := dec.Token(); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var item DefinitionItem
|
|
||||||
if err := dec.Decode(&item); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
items = append(items, item)
|
|
||||||
}
|
|
||||||
*l = items
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// MarshalJSON writes a JSON array; no items is [].
|
|
||||||
func (l DefinitionItems) MarshalJSON() ([]byte, error) {
|
|
||||||
if l == nil {
|
|
||||||
return []byte("[]"), nil
|
|
||||||
}
|
|
||||||
return json.Marshal([]DefinitionItem(l))
|
|
||||||
}
|
|
||||||
|
|
||||||
// DecodeText decodes a stored text value: a string as it is, a number in
|
|
||||||
// its PHP string form, a boolean as PHP casts it ("1" or ""), null as nil.
|
|
||||||
func DecodeText(raw json.RawMessage) (*string, error) {
|
|
||||||
var v any
|
|
||||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
|
||||||
dec.UseNumber()
|
|
||||||
if err := dec.Decode(&v); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var s string
|
|
||||||
switch t := v.(type) {
|
|
||||||
case nil:
|
|
||||||
return nil, nil
|
|
||||||
case string:
|
|
||||||
s = t
|
|
||||||
case json.Number:
|
|
||||||
s = phpNumberString(t)
|
|
||||||
case bool:
|
|
||||||
if t {
|
|
||||||
s = "1"
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("must be text, got %T", v)
|
|
||||||
}
|
|
||||||
return &s, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// decodeTruthy decodes a stored flag with PHP truthiness: false, 0, "",
|
|
||||||
// "0" and null are false.
|
|
||||||
func decodeTruthy(raw json.RawMessage) (bool, error) {
|
|
||||||
var v any
|
|
||||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
|
||||||
dec.UseNumber()
|
|
||||||
if err := dec.Decode(&v); err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
switch t := v.(type) {
|
|
||||||
case nil:
|
|
||||||
return false, nil
|
|
||||||
case bool:
|
|
||||||
return t, nil
|
|
||||||
case string:
|
|
||||||
return t != "" && t != "0", nil
|
|
||||||
case json.Number:
|
|
||||||
f, err := t.Float64()
|
|
||||||
if err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
return f != 0, nil
|
|
||||||
}
|
|
||||||
return false, fmt.Errorf("must be a flag, got %T", v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// phpNumberString is PHP's string cast of a json_decode'd number: an
|
|
||||||
// integer as written, a float in its shortest round-trip form (1.0 is "1").
|
|
||||||
func phpNumberString(n json.Number) string {
|
|
||||||
text := n.String()
|
|
||||||
if !strings.ContainsAny(text, ".eE") {
|
|
||||||
if i, err := strconv.ParseInt(text, 10, 64); err == nil {
|
|
||||||
return strconv.FormatInt(i, 10)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
f, err := n.Float64()
|
|
||||||
if err != nil {
|
|
||||||
return text
|
|
||||||
}
|
|
||||||
return strconv.FormatFloat(f, 'f', -1, 64)
|
|
||||||
}
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
package models_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"slices"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
|
||||||
)
|
|
||||||
|
|
||||||
// TestFillable ports the PHP MassAssignmentTest (SITE-001) as behaviour:
|
|
||||||
// Definition.Fillable is exactly theme and data, and a fill with extra keys
|
|
||||||
// (id, timestamps, unknown keys) writes only those two.
|
|
||||||
func TestFillable(t *testing.T) {
|
|
||||||
if got := (models.Definition{}).Fillable(); !slices.Equal(got, []string{"theme", "data"}) {
|
|
||||||
t.Fatalf("Fillable = %v, want [theme data]", got)
|
|
||||||
}
|
|
||||||
def := models.Definition{ID: 4}
|
|
||||||
requested := map[string]any{
|
|
||||||
"id": 99,
|
|
||||||
"theme": "site",
|
|
||||||
"data": `[{"type":"url","url":"/a"}]`,
|
|
||||||
"created_at": "2020-01-01 00:00:00",
|
|
||||||
"updated_at": "2020-01-01 00:00:00",
|
|
||||||
"is_admin": true,
|
|
||||||
}
|
|
||||||
for _, production := range []bool{true, false} {
|
|
||||||
d := def
|
|
||||||
if err := lagoon.Fill(&d, d.Fillable(), requested, production); err != nil {
|
|
||||||
t.Fatalf("Fill: %v", err)
|
|
||||||
}
|
|
||||||
if d.ID != 4 || d.CreatedAt != nil || d.UpdatedAt != nil || models.Text(d.Theme) != "site" {
|
|
||||||
t.Fatalf("filled definition = %+v", d)
|
|
||||||
}
|
|
||||||
if items := d.Items(); len(items) != 1 || models.Text(items[0].URL) != "/a" {
|
|
||||||
t.Fatalf("filled data = %+v", items)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (models.Definition{}).TableName() != "golem15_sitemap_definitions" || (models.Definition{}).MorphName() != `Golem15\Sitemap\Models\Definition` {
|
|
||||||
t.Fatal("table or morph name changed")
|
|
||||||
}
|
|
||||||
if rules := (models.Definition{}).Rules(); len(rules) != 0 {
|
|
||||||
t.Fatalf("Rules = %v", rules)
|
|
||||||
}
|
|
||||||
if got := (models.Settings{}).Fillable(); slices.Contains(got, "id") || len(got) != 9 {
|
|
||||||
t.Fatalf("Settings.Fillable = %v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestDefinitionItemJSON pins the tolerant decoding of PHP-stored items
|
|
||||||
// (strings, numbers, booleans and null for text fields, PHP truthiness for
|
|
||||||
// nesting, unknown keys ignored, a missing type is url, a null item a
|
|
||||||
// default url item, an object-keyed list in key order) and the PHP toArray
|
|
||||||
// encoding (key set and order, cmsPage always null, null text kept).
|
|
||||||
func TestDefinitionItemJSON(t *testing.T) {
|
|
||||||
for _, tc := range []struct {
|
|
||||||
raw string
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
{`{"type":"url","url":"/a","priority":"0.5","changefreq":"daily","nesting":"0","reference":null,"urlPattern":null,"cmsPage":"x","code":"c","exists":false,"fillable":["a"]}`,
|
|
||||||
`type=url url=/a ref=<nil> pattern=<nil> nesting=false priority=0.5 changefreq=daily`},
|
|
||||||
{`{"url":"/b"}`, `type=url url=/b ref=<nil> pattern=<nil> nesting=false priority=<nil> changefreq=<nil>`},
|
|
||||||
{`{"type":null}`, `type= url=<nil> ref=<nil> pattern=<nil> nesting=false priority=<nil> changefreq=<nil>`},
|
|
||||||
{`{"type":"journal-post","reference":7,"priority":0.5,"changefreq":true,"nesting":1}`,
|
|
||||||
`type=journal-post url=<nil> ref=7 pattern=<nil> nesting=true priority=0.5 changefreq=1`},
|
|
||||||
{`{"type":"x","priority":1.0,"reference":12.50,"changefreq":false,"nesting":"1"}`,
|
|
||||||
`type=x url=<nil> ref=12.5 pattern=<nil> nesting=true priority=1 changefreq=`},
|
|
||||||
{`{"type":"x","nesting":"false"}`, `type=x url=<nil> ref=<nil> pattern=<nil> nesting=true priority=<nil> changefreq=<nil>`},
|
|
||||||
{`{"type":"x","nesting":""}`, `type=x url=<nil> ref=<nil> pattern=<nil> nesting=false priority=<nil> changefreq=<nil>`},
|
|
||||||
{`{"type":"x","nesting":null,"urlPattern":"/p/:slug"}`, `type=x url=<nil> ref=<nil> pattern=/p/:slug nesting=false priority=<nil> changefreq=<nil>`},
|
|
||||||
{`{"type":"x","reference":12345678901234}`, `type=x url=<nil> ref=12345678901234 pattern=<nil> nesting=false priority=<nil> changefreq=<nil>`},
|
|
||||||
{`null`, `type=url url=<nil> ref=<nil> pattern=<nil> nesting=false priority=<nil> changefreq=<nil>`},
|
|
||||||
} {
|
|
||||||
var item models.DefinitionItem
|
|
||||||
if err := json.Unmarshal([]byte(tc.raw), &item); err != nil {
|
|
||||||
t.Fatalf("%s: %v", tc.raw, err)
|
|
||||||
}
|
|
||||||
if got := describe(item); got != tc.want {
|
|
||||||
t.Errorf("%s\n got %s\nwant %s", tc.raw, got, tc.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, raw := range []string{`{"type":["x"]}`, `{"url":{"a":1}}`, `{"nesting":[1]}`, `[1]`, `"x"`} {
|
|
||||||
var item models.DefinitionItem
|
|
||||||
if err := json.Unmarshal([]byte(raw), &item); err == nil {
|
|
||||||
t.Errorf("%s decoded without an error", raw)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// A list, an object keyed like a PHP array with gaps, null and empty.
|
|
||||||
var list models.DefinitionItems
|
|
||||||
if err := json.Unmarshal([]byte(`{"3":{"url":"/c"},"1":{"url":"/a"},"x":{"url":"/x"}}`), &list); err != nil || len(list) != 3 ||
|
|
||||||
models.Text(list[0].URL) != "/c" || models.Text(list[1].URL) != "/a" || models.Text(list[2].URL) != "/x" {
|
|
||||||
t.Fatalf("object list = %+v %v", list, err)
|
|
||||||
}
|
|
||||||
for raw, n := range map[string]int{`[]`: 0, `null`: 0, `[{"url":"/a"},null]`: 2} {
|
|
||||||
var l models.DefinitionItems
|
|
||||||
if err := json.Unmarshal([]byte(raw), &l); err != nil || len(l) != n {
|
|
||||||
t.Fatalf("%s = %+v %v", raw, l, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var bad models.DefinitionItems
|
|
||||||
if err := json.Unmarshal([]byte(`"items"`), &bad); err == nil {
|
|
||||||
t.Fatal("a string decoded as an item list")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Encoding: the PHP toArray key set and order.
|
|
||||||
pattern := "/p/:slug"
|
|
||||||
item := models.DefinitionItem{Type: "journal-post", Reference: str("7"), URLPattern: &pattern, Nesting: true, Priority: str("0.5")}
|
|
||||||
raw, err := json.Marshal(item)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if want := `{"changefreq":null,"priority":"0.5","nesting":true,"type":"journal-post","url":null,"reference":"7","cmsPage":null,"urlPattern":"/p/:slug"}`; string(raw) != want {
|
|
||||||
t.Fatalf("Marshal = %s\nwant %s", raw, want)
|
|
||||||
}
|
|
||||||
if raw, _ := json.Marshal(models.DefinitionItems(nil)); string(raw) != "[]" {
|
|
||||||
t.Fatalf("nil list = %s", raw)
|
|
||||||
}
|
|
||||||
var back models.DefinitionItem
|
|
||||||
if err := json.Unmarshal(raw, &back); err != nil || describe(back) != describe(item) {
|
|
||||||
t.Fatalf("round trip = %s, %v", describe(back), err)
|
|
||||||
}
|
|
||||||
if models.Text(nil) != "" || models.Text(str("x")) != "x" {
|
|
||||||
t.Fatal("Text")
|
|
||||||
}
|
|
||||||
if s, err := models.DecodeText(json.RawMessage(`1e3`)); err != nil || *s != "1000" {
|
|
||||||
t.Fatalf("DecodeText(1e3) = %v %v", s, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func str(s string) *string { return &s }
|
|
||||||
|
|
||||||
func describe(d models.DefinitionItem) string {
|
|
||||||
p := func(s *string) string {
|
|
||||||
if s == nil {
|
|
||||||
return "<nil>"
|
|
||||||
}
|
|
||||||
return *s
|
|
||||||
}
|
|
||||||
return strings.TrimSpace(fmt.Sprintf("type=%s url=%s ref=%s pattern=%s nesting=%v priority=%s changefreq=%s",
|
|
||||||
d.Type, p(d.URL), p(d.Reference), p(d.URLPattern), d.Nesting, p(d.Priority), p(d.Changefreq)))
|
|
||||||
}
|
|
||||||
278
models/legacy.go
Normal file
278
models/legacy.go
Normal file
@@ -0,0 +1,278 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"regexp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Text returns *p, "" for nil.
|
||||||
|
func Text(p *string) string {
|
||||||
|
if p == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return *p
|
||||||
|
}
|
||||||
|
|
||||||
|
// LegacyItemURL is the type of a Phase 17 (and WinterCMS) sitemap
|
||||||
|
// definition item that is an explicit address.
|
||||||
|
const LegacyItemURL = "url"
|
||||||
|
|
||||||
|
// LegacyItem is one item of a Phase 17 or WinterCMS sitemap definition, as
|
||||||
|
// golem15_sitemap_definitions.data and the WinterCMS export store it. Only
|
||||||
|
// the fields the per-type format still reads are kept: the type (a missing
|
||||||
|
// type is url, as in PHP), the address of a url item and the reference of a
|
||||||
|
// registry item.
|
||||||
|
type LegacyItem struct {
|
||||||
|
Type string
|
||||||
|
URL string
|
||||||
|
Reference string
|
||||||
|
CMSPage string
|
||||||
|
}
|
||||||
|
|
||||||
|
// LegacyEntries splits a JSON array, or a JSON object in key order (a PHP
|
||||||
|
// array with keys), into its values with their PHP labels (index or key).
|
||||||
|
// ok is false for any other value.
|
||||||
|
func LegacyEntries(raw []byte) ([]json.RawMessage, []string, bool) {
|
||||||
|
raw = bytes.TrimSpace(raw)
|
||||||
|
if len(raw) == 0 {
|
||||||
|
return nil, nil, false
|
||||||
|
}
|
||||||
|
switch raw[0] {
|
||||||
|
case '[':
|
||||||
|
var list []json.RawMessage
|
||||||
|
if err := json.Unmarshal(raw, &list); err != nil {
|
||||||
|
return nil, nil, false
|
||||||
|
}
|
||||||
|
labels := make([]string, len(list))
|
||||||
|
for i := range list {
|
||||||
|
labels[i] = strconv.Itoa(i)
|
||||||
|
}
|
||||||
|
return list, labels, true
|
||||||
|
case '{':
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||||
|
if _, err := dec.Token(); err != nil {
|
||||||
|
return nil, nil, false
|
||||||
|
}
|
||||||
|
var list []json.RawMessage
|
||||||
|
var labels []string
|
||||||
|
for dec.More() {
|
||||||
|
tok, err := dec.Token()
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, false
|
||||||
|
}
|
||||||
|
key, _ := tok.(string)
|
||||||
|
var v json.RawMessage
|
||||||
|
if err := dec.Decode(&v); err != nil {
|
||||||
|
return nil, nil, false
|
||||||
|
}
|
||||||
|
list = append(list, v)
|
||||||
|
labels = append(labels, key)
|
||||||
|
}
|
||||||
|
return list, labels, true
|
||||||
|
}
|
||||||
|
return nil, nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseLegacyItem decodes one stored item tolerantly: text fields may be
|
||||||
|
// strings, numbers, booleans or null; a missing type is url; unknown keys
|
||||||
|
// are ignored.
|
||||||
|
func ParseLegacyItem(raw json.RawMessage) (LegacyItem, error) {
|
||||||
|
var fields map[string]json.RawMessage
|
||||||
|
if err := json.Unmarshal(raw, &fields); err != nil {
|
||||||
|
return LegacyItem{}, fmt.Errorf("an item must be an object: %w", err)
|
||||||
|
}
|
||||||
|
item := LegacyItem{Type: LegacyItemURL}
|
||||||
|
for key, dest := range map[string]*string{"type": &item.Type, "url": &item.URL, "reference": &item.Reference, "cmsPage": &item.CMSPage} {
|
||||||
|
v, ok := fields[key]
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
text, err := DecodeText(v)
|
||||||
|
if err != nil {
|
||||||
|
return LegacyItem{}, fmt.Errorf("%s %w", key, err)
|
||||||
|
}
|
||||||
|
*dest = strings.TrimSpace(Text(text))
|
||||||
|
}
|
||||||
|
return item, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseLegacyItems decodes the data of a definition: a JSON array or a PHP
|
||||||
|
// keyed object of items, itself possibly stored as a JSON string. Empty or
|
||||||
|
// null data has no items.
|
||||||
|
func ParseLegacyItems(data []byte) ([]LegacyItem, []string, error) {
|
||||||
|
data = LegacyJSON(data)
|
||||||
|
if len(data) == 0 || bytes.Equal(data, []byte("null")) {
|
||||||
|
return nil, nil, nil
|
||||||
|
}
|
||||||
|
raws, labels, ok := LegacyEntries(data)
|
||||||
|
if !ok {
|
||||||
|
return nil, nil, fmt.Errorf("the definition data is not a list of items")
|
||||||
|
}
|
||||||
|
items := make([]LegacyItem, 0, len(raws))
|
||||||
|
for i, raw := range raws {
|
||||||
|
item, err := ParseLegacyItem(raw)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("definition item %s: %w", labels[i], err)
|
||||||
|
}
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
return items, labels, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LegacyJSON is a JSON value that may be held as text (a TEXT column
|
||||||
|
// selected as it is) or as JSON: a string is decoded once more.
|
||||||
|
func LegacyJSON(raw []byte) []byte {
|
||||||
|
raw = bytes.TrimSpace(raw)
|
||||||
|
if len(raw) > 0 && raw[0] == '"' {
|
||||||
|
var text string
|
||||||
|
if json.Unmarshal(raw, &text) == nil {
|
||||||
|
return []byte(strings.TrimSpace(text))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return raw
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecodeText decodes a stored text value with PHP's string conversion:
|
||||||
|
// null is nil, a number its PHP text, true "1" and false "".
|
||||||
|
func DecodeText(raw json.RawMessage) (*string, error) {
|
||||||
|
var v any
|
||||||
|
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||||
|
dec.UseNumber()
|
||||||
|
if err := dec.Decode(&v); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var s string
|
||||||
|
switch t := v.(type) {
|
||||||
|
case nil:
|
||||||
|
return nil, nil
|
||||||
|
case string:
|
||||||
|
s = t
|
||||||
|
case json.Number:
|
||||||
|
s = phpNumberString(t)
|
||||||
|
case bool:
|
||||||
|
if t {
|
||||||
|
s = "1"
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("must be text, got %T", v)
|
||||||
|
}
|
||||||
|
return &s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func phpNumberString(n json.Number) string {
|
||||||
|
text := n.String()
|
||||||
|
if !strings.ContainsAny(text, ".eE") {
|
||||||
|
if i, err := strconv.ParseInt(text, 10, 64); err == nil {
|
||||||
|
return strconv.FormatInt(i, 10)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f, err := n.Float64()
|
||||||
|
if err != nil {
|
||||||
|
return text
|
||||||
|
}
|
||||||
|
return strconv.FormatFloat(f, 'f', -1, 64)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DroppedItem is a url item of a Phase 17 definition that ConvertLegacyItems
|
||||||
|
// could not copy: its PHP label (index or key; "" for a definition that is
|
||||||
|
// not a list of items), the value as stored and the reason.
|
||||||
|
type DroppedItem struct {
|
||||||
|
Label string
|
||||||
|
URL string
|
||||||
|
Reason string
|
||||||
|
}
|
||||||
|
|
||||||
|
// legacyScheme matches a value that starts with a URL scheme.
|
||||||
|
var legacyScheme = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9+.\-]*:`)
|
||||||
|
|
||||||
|
// ConvertLegacyItems turns the url items of a Phase 17 definition into
|
||||||
|
// additional addresses (D-32, P33-66; pure). The entries are parsed one by
|
||||||
|
// one: a malformed item is dropped with its parse error and the others are
|
||||||
|
// kept; items of another type (records the content types list) are neither
|
||||||
|
// kept nor reported. A value without a scheme and without a leading / gets
|
||||||
|
// one, as the Phase 17 sitemap resolved it against the site root; spaces
|
||||||
|
// and the bytes " < > \ are percent-encoded. The result must pass
|
||||||
|
// AllowedAddress; one that does not is dropped with the reason (an
|
||||||
|
// absolute URL with & among them). A duplicate is kept once and not
|
||||||
|
// reported.
|
||||||
|
func ConvertLegacyItems(data []byte) ([]ExtraURL, []DroppedItem) {
|
||||||
|
rows := []ExtraURL{}
|
||||||
|
var dropped []DroppedItem
|
||||||
|
data = LegacyJSON(data)
|
||||||
|
if len(data) == 0 || bytes.Equal(data, []byte("null")) {
|
||||||
|
return rows, nil
|
||||||
|
}
|
||||||
|
raws, labels, ok := LegacyEntries(data)
|
||||||
|
if !ok {
|
||||||
|
return rows, []DroppedItem{{Reason: "the definition data is not a list of items"}}
|
||||||
|
}
|
||||||
|
seen := map[string]bool{}
|
||||||
|
for i, raw := range raws {
|
||||||
|
item, err := ParseLegacyItem(raw)
|
||||||
|
if err != nil {
|
||||||
|
dropped = append(dropped, DroppedItem{Label: labels[i], Reason: err.Error()})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if item.Type != LegacyItemURL {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
u, reason := convertLegacyURL(item.URL)
|
||||||
|
if reason != "" {
|
||||||
|
dropped = append(dropped, DroppedItem{Label: labels[i], URL: item.URL, Reason: reason})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if seen[u] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[u] = true
|
||||||
|
rows = append(rows, ExtraURL{URL: u})
|
||||||
|
}
|
||||||
|
return rows, dropped
|
||||||
|
}
|
||||||
|
|
||||||
|
// convertLegacyURL is one url item's value as an additional address, or
|
||||||
|
// the reason it cannot be one.
|
||||||
|
func convertLegacyURL(raw string) (string, string) {
|
||||||
|
u := strings.TrimSpace(raw)
|
||||||
|
if u == "" {
|
||||||
|
return "", "the item has no address"
|
||||||
|
}
|
||||||
|
if !utf8.ValidString(u) {
|
||||||
|
return "", "the address is not valid UTF-8"
|
||||||
|
}
|
||||||
|
if !legacyScheme.MatchString(u) && !strings.HasPrefix(u, "/") {
|
||||||
|
u = "/" + u
|
||||||
|
}
|
||||||
|
var b strings.Builder
|
||||||
|
for _, r := range u {
|
||||||
|
switch {
|
||||||
|
case r == '"' || r == '<' || r == '>' || r == '\\' || unicode.IsSpace(r):
|
||||||
|
for _, c := range []byte(string(r)) {
|
||||||
|
fmt.Fprintf(&b, "%%%02X", c)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
b.WriteRune(r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
u = b.String()
|
||||||
|
if AllowedAddress(u) {
|
||||||
|
return u, ""
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(u, "//"):
|
||||||
|
return "", "an address starting with // has no scheme"
|
||||||
|
case strings.HasPrefix(u, "/"):
|
||||||
|
return "", "the path holds a control character"
|
||||||
|
case strings.Contains(u, "&"):
|
||||||
|
return "", "an absolute address may not hold &"
|
||||||
|
case strings.ContainsFunc(u, unicode.IsControl):
|
||||||
|
return "", "the address holds a control character"
|
||||||
|
}
|
||||||
|
return "", "only a path or an absolute http(s) address can be an additional address"
|
||||||
|
}
|
||||||
60
models/legacy_test.go
Normal file
60
models/legacy_test.go
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
package models_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TestConvertLegacyItems pins L2 WR-04 (D-32, P33-66): every url item the
|
||||||
|
// Phase 17 sitemap served is copied, a relative path with a leading slash
|
||||||
|
// and spaces and unsafe bytes percent-encoded; a duplicate is kept once
|
||||||
|
// and not reported; an item that still is no allowed address, and a
|
||||||
|
// malformed one, is dropped with its reason while the others are kept;
|
||||||
|
// items of another type are neither kept nor reported.
|
||||||
|
func TestConvertLegacyItems(t *testing.T) {
|
||||||
|
data := `[{"type":"url","url":"o-nas"},` +
|
||||||
|
`{"type":"url","url":"/blog/zażółć gęślą"},` +
|
||||||
|
`{"type":"url","url":"/o-nas"},` +
|
||||||
|
`{"type":"url","url":"https://site.test/x?a=1&b=2"},` +
|
||||||
|
`{"type":"url","url":["not", "text"]},` +
|
||||||
|
`{"type":"acme-post","reference":"7"},` +
|
||||||
|
`{"url":"/a\"b<c>d\\e"},` +
|
||||||
|
`{"type":"url","url":"https://site.test/kontakt"},` +
|
||||||
|
`{"type":"url","url":"javascript:alert(1)"}]`
|
||||||
|
rows, dropped := models.ConvertLegacyItems([]byte(data))
|
||||||
|
var got []string
|
||||||
|
for _, r := range rows {
|
||||||
|
got = append(got, r.URL)
|
||||||
|
if r.LastMod != "" {
|
||||||
|
t.Errorf("a copied address has a lastmod: %+v", r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
want := "/o-nas /blog/zażółć%20gęślą /a%22b%3Cc%3Ed%5Ce https://site.test/kontakt"
|
||||||
|
if strings.Join(got, " ") != want {
|
||||||
|
t.Fatalf("rows = %q, want %q", strings.Join(got, " "), want)
|
||||||
|
}
|
||||||
|
if len(dropped) != 3 {
|
||||||
|
t.Fatalf("dropped = %+v, want the & URL, the malformed item and javascript:", dropped)
|
||||||
|
}
|
||||||
|
if d := dropped[0]; d.Label != "3" || d.URL != "https://site.test/x?a=1&b=2" || !strings.Contains(d.Reason, "&") {
|
||||||
|
t.Errorf("dropped & URL = %+v", d)
|
||||||
|
}
|
||||||
|
if d := dropped[1]; d.Label != "4" || d.URL != "" || !strings.Contains(d.Reason, "url") {
|
||||||
|
t.Errorf("dropped malformed item = %+v", d)
|
||||||
|
}
|
||||||
|
if d := dropped[2]; d.Label != "8" || d.URL != "javascript:alert(1)" || d.Reason == "" {
|
||||||
|
t.Errorf("dropped javascript: = %+v", d)
|
||||||
|
}
|
||||||
|
|
||||||
|
if rows, dropped := models.ConvertLegacyItems([]byte(`{"a":{"url":"/x"},"b":{"url":"/x"}}`)); len(rows) != 1 || rows[0].URL != "/x" || len(dropped) != 0 {
|
||||||
|
t.Errorf("keyed object = %+v %+v", rows, dropped)
|
||||||
|
}
|
||||||
|
if rows, dropped := models.ConvertLegacyItems([]byte(`"not a list"`)); len(rows) != 0 || len(dropped) != 1 || dropped[0].Label != "" {
|
||||||
|
t.Errorf("not a list = %+v %+v", rows, dropped)
|
||||||
|
}
|
||||||
|
if rows, dropped := models.ConvertLegacyItems(nil); len(rows) != 0 || dropped != nil {
|
||||||
|
t.Errorf("empty = %+v %+v", rows, dropped)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,93 +2,238 @@ package models
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/url"
|
"net/url"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
"unicode"
|
"unicode"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
"gorm.io/gorm"
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
)
|
)
|
||||||
|
|
||||||
// errFrontendURL is the phrase key of the frontend_url refusal.
|
// errFrontendURL is the phrase key of the site address refusal (the
|
||||||
|
// Phase 17 frontend_url phrase, unchanged).
|
||||||
const errFrontendURL = "golem15.sitemap::lang.errors.frontend_url"
|
const errFrontendURL = "golem15.sitemap::lang.errors.frontend_url"
|
||||||
|
|
||||||
// The settings keys of the five priority tiers, in the order PHP checked
|
// Settings is the sitemap settings singleton (row id 1) on
|
||||||
// them. A tier rule names one of them.
|
// golem15_sitemap_settings (UI-SPEC C26). SiteURL is the public site
|
||||||
|
// address every <loc> starts with (empty: golem15.sitemap.site_url, then
|
||||||
|
// app.url), FileSize the addresses per file, DefaultLocale the site's
|
||||||
|
// default locale (the unprefixed one, and the target of x-default) and
|
||||||
|
// ExtraURLs the additional addresses. RebuildPendingUntil is the debounce
|
||||||
|
// time of the next queued rebuild, NumberedSize the file size the files are
|
||||||
|
// numbered for, BuiltAt the end of the last rebuild and RebuildRequestedAt
|
||||||
|
// the last rebuild asked for from the admin. The Phase 17 columns
|
||||||
|
// (frontend_url, priorities, tiers, the update manifest) stay in the table
|
||||||
|
// and are no longer read (D-32).
|
||||||
|
//
|
||||||
|
// The image and News sitemaps, IndexNow and the HTML sitemap (D-31, D-34):
|
||||||
|
// ImagesEnabled lists the sitemap-images files, NewsEnabled sitemap-news.xml
|
||||||
|
// with NewsPublication (empty: app.name) and NewsSources (type:<key> and
|
||||||
|
// category:<key>:<id> values; empty: every article type). IndexNowEnabled
|
||||||
|
// notifies api.indexnow.org with IndexNowKey after each rebuild, and the
|
||||||
|
// last answer is IndexNowLastAt, IndexNowLastCount and IndexNowLastStatus.
|
||||||
|
// HTMLEnabled serves the HTML sitemap API, HTMLPaths is the site's HTML
|
||||||
|
// sitemap address per locale and HTMLPageSize the links per page.
|
||||||
|
type Settings struct {
|
||||||
|
ID uint `gorm:"column:id;primaryKey"`
|
||||||
|
SiteURL *string `gorm:"column:site_url"`
|
||||||
|
FileSize int `gorm:"column:file_size"`
|
||||||
|
DefaultLocale *string `gorm:"column:default_locale"`
|
||||||
|
ExtraURLs lagoon.Jsonable[[]ExtraURL] `gorm:"column:extra_urls"`
|
||||||
|
RebuildPendingUntil *time.Time `gorm:"column:rebuild_pending_until"`
|
||||||
|
NumberedSize *int `gorm:"column:numbered_size"`
|
||||||
|
BuiltAt *time.Time `gorm:"column:built_at"`
|
||||||
|
RebuildRequestedAt *time.Time `gorm:"column:rebuild_requested_at"`
|
||||||
|
|
||||||
|
ImagesEnabled bool `gorm:"column:images_enabled"`
|
||||||
|
NewsEnabled bool `gorm:"column:news_enabled"`
|
||||||
|
NewsPublication *string `gorm:"column:news_publication"`
|
||||||
|
NewsSources lagoon.Jsonable[[]string] `gorm:"column:news_sources"`
|
||||||
|
IndexNowEnabled bool `gorm:"column:indexnow_enabled"`
|
||||||
|
IndexNowKey *string `gorm:"column:indexnow_key"`
|
||||||
|
IndexNowLastAt *time.Time `gorm:"column:indexnow_last_at"`
|
||||||
|
IndexNowLastCount *int `gorm:"column:indexnow_last_count"`
|
||||||
|
IndexNowLastStatus *int `gorm:"column:indexnow_last_status"`
|
||||||
|
HTMLEnabled bool `gorm:"column:html_enabled"`
|
||||||
|
HTMLPaths lagoon.Jsonable[map[string]string] `gorm:"column:html_paths"`
|
||||||
|
HTMLPageSize int `gorm:"column:html_page_size"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DefaultFileSize is the number of addresses per sitemap file when the
|
||||||
|
// setting is not stored (D-30); MaxFileSize is the protocol's limit.
|
||||||
const (
|
const (
|
||||||
PriorityHomepage = "priority_homepage"
|
DefaultFileSize = 1000
|
||||||
PriorityServices = "priority_services"
|
MaxFileSize = 50000
|
||||||
PriorityBlog = "priority_blog"
|
|
||||||
PriorityCategories = "priority_categories"
|
|
||||||
PriorityLegal = "priority_legal"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// PriorityDefaults are the PHP defaults of the priority settings.
|
// ExtraURL is one additional address of the settings: URL is a path (or an
|
||||||
var PriorityDefaults = map[string]string{
|
// absolute http(s) URL on the site), LastMod its optional last change as
|
||||||
PriorityHomepage: "1.0",
|
// the admin's date picker sends it.
|
||||||
PriorityServices: "0.8",
|
type ExtraURL struct {
|
||||||
PriorityBlog: "0.6",
|
URL string `json:"url"`
|
||||||
PriorityCategories: "0.4",
|
LastMod string `json:"lastmod"`
|
||||||
PriorityLegal: "0.2",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Settings is the sitemap settings singleton (row id 1) on
|
// EffectiveFileSize is the stored file size, or DefaultFileSize when it is
|
||||||
// golem15_sitemap_settings, the PHP Golem15\Sitemap\Models\Settings that
|
// outside 1..MaxFileSize.
|
||||||
// WinterCMS kept in system_settings under golem15_sitemap_settings.
|
func (s Settings) EffectiveFileSize() int {
|
||||||
// FrontendURL replaces the backend URL in the generated XML;
|
if s.FileSize < 1 || s.FileSize > MaxFileSize {
|
||||||
// FrontendDefaultLocale is the locale whose URLs carry no prefix;
|
return DefaultFileSize
|
||||||
// UpdatesManifestPath names a JSON file of URL path to last-modified date;
|
}
|
||||||
// EnablePriorityTiers turns the tier priorities on, and the priority fields
|
return s.FileSize
|
||||||
// hold each tier's value as text. A null priority reads as its PHP default.
|
|
||||||
// The PHP settings form validated nothing; the port checks FrontendURL in
|
|
||||||
// BeforeValidate.
|
|
||||||
type Settings struct {
|
|
||||||
ID uint `gorm:"column:id;primaryKey"`
|
|
||||||
FrontendURL *string `gorm:"column:frontend_url"`
|
|
||||||
FrontendDefaultLocale *string `gorm:"column:frontend_default_locale"`
|
|
||||||
UpdatesManifestPath *string `gorm:"column:updates_manifest_path"`
|
|
||||||
EnablePriorityTiers bool `gorm:"column:enable_priority_tiers"`
|
|
||||||
PriorityHomepage *string `gorm:"column:priority_homepage"`
|
|
||||||
PriorityServices *string `gorm:"column:priority_services"`
|
|
||||||
PriorityBlog *string `gorm:"column:priority_blog"`
|
|
||||||
PriorityCategories *string `gorm:"column:priority_categories"`
|
|
||||||
PriorityLegal *string `gorm:"column:priority_legal"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Extra returns the additional addresses.
|
||||||
|
func (s Settings) Extra() []ExtraURL { return s.ExtraURLs.Get() }
|
||||||
|
|
||||||
func (Settings) TableName() string { return "golem15_sitemap_settings" }
|
func (Settings) TableName() string { return "golem15_sitemap_settings" }
|
||||||
|
|
||||||
// Fillable lists only the settings columns.
|
// Fillable lists the columns the settings form edits.
|
||||||
func (Settings) Fillable() []string {
|
func (Settings) Fillable() []string {
|
||||||
return []string{
|
return []string{"site_url", "file_size", "extra_urls", "images_enabled", "news_enabled", "news_publication", "news_sources", "indexnow_enabled", "html_enabled", "html_page_size"}
|
||||||
"frontend_url", "frontend_default_locale", "updates_manifest_path",
|
|
||||||
"enable_priority_tiers", PriorityHomepage, PriorityServices,
|
|
||||||
PriorityBlog, PriorityCategories, PriorityLegal,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rules is empty: the PHP settings form validated nothing. The one check of
|
// Rules is empty: the settings controller runs Validate before a save.
|
||||||
// the port, on frontend_url, is in BeforeValidate.
|
|
||||||
func (Settings) Rules() map[string]string { return map[string]string{} }
|
func (Settings) Rules() map[string]string { return map[string]string{} }
|
||||||
|
|
||||||
// BeforeValidate is the lagoon.HasBeforeValidate hook cabana calls on a
|
// The phrase keys of the other settings refusals.
|
||||||
// settings save, after the fill and before the row is written: a
|
const (
|
||||||
// frontend_url that AllowedFrontendURL refuses is a validation error on
|
errFileSize = "golem15.sitemap::lang.errors.file_size"
|
||||||
// frontend_url, so the save answers 422 and the row is left as it was.
|
errURLScheme = "golem15.sitemap::lang.errors.url_scheme"
|
||||||
func (s Settings) BeforeValidate(*gorm.DB) error {
|
errLastmod = "golem15.sitemap::lang.errors.lastmod"
|
||||||
if AllowedFrontendURL(Text(s.FrontendURL)) {
|
errNewsName = "golem15.sitemap::lang.errors.news_publication"
|
||||||
|
errNewsSrc = "golem15.sitemap::lang.errors.news_source"
|
||||||
|
errHTMLPath = "golem15.sitemap::lang.errors.html_path"
|
||||||
|
errPageSize = "golem15.sitemap::lang.errors.page_size"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MaxNewsPublication is the longest publication name.
|
||||||
|
const MaxNewsPublication = 255
|
||||||
|
|
||||||
|
// Validate answers every problem Problems finds as a validation error on
|
||||||
|
// its field; the settings controller calls it before a save, so the save
|
||||||
|
// answers 422 and the row is left as it was.
|
||||||
|
func (s Settings) Validate() error {
|
||||||
|
problems := s.Problems()
|
||||||
|
if len(problems) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return &cabana.ValidationError{Details: map[string]any{"frontend_url": []string{errFrontendURL}}}
|
details := make(map[string]any, len(problems))
|
||||||
|
for field, keys := range problems {
|
||||||
|
details[field] = keys
|
||||||
|
}
|
||||||
|
return &cabana.ValidationError{Details: details}
|
||||||
}
|
}
|
||||||
|
|
||||||
// AllowedFrontendURL reports whether u may be the frontend_url setting: the
|
// Problems lists the settings' refusals by field (UI-SPEC C26): a site
|
||||||
// empty string, or an absolute http or https URL with a host and without
|
// address that AllowedFrontendURL refuses, a file size outside 1..MaxFileSize and an additional
|
||||||
// whitespace, control characters, a double quote, <, > or &. The PHP plugin
|
// address that is not a path or an http(s) URL (extra_urls.<i>.url) or
|
||||||
// stored any text. The value is written into every loc, every hreflang link
|
// whose lastmod is not a date (extra_urls.<i>.lastmod), a publication name
|
||||||
// and the stylesheet instruction of the sitemap, and sitemap.xsl renders
|
// over 255 characters, a malformed News source, an HTML sitemap address
|
||||||
// each loc as a link on the public origin, so a value outside this form
|
// that ValidHTMLPath refuses (html_path) and a page size outside 50..500.
|
||||||
// (a javascript: URL, or text that closes the attribute it is written into)
|
func (s Settings) Problems() map[string][]string {
|
||||||
// would reach the readers of /sitemap.xml (T-17-15).
|
out := map[string][]string{}
|
||||||
|
if !AllowedFrontendURL(Text(s.SiteURL)) {
|
||||||
|
out["site_url"] = []string{errFrontendURL}
|
||||||
|
}
|
||||||
|
if s.FileSize < 1 || s.FileSize > MaxFileSize {
|
||||||
|
out["file_size"] = []string{errFileSize}
|
||||||
|
}
|
||||||
|
for i, e := range s.Extra() {
|
||||||
|
if !AllowedAddress(strings.TrimSpace(e.URL)) {
|
||||||
|
out["extra_urls."+strconv.Itoa(i)+".url"] = []string{errURLScheme}
|
||||||
|
}
|
||||||
|
if mod := strings.TrimSpace(e.LastMod); mod != "" && !ValidDate(mod) {
|
||||||
|
out["extra_urls."+strconv.Itoa(i)+".lastmod"] = []string{errLastmod}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if name := Text(s.NewsPublication); utf8.RuneCountInString(name) > MaxNewsPublication || strings.ContainsFunc(name, unicode.IsControl) {
|
||||||
|
out["news_publication"] = []string{errNewsName}
|
||||||
|
}
|
||||||
|
for _, v := range s.NewsSources.Get() {
|
||||||
|
if !ValidNewsSource(strings.TrimSpace(v)) {
|
||||||
|
out["news_sources"] = []string{errNewsSrc}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, p := range s.HTMLPaths.Get() {
|
||||||
|
if p = strings.TrimSpace(p); p != "" && !ValidHTMLPath(p) {
|
||||||
|
out["html_path"] = []string{errHTMLPath}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.HTMLPageSize < MinHTMLPageSize || s.HTMLPageSize > MaxHTMLPageSize {
|
||||||
|
out["html_page_size"] = []string{errPageSize}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// HTMLPathProblem is the refusal of an HTML sitemap address (errors.html_path).
|
||||||
|
const HTMLPathProblem = errHTMLPath
|
||||||
|
|
||||||
|
// ValidHTMLPath reports whether p may be the HTML sitemap's address: a
|
||||||
|
// path that starts with a single /, at most 255 characters of letters,
|
||||||
|
// digits and - _ . ~ / (no query, fragment, "//" or ".." segment), and not
|
||||||
|
// the site root.
|
||||||
|
func ValidHTMLPath(p string) bool {
|
||||||
|
if len(p) < 2 || len(p) > 255 || p[0] != '/' || strings.Contains(p, "//") {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, seg := range strings.Split(p[1:], "/") {
|
||||||
|
if seg == "." || seg == ".." {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, r := range p {
|
||||||
|
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || strings.ContainsRune("-_.~/", r)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// The prefixes of the news_sources values (P33-15): type:<type key> and
|
||||||
|
// category:<type key>:<id>.
|
||||||
|
const (
|
||||||
|
NewsSourceType = "type:"
|
||||||
|
NewsSourceCategory = "category:"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ValidNewsSource reports whether v is a news_sources value:
|
||||||
|
// type:<type key> or category:<type key>:<id>, each part 1 to 128 letters,
|
||||||
|
// digits, '-', '_' or '.'.
|
||||||
|
func ValidNewsSource(v string) bool {
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(v, NewsSourceType):
|
||||||
|
return validSourcePart(strings.TrimPrefix(v, NewsSourceType))
|
||||||
|
case strings.HasPrefix(v, NewsSourceCategory):
|
||||||
|
rest := strings.TrimPrefix(v, NewsSourceCategory)
|
||||||
|
i := strings.LastIndex(rest, ":")
|
||||||
|
return i > 0 && validSourcePart(rest[:i]) && validSourcePart(rest[i+1:])
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func validSourcePart(s string) bool {
|
||||||
|
if s == "" || len(s) > 128 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for _, r := range s {
|
||||||
|
if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_' || r == '.') {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// AllowedFrontendURL reports whether u may be the site address: the empty
|
||||||
|
// string, or an absolute http or https URL with a host and without
|
||||||
|
// whitespace, control characters, a double quote, <, > or &. The value
|
||||||
|
// starts every <loc> and hreflang link of the sitemaps, so a value outside
|
||||||
|
// this form (a javascript: URL, or text that closes the attribute it is
|
||||||
|
// written into) would reach their readers (T-17-15, T-33-12).
|
||||||
func AllowedFrontendURL(u string) bool {
|
func AllowedFrontendURL(u string) bool {
|
||||||
if u == "" {
|
if u == "" {
|
||||||
return true
|
return true
|
||||||
@@ -111,34 +256,82 @@ func AllowedFrontendURL(u string) bool {
|
|||||||
return parsed.Opaque == "" && parsed.Hostname() != ""
|
return parsed.Opaque == "" && parsed.Hostname() != ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// DefaultSettings is the settings PHP read when nothing was saved: tiers on
|
// DefaultSettings is the settings read when no row is stored.
|
||||||
// with the default priorities.
|
|
||||||
func DefaultSettings() Settings {
|
func DefaultSettings() Settings {
|
||||||
return Settings{ID: 1, EnablePriorityTiers: true}
|
return Settings{ID: 1, FileSize: DefaultFileSize, ImagesEnabled: true, HTMLEnabled: true, HTMLPageSize: DefaultHTMLPageSize}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Priority returns the value of a priority setting: the stored text, or the
|
// The HTML sitemap's links per page: DefaultHTMLPageSize when not stored,
|
||||||
// PHP default when it is null.
|
// MinHTMLPageSize to MaxHTMLPageSize when set (UI-SPEC C26).
|
||||||
func (s Settings) Priority(key string) string {
|
const (
|
||||||
var p *string
|
DefaultHTMLPageSize = 150
|
||||||
switch key {
|
MinHTMLPageSize = 50
|
||||||
case PriorityHomepage:
|
MaxHTMLPageSize = 500
|
||||||
p = s.PriorityHomepage
|
)
|
||||||
case PriorityServices:
|
|
||||||
p = s.PriorityServices
|
// DefaultHTMLPaths are the HTML sitemap's addresses when none is stored.
|
||||||
case PriorityBlog:
|
func DefaultHTMLPaths() map[string]string {
|
||||||
p = s.PriorityBlog
|
return map[string]string{"pl": "/mapa-strony", "en": "/sitemap"}
|
||||||
case PriorityCategories:
|
}
|
||||||
p = s.PriorityCategories
|
|
||||||
case PriorityLegal:
|
// EffectiveHTMLPageSize is the stored page size, or DefaultHTMLPageSize
|
||||||
p = s.PriorityLegal
|
// when it is outside MinHTMLPageSize..MaxHTMLPageSize.
|
||||||
|
func (s Settings) EffectiveHTMLPageSize() int {
|
||||||
|
if s.HTMLPageSize < MinHTMLPageSize || s.HTMLPageSize > MaxHTMLPageSize {
|
||||||
|
return DefaultHTMLPageSize
|
||||||
}
|
}
|
||||||
if p == nil {
|
return s.HTMLPageSize
|
||||||
return PriorityDefaults[key]
|
}
|
||||||
|
|
||||||
|
// EffectiveHTMLPaths are the stored HTML sitemap addresses without blank
|
||||||
|
// ones, or DefaultHTMLPaths when none is stored.
|
||||||
|
func (s Settings) EffectiveHTMLPaths() map[string]string {
|
||||||
|
out := map[string]string{}
|
||||||
|
for locale, path := range s.HTMLPaths.Get() {
|
||||||
|
if p := strings.TrimSpace(path); p != "" && strings.TrimSpace(locale) != "" {
|
||||||
|
out[locale] = p
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return *p
|
if len(out) == 0 {
|
||||||
|
return DefaultHTMLPaths()
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sources returns the News sources without blank values.
|
||||||
|
func (s Settings) Sources() []string {
|
||||||
|
var out []string
|
||||||
|
for _, v := range s.NewsSources.Get() {
|
||||||
|
if v = strings.TrimSpace(v); v != "" {
|
||||||
|
out = append(out, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
Register(Settings{})
|
Register(Settings{})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// dateLayouts are the lastmod forms an additional address may carry.
|
||||||
|
var dateLayouts = []string{time.RFC3339Nano, "2006-01-02 15:04:05", "2006-01-02T15:04:05", "2006-01-02"}
|
||||||
|
|
||||||
|
// ParseDate reads a lastmod as the settings form or an import gives it
|
||||||
|
// (YYYY-MM-DD, "YYYY-MM-DD hh:mm:ss" or RFC 3339; UTC unless it names a
|
||||||
|
// zone); nil when empty or unreadable.
|
||||||
|
func ParseDate(s string) *time.Time {
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
if s == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, layout := range dateLayouts {
|
||||||
|
if t, err := time.Parse(layout, s); err == nil {
|
||||||
|
t = t.UTC()
|
||||||
|
return &t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidDate reports whether s is a lastmod ParseDate reads.
|
||||||
|
func ValidDate(s string) bool { return ParseDate(s) != nil }
|
||||||
|
|||||||
@@ -2,67 +2,146 @@
|
|||||||
# Form Field Definitions
|
# Form Field Definitions
|
||||||
# ===================================
|
# ===================================
|
||||||
#
|
#
|
||||||
# The WinterCMS form's nginx hint and Priority Tiers section are field
|
# Sitemap settings (UI-SPEC C26): Files, Content types (one block per
|
||||||
# comments and README text here, and the tier fields always show (the
|
# signpost content type, added by the plugin's form extension after Files)
|
||||||
# trigger on enable_priority_tiers is not ported).
|
# and Additional addresses. A repeater row takes no date picker, so an
|
||||||
|
# additional address's lastmod is a text field read as YYYY-MM-DD.
|
||||||
|
|
||||||
fields:
|
fields:
|
||||||
frontend_url:
|
site_url:
|
||||||
label: golem15.sitemap::lang.settings.frontend_url
|
label: golem15.sitemap::lang.settings.site_url
|
||||||
comment: golem15.sitemap::lang.settings.frontend_url_comment
|
comment: golem15.sitemap::lang.settings.site_url_comment
|
||||||
type: text
|
type: text
|
||||||
span: left
|
span: left
|
||||||
|
tab: golem15.sitemap::lang.settings.tab_files
|
||||||
|
|
||||||
frontend_default_locale:
|
file_size:
|
||||||
label: golem15.sitemap::lang.settings.frontend_default_locale
|
label: golem15.sitemap::lang.settings.file_size
|
||||||
comment: golem15.sitemap::lang.settings.frontend_default_locale_comment
|
comment: golem15.sitemap::lang.settings.file_size_comment
|
||||||
type: text
|
type: number
|
||||||
|
default: 1000
|
||||||
span: right
|
span: right
|
||||||
|
tab: golem15.sitemap::lang.settings.tab_files
|
||||||
|
|
||||||
updates_manifest_path:
|
_files:
|
||||||
label: golem15.sitemap::lang.settings.updates_manifest_path
|
type: partial
|
||||||
comment: golem15.sitemap::lang.settings.updates_manifest_path_comment
|
path: sitemap_files
|
||||||
type: text
|
|
||||||
span: full
|
span: full
|
||||||
|
tab: golem15.sitemap::lang.settings.tab_files
|
||||||
|
|
||||||
enable_priority_tiers:
|
extra_urls:
|
||||||
label: golem15.sitemap::lang.settings.enable_priority_tiers
|
label: golem15.sitemap::lang.settings.extra_urls
|
||||||
comment: golem15.sitemap::lang.settings.enable_priority_tiers_comment
|
comment: golem15.sitemap::lang.settings.extra_urls_comment
|
||||||
type: checkbox
|
type: repeater
|
||||||
|
prompt: golem15.sitemap::lang.settings.extra_urls_add
|
||||||
|
titleFrom: url
|
||||||
|
span: full
|
||||||
|
tab: golem15.sitemap::lang.settings.tab_extra
|
||||||
|
form:
|
||||||
|
fields:
|
||||||
|
url:
|
||||||
|
label: golem15.sitemap::lang.settings.extra_url
|
||||||
|
type: text
|
||||||
|
span: left
|
||||||
|
lastmod:
|
||||||
|
label: golem15.sitemap::lang.settings.extra_url_lastmod
|
||||||
|
comment: golem15.sitemap::lang.settings.extra_url_lastmod_comment
|
||||||
|
type: text
|
||||||
|
span: right
|
||||||
|
|
||||||
|
images_enabled:
|
||||||
|
label: golem15.sitemap::lang.settings.images_enabled
|
||||||
|
comment: golem15.sitemap::lang.settings.images_enabled_comment
|
||||||
|
type: switch
|
||||||
default: true
|
default: true
|
||||||
span: full
|
span: full
|
||||||
|
tab: golem15.sitemap::lang.settings.tab_media
|
||||||
|
|
||||||
priority_homepage:
|
news_enabled:
|
||||||
label: golem15.sitemap::lang.settings.priority_homepage
|
label: golem15.sitemap::lang.settings.news_enabled
|
||||||
comment: golem15.sitemap::lang.settings.priority_homepage_comment
|
comment: golem15.sitemap::lang.settings.news_enabled_comment
|
||||||
type: text
|
type: switch
|
||||||
default: '1.0'
|
default: false
|
||||||
span: auto
|
span: full
|
||||||
|
tab: golem15.sitemap::lang.settings.tab_media
|
||||||
|
|
||||||
priority_services:
|
news_publication:
|
||||||
label: golem15.sitemap::lang.settings.priority_services
|
label: golem15.sitemap::lang.settings.news_publication
|
||||||
comment: golem15.sitemap::lang.settings.priority_services_comment
|
comment: golem15.sitemap::lang.settings.news_publication_comment
|
||||||
type: text
|
type: text
|
||||||
default: '0.8'
|
span: left
|
||||||
span: auto
|
tab: golem15.sitemap::lang.settings.tab_media
|
||||||
|
trigger:
|
||||||
|
action: hide
|
||||||
|
field: news_enabled
|
||||||
|
condition: unchecked
|
||||||
|
|
||||||
priority_blog:
|
# Taglist options are a fixed list, so the article types and their
|
||||||
label: golem15.sitemap::lang.settings.priority_blog
|
# categories are listed by the news_sources partial below instead.
|
||||||
comment: golem15.sitemap::lang.settings.priority_blog_comment
|
news_sources:
|
||||||
type: text
|
label: golem15.sitemap::lang.settings.news_sources
|
||||||
default: '0.6'
|
comment: golem15.sitemap::lang.settings.news_sources_comment
|
||||||
span: auto
|
type: taglist
|
||||||
|
mode: array
|
||||||
|
span: right
|
||||||
|
tab: golem15.sitemap::lang.settings.tab_media
|
||||||
|
trigger:
|
||||||
|
action: hide
|
||||||
|
field: news_enabled
|
||||||
|
condition: unchecked
|
||||||
|
|
||||||
priority_categories:
|
_news_sources:
|
||||||
label: golem15.sitemap::lang.settings.priority_categories
|
type: partial
|
||||||
comment: golem15.sitemap::lang.settings.priority_categories_comment
|
path: news_sources
|
||||||
type: text
|
span: full
|
||||||
default: '0.4'
|
tab: golem15.sitemap::lang.settings.tab_media
|
||||||
span: auto
|
trigger:
|
||||||
|
action: hide
|
||||||
|
field: news_enabled
|
||||||
|
condition: unchecked
|
||||||
|
|
||||||
priority_legal:
|
indexnow_enabled:
|
||||||
label: golem15.sitemap::lang.settings.priority_legal
|
label: golem15.sitemap::lang.settings.indexnow_enabled
|
||||||
comment: golem15.sitemap::lang.settings.priority_legal_comment
|
comment: golem15.sitemap::lang.settings.indexnow_enabled_comment
|
||||||
type: text
|
type: switch
|
||||||
default: '0.2'
|
default: false
|
||||||
span: auto
|
span: full
|
||||||
|
tab: golem15.sitemap::lang.settings.tab_indexnow
|
||||||
|
|
||||||
|
_indexnow_status:
|
||||||
|
type: partial
|
||||||
|
path: indexnow_status
|
||||||
|
span: full
|
||||||
|
tab: golem15.sitemap::lang.settings.tab_indexnow
|
||||||
|
|
||||||
|
# No column: the controller lists it in FormVirtualFields and generates
|
||||||
|
# a new key on save when it is checked.
|
||||||
|
indexnow_new_key:
|
||||||
|
label: golem15.sitemap::lang.settings.indexnow_new_key
|
||||||
|
comment: golem15.sitemap::lang.settings.indexnow_new_key_comment
|
||||||
|
type: checkbox
|
||||||
|
default: false
|
||||||
|
span: full
|
||||||
|
tab: golem15.sitemap::lang.settings.tab_indexnow
|
||||||
|
trigger:
|
||||||
|
action: hide
|
||||||
|
field: indexnow_enabled
|
||||||
|
condition: unchecked
|
||||||
|
|
||||||
|
# The address per locale (html_path, an mltext field) is added after
|
||||||
|
# this switch by the plugin's form extension, stored in html_paths.
|
||||||
|
html_enabled:
|
||||||
|
label: golem15.sitemap::lang.settings.html_enabled
|
||||||
|
comment: golem15.sitemap::lang.settings.html_enabled_comment
|
||||||
|
type: switch
|
||||||
|
default: true
|
||||||
|
span: full
|
||||||
|
tab: golem15.sitemap::lang.settings.tab_html
|
||||||
|
|
||||||
|
html_page_size:
|
||||||
|
label: golem15.sitemap::lang.settings.html_page_size
|
||||||
|
comment: golem15.sitemap::lang.settings.html_page_size_comment
|
||||||
|
type: number
|
||||||
|
default: 150
|
||||||
|
span: right
|
||||||
|
tab: golem15.sitemap::lang.settings.tab_html
|
||||||
|
|||||||
@@ -10,9 +10,6 @@ import (
|
|||||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
)
|
)
|
||||||
|
|
||||||
// cabana calls the hook on a settings save through this interface.
|
|
||||||
var _ lagoon.HasBeforeValidate = (*models.Settings)(nil)
|
|
||||||
|
|
||||||
// TestAllowedFrontendURL pins the one definition of a frontend_url that may
|
// TestAllowedFrontendURL pins the one definition of a frontend_url that may
|
||||||
// be saved, imported and applied (T-17-15): empty, or an absolute http(s)
|
// be saved, imported and applied (T-17-15): empty, or an absolute http(s)
|
||||||
// URL with a host and without whitespace, control characters, a double
|
// URL with a host and without whitespace, control characters, a double
|
||||||
@@ -67,31 +64,62 @@ func TestAllowedFrontendURL(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSettingsBeforeValidate pins the save check of T-17-15: the hook cabana
|
// TestSettingsValidate pins the save checks of the settings singleton
|
||||||
// calls on a settings save passes a null, empty or accepted frontend_url and
|
// (UI-SPEC C26, T-33-12): the check the controller runs before a save passes
|
||||||
// answers a validation error keyed frontend_url for any other value.
|
// a null, empty or accepted site_url, a file size from 1 to 50 000 and
|
||||||
func TestSettingsBeforeValidate(t *testing.T) {
|
// additional addresses that are paths or http(s) URLs, and answers a
|
||||||
|
// validation error keyed by the field for any other value.
|
||||||
|
func TestSettingsValidate(t *testing.T) {
|
||||||
text := func(s string) *string { return &s }
|
text := func(s string) *string { return &s }
|
||||||
for _, url := range []*string{nil, text(""), text("https://www.ex.pl/")} {
|
ok := func(s models.Settings) models.Settings {
|
||||||
if err := (&models.Settings{FrontendURL: url}).BeforeValidate(nil); err != nil {
|
if s.FileSize == 0 {
|
||||||
t.Errorf("BeforeValidate(%q) = %v, want nil", models.Text(url), err)
|
s.FileSize = 1000
|
||||||
|
}
|
||||||
|
if s.HTMLPageSize == 0 {
|
||||||
|
s.HTMLPageSize = models.DefaultHTMLPageSize
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
extra := func(urls ...string) lagoon.Jsonable[[]models.ExtraURL] {
|
||||||
|
rows := []models.ExtraURL{}
|
||||||
|
for _, u := range urls {
|
||||||
|
rows = append(rows, models.ExtraURL{URL: u})
|
||||||
|
}
|
||||||
|
return lagoon.Jsonable[[]models.ExtraURL]{Data: rows, Valid: true}
|
||||||
|
}
|
||||||
|
for name, s := range map[string]models.Settings{
|
||||||
|
"null site_url": ok(models.Settings{}),
|
||||||
|
"empty site_url": ok(models.Settings{SiteURL: text("")}),
|
||||||
|
"site_url": ok(models.Settings{SiteURL: text("https://www.ex.pl/")}),
|
||||||
|
"file size 1": ok(models.Settings{FileSize: 1}),
|
||||||
|
"file size 50 000": ok(models.Settings{FileSize: 50000}),
|
||||||
|
"extra addresses": ok(models.Settings{ExtraURLs: extra("/", "/o-nas?x=1&y=2", "https://www.ex.pl/kontakt")}),
|
||||||
|
} {
|
||||||
|
if err := s.Validate(); err != nil {
|
||||||
|
t.Errorf("%s: Validate = %v, want nil", name, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
want := map[string]any{"frontend_url": []string{"golem15.sitemap::lang.errors.frontend_url"}}
|
for name, c := range map[string]struct {
|
||||||
for _, url := range []string{
|
s models.Settings
|
||||||
"javascript:alert(document.domain)//",
|
want map[string]any
|
||||||
`https://x"/><y a="`,
|
}{
|
||||||
"0",
|
"javascript site_url": {ok(models.Settings{SiteURL: text("javascript:alert(document.domain)//")}), map[string]any{"site_url": []string{"golem15.sitemap::lang.errors.frontend_url"}}},
|
||||||
" https://www.ex.pl",
|
"attribute site_url": {ok(models.Settings{SiteURL: text(`https://x"/><y a="`)}), map[string]any{"site_url": []string{"golem15.sitemap::lang.errors.frontend_url"}}},
|
||||||
|
"path site_url": {ok(models.Settings{SiteURL: text("/x")}), map[string]any{"site_url": []string{"golem15.sitemap::lang.errors.frontend_url"}}},
|
||||||
|
"file size 0": {models.Settings{HTMLPageSize: 150}, map[string]any{"file_size": []string{"golem15.sitemap::lang.errors.file_size"}}},
|
||||||
|
"file size 50 001": {models.Settings{FileSize: 50001, HTMLPageSize: 150}, map[string]any{"file_size": []string{"golem15.sitemap::lang.errors.file_size"}}},
|
||||||
|
"javascript address": {ok(models.Settings{ExtraURLs: extra("/", "javascript:alert(1)")}), map[string]any{"extra_urls.1.url": []string{"golem15.sitemap::lang.errors.url_scheme"}}},
|
||||||
|
"protocol-relative": {ok(models.Settings{ExtraURLs: extra("//evil.test/x")}), map[string]any{"extra_urls.0.url": []string{"golem15.sitemap::lang.errors.url_scheme"}}},
|
||||||
|
"address with a space": {ok(models.Settings{ExtraURLs: extra("/a b")}), map[string]any{"extra_urls.0.url": []string{"golem15.sitemap::lang.errors.url_scheme"}}},
|
||||||
} {
|
} {
|
||||||
err := (&models.Settings{FrontendURL: &url}).BeforeValidate(nil)
|
err := c.s.Validate()
|
||||||
var invalid *cabana.ValidationError
|
var invalid *cabana.ValidationError
|
||||||
if !errors.As(err, &invalid) {
|
if !errors.As(err, &invalid) {
|
||||||
t.Errorf("BeforeValidate(%q) = %v, want a *cabana.ValidationError", url, err)
|
t.Errorf("%s: Validate = %v, want a *cabana.ValidationError", name, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if !reflect.DeepEqual(invalid.Details, want) {
|
if !reflect.DeepEqual(invalid.Details, c.want) {
|
||||||
t.Errorf("BeforeValidate(%q) details = %v, want %v", url, invalid.Details, want)
|
t.Errorf("%s: details = %v, want %v", name, invalid.Details, c.want)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
27
models/type_setting.go
Normal file
27
models/type_setting.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TypeSetting is the sitemap's setting of one signpost content type on
|
||||||
|
// golem15_sitemap_types, edited on the settings singleton's Content types
|
||||||
|
// tab: whether its records are listed, the file name part of its group
|
||||||
|
// (sitemap-<slug>-<n>.xml; "" means the default) and its heading per locale
|
||||||
|
// in the HTML sitemap. A type without a row is listed under its default
|
||||||
|
// slug.
|
||||||
|
type TypeSetting struct {
|
||||||
|
TypeKey string `gorm:"column:type_key;primaryKey"`
|
||||||
|
Include bool `gorm:"column:include"`
|
||||||
|
Slug string `gorm:"column:slug"`
|
||||||
|
Titles lagoon.Jsonable[map[string]string] `gorm:"column:titles"`
|
||||||
|
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (TypeSetting) TableName() string { return "golem15_sitemap_types" }
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
Register(TypeSetting{})
|
||||||
|
}
|
||||||
100
models/url.go
Normal file
100
models/url.go
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
package models
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unicode"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ExtraTypeKey is the type_key of the settings' additional addresses in
|
||||||
|
// golem15_sitemap_urls; their record_id is the hex SHA-256 of the address.
|
||||||
|
const ExtraTypeKey = "extra"
|
||||||
|
|
||||||
|
// ExtraGroup is the file group of the additional addresses.
|
||||||
|
const ExtraGroup = "pages"
|
||||||
|
|
||||||
|
// The excluded reasons the sitemap sets itself. A Filter's reasons
|
||||||
|
// (contract.ReasonNoindex and the others) are stored as it gives them.
|
||||||
|
const (
|
||||||
|
// ReasonDeleted is an address whose record or locale is gone.
|
||||||
|
ReasonDeleted = "deleted"
|
||||||
|
// ReasonUnpublished is an address whose record is not published.
|
||||||
|
ReasonUnpublished = "unpublished"
|
||||||
|
// ReasonDuplicate is an additional address that a content type
|
||||||
|
// already lists (the same absolute URL), so the files carry it once.
|
||||||
|
ReasonDuplicate = "duplicate"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Alternate is one hreflang alternate of an address: Hreflang the locale
|
||||||
|
// code or x-default, Href the alternate's path or absolute URL.
|
||||||
|
type Alternate struct {
|
||||||
|
Hreflang string `json:"hreflang"`
|
||||||
|
Href string `json:"href"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ref points at a record: Type is its content type key and ID the record's
|
||||||
|
// ID within it (pact.ContentRef as stored in parent_refs).
|
||||||
|
type Ref struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
ID string `json:"id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// URL is one row of the slot table golem15_sitemap_urls (D-30): an address
|
||||||
|
// of a content type's record in one locale, or an additional address. Grp
|
||||||
|
// and FileNo place it in the file sitemap-<grp>-<file_no>.xml; FileNo is
|
||||||
|
// nil until the address is numbered. ExcludedReason is "" for a listed
|
||||||
|
// address; a row left out keeps its FileNo, so its file keeps a hole.
|
||||||
|
// Images are the page's image addresses (D-31), ImageFileNo the number of
|
||||||
|
// its sitemap-images file (nil while it has none). Kind is the content
|
||||||
|
// type's kind (pact.ContentKindArticle and the others), PublishedAt the
|
||||||
|
// record's first publication and ParentRefs its parents, for the News
|
||||||
|
// sitemap and the HTML sitemap. IndexNowPendingAt is set by the record
|
||||||
|
// listeners on a row the next rebuild sends to IndexNow (a deleted
|
||||||
|
// record's listed row, an edited record's row whose lastmod moved) and
|
||||||
|
// cleared by that rebuild.
|
||||||
|
type URL struct {
|
||||||
|
ID uint64 `gorm:"column:id;primaryKey"`
|
||||||
|
Grp string `gorm:"column:grp"`
|
||||||
|
TypeKey string `gorm:"column:type_key"`
|
||||||
|
RecordID string `gorm:"column:record_id"`
|
||||||
|
Locale string `gorm:"column:locale"`
|
||||||
|
URL string `gorm:"column:url"`
|
||||||
|
Title string `gorm:"column:title"`
|
||||||
|
FileNo *int `gorm:"column:file_no"`
|
||||||
|
FirstSeen time.Time `gorm:"column:first_seen"`
|
||||||
|
LastMod *time.Time `gorm:"column:lastmod"`
|
||||||
|
Alternates lagoon.Jsonable[[]Alternate] `gorm:"column:alternates"`
|
||||||
|
Images lagoon.Jsonable[[]string] `gorm:"column:images"`
|
||||||
|
ImageFileNo *int `gorm:"column:image_file_no"`
|
||||||
|
Kind string `gorm:"column:kind"`
|
||||||
|
PublishedAt *time.Time `gorm:"column:published_at"`
|
||||||
|
ParentRefs lagoon.Jsonable[[]Ref] `gorm:"column:parent_refs"`
|
||||||
|
ExcludedReason string `gorm:"column:excluded_reason"`
|
||||||
|
UpdatedAt time.Time `gorm:"column:updated_at"`
|
||||||
|
// IndexNowPendingAt (P33-62).
|
||||||
|
IndexNowPendingAt *time.Time `gorm:"column:indexnow_pending_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (URL) TableName() string { return "golem15_sitemap_urls" }
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
Register(URL{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// AllowedAddress reports whether u may be a stored address: a path that
|
||||||
|
// starts with a single / (no whitespace, control characters, quotes, < or
|
||||||
|
// >), or an absolute http(s) URL that AllowedFrontendURL accepts.
|
||||||
|
func AllowedAddress(u string) bool {
|
||||||
|
if u == "" || !utf8.ValidString(u) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(u, "/") && !strings.HasPrefix(u, "//") {
|
||||||
|
return !strings.ContainsFunc(u, func(r rune) bool {
|
||||||
|
return unicode.IsControl(r) || unicode.IsSpace(r) || r == '"' || r == '<' || r == '>' || r == '\\'
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return AllowedFrontendURL(u)
|
||||||
|
}
|
||||||
65
plugin.go
65
plugin.go
@@ -1,17 +1,18 @@
|
|||||||
// Package sitemap is the golem15.sitemap plugin: it serves /sitemap.xml
|
// Package sitemap is the golem15.sitemap plugin: it serves a sitemap index
|
||||||
// from the application's one sitemap definition, byte for byte the way the
|
// at /sitemap.xml whose entries are per-group files of a configurable size
|
||||||
// WinterCMS Golem15.Sitemap plugin did, with items that are explicit URLs
|
// (sitemap-<slug>-<n>.xml, D-30), built from the published records of every
|
||||||
// or menu item types of the framework's registry.
|
// signpost content type and the additional addresses of its settings, with
|
||||||
|
// stable file numbers and real lastmod. Other plugins narrow it through the
|
||||||
|
// Filter of the contract package and read it through its Listing.
|
||||||
package sitemap
|
package sitemap
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"embed"
|
"embed"
|
||||||
"fmt"
|
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/console"
|
"git.golem15.com/golem15/sm-sitemap-plugin/console"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/contract"
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/updates"
|
"git.golem15.com/golem15/sm-sitemap-plugin/updates"
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
@@ -29,67 +30,51 @@ var (
|
|||||||
_ pact.HasModels = (*Plugin)(nil)
|
_ pact.HasModels = (*Plugin)(nil)
|
||||||
_ pact.HasRoutes = (*Plugin)(nil)
|
_ pact.HasRoutes = (*Plugin)(nil)
|
||||||
_ pact.HasCommands = (*Plugin)(nil)
|
_ pact.HasCommands = (*Plugin)(nil)
|
||||||
|
_ pact.HasJobs = (*Plugin)(nil)
|
||||||
_ surf.BucketProvider = (*Plugin)(nil)
|
_ surf.BucketProvider = (*Plugin)(nil)
|
||||||
)
|
)
|
||||||
|
|
||||||
//go:embed config
|
//go:embed config
|
||||||
var configFS embed.FS
|
var configFS embed.FS
|
||||||
|
|
||||||
// sitemapXSL is the PHP plugin's assets/sitemap.xsl, byte for byte.
|
|
||||||
//
|
|
||||||
//go:embed assets/sitemap.xsl
|
|
||||||
var sitemapXSL []byte
|
|
||||||
|
|
||||||
// Plugin is the golem15.sitemap plugin.
|
// Plugin is the golem15.sitemap plugin.
|
||||||
type Plugin struct {
|
type Plugin struct {
|
||||||
app *backpack.App
|
app *backpack.App
|
||||||
tiers classes.Tiers
|
|
||||||
cache *sitemapCache
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Plugin) ID() string { return "golem15.sitemap" }
|
func (p *Plugin) ID() string { return "golem15.sitemap" }
|
||||||
|
|
||||||
// Requires is empty: the sitemap reads content types through the framework's
|
// Requires is empty: the sitemap reads content types through signpost, not
|
||||||
// menu item type registry, not from a named plugin.
|
// from a named plugin, and a Filter through the service registry.
|
||||||
func (p *Plugin) Requires() []string { return nil }
|
func (p *Plugin) Requires() []string { return nil }
|
||||||
|
|
||||||
|
// Register publishes the sitemap's contract.Listing and contract.Rebuilder
|
||||||
|
// for other plugins (D-95).
|
||||||
func (p *Plugin) Register(app *backpack.App) error {
|
func (p *Plugin) Register(app *backpack.App) error {
|
||||||
p.app = app
|
p.app = app
|
||||||
return nil
|
if err := app.Publish[contract.Listing](classes.Listing{App: app}); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return app.Publish[contract.Rebuilder](classes.Listing{App: app})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Boot compiles the priority tier rules (classes.TiersConfigKey); a rule
|
// Boot keeps the booted application for the routes, jobs and commands and
|
||||||
// with an unknown setting or a pattern that does not compile fails the boot.
|
// subscribes to the record events.
|
||||||
// It also starts an empty sitemap cache for CacheConfigKey seconds; a
|
|
||||||
// negative value fails the boot.
|
|
||||||
func (p *Plugin) Boot(app *backpack.App) error {
|
func (p *Plugin) Boot(app *backpack.App) error {
|
||||||
p.app = app
|
p.app = app
|
||||||
var tiers classes.Tiers
|
p.listen(app)
|
||||||
var err error
|
|
||||||
seconds := 0
|
|
||||||
if app != nil {
|
|
||||||
tiers, err = classes.LoadTiers(app.Config)
|
|
||||||
if app.Config != nil {
|
|
||||||
seconds = app.Config.Int(CacheConfigKey)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("golem15.sitemap: %w", err)
|
|
||||||
}
|
|
||||||
if seconds < 0 {
|
|
||||||
return fmt.Errorf("golem15.sitemap: %s must not be negative, got %d", CacheConfigKey, seconds)
|
|
||||||
}
|
|
||||||
p.tiers = tiers
|
|
||||||
p.cache = newSitemapCache(time.Duration(seconds) * time.Second)
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ConfigFS ships config/config.yaml: the default priority tier rules.
|
// ConfigFS ships config/config.yaml: lastmod_ignore and
|
||||||
|
// rebuild_delay_seconds.
|
||||||
func (p *Plugin) ConfigFS() fs.FS { return configFS }
|
func (p *Plugin) ConfigFS() fs.FS { return configFS }
|
||||||
|
|
||||||
// Commands registers sitemap:import and sitemap:import-winter.
|
// Commands registers sitemap:rebuild, sitemap:import and
|
||||||
|
// sitemap:import-winter.
|
||||||
func (p *Plugin) Commands() []bonfire.Command {
|
func (p *Plugin) Commands() []bonfire.Command {
|
||||||
return []bonfire.Command{
|
return []bonfire.Command{
|
||||||
|
console.Rebuild(p.app),
|
||||||
console.Import(p.app),
|
console.Import(p.app),
|
||||||
console.ImportWinter(p.app),
|
console.ImportWinter(p.app),
|
||||||
}
|
}
|
||||||
|
|||||||
10
plugin.yaml
Normal file
10
plugin.yaml
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
# Generated by summer plugin:manifest. Do not edit; rerun the command.
|
||||||
|
schema: 1
|
||||||
|
id: golem15.sitemap
|
||||||
|
module: git.golem15.com/golem15/sm-sitemap-plugin
|
||||||
|
package: git.golem15.com/golem15/sm-sitemap-plugin
|
||||||
|
name: Sitemap
|
||||||
|
description: "The compiled sitemap plugin for SummerCMS applications: it serves a sitemap index at /sitemap.xml whose per-type files of a configurable size keep their numbers across rebuilds and carry real lastmod and hreflang alternates, built from every content type's published records, with image and Google News sitemaps, IndexNow notifications and the data of the site's HTML sitemap."
|
||||||
|
framework: v0.6.1
|
||||||
|
overrides:
|
||||||
|
name: Sitemap
|
||||||
134
rebuild_lock_test.go
Normal file
134
rebuild_lock_test.go
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
package sitemap_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"slices"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
)
|
||||||
|
|
||||||
|
// rebuildResult is the outcome of one classes.Rebuild run in a goroutine.
|
||||||
|
type rebuildResult struct {
|
||||||
|
res classes.RebuildResult
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// waitFor polls cond until it holds or the deadline passes.
|
||||||
|
func waitFor(t *testing.T, what string, cond func() bool) {
|
||||||
|
t.Helper()
|
||||||
|
deadline := time.Now().Add(15 * time.Second)
|
||||||
|
for !cond() {
|
||||||
|
if time.Now().After(deadline) {
|
||||||
|
t.Fatalf("timed out waiting for %s", what)
|
||||||
|
}
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConcurrentRebuilds pins L2 WR-02 (D-30, P33-63): a second rebuild
|
||||||
|
// waits on the rebuild's advisory lock while the first one collects, so it
|
||||||
|
// collects only after the first has committed; a record published while
|
||||||
|
// the first rebuild ran is listed afterwards and never sent to IndexNow as
|
||||||
|
// removed.
|
||||||
|
func TestConcurrentRebuilds(t *testing.T) {
|
||||||
|
e := bootIndex(t, filterPluginID)
|
||||||
|
mod := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
contentStore.put(pageType, page1(1, "a", mod))
|
||||||
|
if _, err := classes.Rebuild(t.Context(), e.app); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
entered, release := make(chan struct{}), make(chan struct{})
|
||||||
|
var once sync.Once
|
||||||
|
theFilter.setHook(t, func() {
|
||||||
|
first := false
|
||||||
|
once.Do(func() { first = true; close(entered) })
|
||||||
|
if first {
|
||||||
|
<-release
|
||||||
|
}
|
||||||
|
})
|
||||||
|
run := func() <-chan rebuildResult {
|
||||||
|
out := make(chan rebuildResult, 1)
|
||||||
|
go func() {
|
||||||
|
res, err := classes.Rebuild(context.Background(), e.app)
|
||||||
|
out <- rebuildResult{res, err}
|
||||||
|
}()
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
a := run()
|
||||||
|
select {
|
||||||
|
case <-entered:
|
||||||
|
case <-time.After(15 * time.Second):
|
||||||
|
t.Fatal("rebuild A never asked the filter")
|
||||||
|
}
|
||||||
|
contentStore.put(pageType, page1(2, "x", mod))
|
||||||
|
b := run()
|
||||||
|
waitFor(t, "rebuild B to wait on the advisory lock", func() bool {
|
||||||
|
var waiting int64
|
||||||
|
e.gdb.Raw(`SELECT COUNT(*) FROM pg_locks WHERE locktype = 'advisory' AND NOT granted`).Scan(&waiting)
|
||||||
|
return waiting > 0
|
||||||
|
})
|
||||||
|
close(release)
|
||||||
|
ra, rb := <-a, <-b
|
||||||
|
if ra.err != nil || rb.err != nil {
|
||||||
|
t.Fatalf("rebuilds: %v, %v", ra.err, rb.err)
|
||||||
|
}
|
||||||
|
var reason []string
|
||||||
|
e.gdb.Raw(`SELECT excluded_reason FROM golem15_sitemap_urls WHERE type_key = ? AND record_id = '2'`, pageType).Scan(&reason)
|
||||||
|
if len(reason) != 1 || reason[0] != "" {
|
||||||
|
t.Fatalf("record x after both rebuilds = %v, want listed", reason)
|
||||||
|
}
|
||||||
|
x := "https://api.example.test/pages/x"
|
||||||
|
if slices.Contains(ra.res.Removed, x) || slices.Contains(rb.res.Removed, x) {
|
||||||
|
t.Fatalf("x sent as removed: A %v, B %v", ra.res.Removed, rb.res.Removed)
|
||||||
|
}
|
||||||
|
if !slices.Contains(rb.res.Added, x) {
|
||||||
|
t.Fatalf("rebuild B added %v, want x", rb.res.Added)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRebuildKeepsMovedLastmod pins L2 WR-03 (D-30): a lastmod that
|
||||||
|
// RecordSaved moves while a rebuild runs stays, also when the same rebuild
|
||||||
|
// rewrites the row for another change (its title).
|
||||||
|
func TestRebuildKeepsMovedLastmod(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
old := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
contentStore.put(pageType, page1(1, "a", old))
|
||||||
|
if _, err := classes.Rebuild(t.Context(), e.app); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
renamed := page1(1, "a", old)
|
||||||
|
renamed.Locales[0].Title = "Page a, renamed"
|
||||||
|
contentStore.put(pageType, renamed)
|
||||||
|
|
||||||
|
lastmod := func() time.Time {
|
||||||
|
var at time.Time
|
||||||
|
e.gdb.Raw(`SELECT lastmod FROM golem15_sitemap_urls WHERE type_key = ? AND record_id = '1'`, pageType).Scan(&at)
|
||||||
|
return at
|
||||||
|
}
|
||||||
|
saved := make(chan error, 1)
|
||||||
|
ctx := classes.WithAfterSlotRead(t.Context(), func() {
|
||||||
|
go func() {
|
||||||
|
saved <- e.app.Events.Fire(context.Background(), &pact.RecordSaved{Model: pageModel, ID: "1", Changes: []pact.RecordChange{{Attribute: "title"}}})
|
||||||
|
}()
|
||||||
|
waitFor(t, "RecordSaved to move the lastmod", func() bool { return !lastmod().Equal(old) })
|
||||||
|
})
|
||||||
|
if _, err := classes.Rebuild(ctx, e.app); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := <-saved; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := lastmod(); got.Equal(old) {
|
||||||
|
t.Fatal("the rebuild wrote the lastmod it read back over the moved one")
|
||||||
|
}
|
||||||
|
var title string
|
||||||
|
e.gdb.Raw(`SELECT title FROM golem15_sitemap_urls WHERE type_key = ? AND record_id = '1'`, pageType).Scan(&title)
|
||||||
|
if title != "Page a, renamed" {
|
||||||
|
t.Fatalf("title = %q, want the rebuild's change", title)
|
||||||
|
}
|
||||||
|
}
|
||||||
463
routes.go
463
routes.go
@@ -1,228 +1,291 @@
|
|||||||
package sitemap
|
package sitemap
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/sha256"
|
"bytes"
|
||||||
"encoding/hex"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
"errors"
|
||||||
"net"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/netip"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
apicontrollers "git.golem15.com/golem15/sm-sitemap-plugin/controllers/api"
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
"git.golem15.com/golem15/summercms/modules/pact"
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
"git.golem15.com/golem15/summercms/modules/signpost"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/surf"
|
"git.golem15.com/golem15/summercms/modules/surf"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
// The response headers of the PHP routes (live responses).
|
// The response headers of the sitemap routes.
|
||||||
const (
|
const (
|
||||||
contentTypeXML = "application/xml"
|
contentTypeXML = "application/xml"
|
||||||
contentTypeXSL = "text/xsl; charset=UTF-8"
|
|
||||||
cacheControl = "no-cache, private"
|
cacheControl = "no-cache, private"
|
||||||
)
|
)
|
||||||
|
|
||||||
// BucketSitemap is the throttle bucket of GET /sitemap.xml.
|
// The throttle buckets: BucketSitemap of the sitemap files and the key
|
||||||
const BucketSitemap = "sitemap-xml"
|
// file, BucketHTML of the HTML sitemap API, BucketAPI of the management
|
||||||
|
// API.
|
||||||
|
const (
|
||||||
|
BucketSitemap = "sitemap-xml"
|
||||||
|
BucketHTML = "sitemap-html"
|
||||||
|
BucketAPI = "sitemap-api"
|
||||||
|
)
|
||||||
|
|
||||||
// CacheConfigKey is the config key of the number of seconds a generated
|
// FilesPath is the route of the per-group files. The index lists them at
|
||||||
// sitemap is served from memory; 0 turns the cache off.
|
// the site root (sitemap-<slug>-<n>.xml); the site's SEO layer or proxy
|
||||||
const CacheConfigKey = "golem15.sitemap.cache_seconds"
|
// maps the root names to this route.
|
||||||
|
const FilesPath = "/_sitemap/files/"
|
||||||
|
|
||||||
// cacheMaxEntries bounds the cache: one entry per root URL (app.url, or the
|
// Routes mounts GET /sitemap.xml (the index), GET /_sitemap/files/{file}
|
||||||
// request's scheme and Host when app.url is not set) and stored definition
|
// (one file) and GET /_sitemap/indexnow/{file} (the IndexNow key file)
|
||||||
// and settings. A full cache is emptied.
|
// without the backend middleware: search engines fetch them anonymously.
|
||||||
const cacheMaxEntries = 16
|
// The sitemaps are served from the slot table, never generated per
|
||||||
|
// request, and every route is throttled per client IP (BucketSitemap). GET
|
||||||
// Routes mounts GET /sitemap.xml and GET /sitemap.xsl at the application
|
// /_sitemap/api/v1/html and /_sitemap/api/v1/html/{group} answer the HTML
|
||||||
// root without the backend middleware: search engines and browsers fetch
|
// sitemap's data (BucketHTML).
|
||||||
// them anonymously. /sitemap.xml resolves every registry item, so it is
|
|
||||||
// throttled per client IP (BucketSitemap) and its output is cached.
|
|
||||||
func (p *Plugin) Routes(r pact.Router) error {
|
func (p *Plugin) Routes(r pact.Router) error {
|
||||||
r.Get("/sitemap.xml", p.sitemapXML, "throttle:"+BucketSitemap)
|
r.Get("/sitemap.xml", p.sitemapIndex, "throttle:"+BucketSitemap)
|
||||||
r.Get("/sitemap.xsl", p.sitemapXSL)
|
r.Get("/_sitemap/files/{file}", p.sitemapFile, "throttle:"+BucketSitemap)
|
||||||
|
r.Where("file", `sitemap-(news|[a-z0-9-]+-[0-9]+)\.xml`)
|
||||||
|
r.Get("/_sitemap/indexnow/{file}", apicontrollers.KeyFile(p.booted), "throttle:"+BucketSitemap)
|
||||||
|
r.Where("file", apicontrollers.KeyFilePattern)
|
||||||
|
// The HTML sitemap's data (D-34), read by the site's server when it
|
||||||
|
// renders the HTML sitemap page; public, noindex, per-IP bucket
|
||||||
|
// sitemap-html.
|
||||||
|
r.Get("/_sitemap/api/v1/html", apicontrollers.HTMLOverview(p.booted), "throttle:"+BucketHTML)
|
||||||
|
r.Get("/_sitemap/api/v1/html/{group}", apicontrollers.HTMLGroup(p.booted), "throttle:"+BucketHTML)
|
||||||
|
r.Where("group", apicontrollers.GroupPattern)
|
||||||
|
// The management API (D-10): each route resolves the administrator
|
||||||
|
// from a backend token, a personal API token or the MCP dispatch and
|
||||||
|
// requires the sitemap permission; each one is an MCP tool (mcp.go).
|
||||||
|
r.Group("/_sitemap/api/v1", nil, func(g pact.Router) {
|
||||||
|
api := "throttle:" + BucketAPI
|
||||||
|
g.Get("/settings", apicontrollers.ShowSettings(p.booted), api)
|
||||||
|
g.Put("/settings", apicontrollers.UpdateSettings(p.booted), api)
|
||||||
|
g.Post("/rebuild", apicontrollers.Rebuild(p.booted), api)
|
||||||
|
})
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Buckets registers sitemap-xml: 60 requests a minute per client IP (behind
|
// booted returns the booted application.
|
||||||
// the configured trusted proxies). 429 bodies are surf's
|
func (p *Plugin) booted() *backpack.App { return p.app }
|
||||||
// {"message":"Too Many Attempts."}.
|
|
||||||
|
// Buckets registers sitemap-xml (60 requests a minute), sitemap-html (300
|
||||||
|
// a minute: the site's server renders every HTML sitemap page from it) and
|
||||||
|
// sitemap-api (300 a minute) per client IP, behind the configured trusted
|
||||||
|
// proxies. 429 bodies are
|
||||||
|
// surf's {"message":"Too Many Attempts."}.
|
||||||
func (p *Plugin) Buckets() map[string]surf.Bucket {
|
func (p *Plugin) Buckets() map[string]surf.Bucket {
|
||||||
trusted := surf.TrustedProxies(nil)
|
trusted := surf.TrustedProxies(nil)
|
||||||
if p.app != nil {
|
if p.app != nil {
|
||||||
trusted = surf.TrustedProxies(p.app.Config)
|
trusted = surf.TrustedProxies(p.app.Config)
|
||||||
}
|
}
|
||||||
return map[string]surf.Bucket{
|
bucket := func(name string, max int) surf.Bucket {
|
||||||
BucketSitemap: {
|
return surf.Bucket{
|
||||||
Name: BucketSitemap,
|
Name: name,
|
||||||
Max: 60,
|
Max: max,
|
||||||
Decay: time.Minute,
|
Decay: time.Minute,
|
||||||
Key: func(r *http.Request) string {
|
Key: func(r *http.Request) string {
|
||||||
return "sitemap-xml|" + surf.ClientIP(r, trusted)
|
return name + "|" + surf.ClientIP(r, trusted)
|
||||||
},
|
},
|
||||||
},
|
}
|
||||||
|
}
|
||||||
|
return map[string]surf.Bucket{
|
||||||
|
BucketSitemap: bucket(BucketSitemap, 60),
|
||||||
|
BucketHTML: bucket(BucketHTML, 300),
|
||||||
|
BucketAPI: bucket(BucketAPI, 300),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// sitemapCache holds generated sitemaps for the configured time. The key
|
// sitemapIndex serves the sitemap index: one <sitemap> per file that lists
|
||||||
// covers the root URL and the stored definition and settings, so a save of
|
// at least one address (classes.SitemapFiles: the per-group files, the
|
||||||
// either is served at once; registry content (a new post) shows after the
|
// image files and the News file), with the newest lastmod of its
|
||||||
// entry expires. gen lets one generation run at a time, so concurrent misses
|
// addresses. Without a
|
||||||
// wait for it instead of each resolving every registry item.
|
// site address (the setting, golem15.sitemap.site_url or app.url) it is a
|
||||||
type sitemapCache struct {
|
// 404: a <loc> is never built from the request's Host.
|
||||||
ttl time.Duration
|
func (p *Plugin) sitemapIndex(w http.ResponseWriter, r *http.Request) {
|
||||||
gen sync.Mutex
|
db, err := database(p.app)
|
||||||
mu sync.Mutex
|
|
||||||
entries map[string]cachedSitemap
|
|
||||||
}
|
|
||||||
|
|
||||||
type cachedSitemap struct {
|
|
||||||
xml string
|
|
||||||
expires time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
func newSitemapCache(ttl time.Duration) *sitemapCache {
|
|
||||||
return &sitemapCache{ttl: ttl, entries: map[string]cachedSitemap{}}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *sitemapCache) get(key string) (string, bool) {
|
|
||||||
if c == nil || c.ttl <= 0 || key == "" {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
e, ok := c.entries[key]
|
|
||||||
if !ok || time.Now().After(e.expires) {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
return e.xml, true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *sitemapCache) put(key, xml string) {
|
|
||||||
if c == nil || c.ttl <= 0 || key == "" {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.mu.Lock()
|
|
||||||
defer c.mu.Unlock()
|
|
||||||
if len(c.entries) >= cacheMaxEntries {
|
|
||||||
clear(c.entries)
|
|
||||||
}
|
|
||||||
c.entries[key] = cachedSitemap{xml: xml, expires: time.Now().Add(c.ttl)}
|
|
||||||
}
|
|
||||||
|
|
||||||
// cacheKey is a digest of the root URL, the definition's items and the
|
|
||||||
// settings; "" (no caching) when either does not encode.
|
|
||||||
func cacheKey(root string, def models.Definition, settings models.Settings) string {
|
|
||||||
items, err := json.Marshal(def.Items())
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
set, err := json.Marshal(settings)
|
|
||||||
if err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
h := sha256.New()
|
|
||||||
for _, part := range [][]byte{[]byte(root), items, set} {
|
|
||||||
h.Write(part)
|
|
||||||
h.Write([]byte{0})
|
|
||||||
}
|
|
||||||
return hex.EncodeToString(h.Sum(nil))
|
|
||||||
}
|
|
||||||
|
|
||||||
// sitemapXSL serves the embedded stylesheet, the PHP file byte for byte.
|
|
||||||
func (p *Plugin) sitemapXSL(w http.ResponseWriter, _ *http.Request) {
|
|
||||||
w.Header().Set("Content-Type", contentTypeXSL)
|
|
||||||
w.Header().Set("Cache-Control", cacheControl)
|
|
||||||
w.WriteHeader(http.StatusOK)
|
|
||||||
_, _ = w.Write(sitemapXSL)
|
|
||||||
}
|
|
||||||
|
|
||||||
// sitemapXML serves the definition with the fixed theme key: 404 when there
|
|
||||||
// is none, an empty application/xml body when it has no items, else the
|
|
||||||
// generated XML with the settings' frontend_url rewrite applied.
|
|
||||||
func (p *Plugin) sitemapXML(w http.ResponseWriter, r *http.Request) {
|
|
||||||
app := p.app
|
|
||||||
db, err := database(app)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var defs []models.Definition
|
db = db.WithContext(r.Context())
|
||||||
if err := db.WithContext(r.Context()).Where("theme = ?", models.DefinitionTheme).Order("id ASC").Limit(1).Find(&defs).Error; err != nil {
|
settings, err := classes.LoadSettings(db)
|
||||||
pluginLog.Error("golem15.sitemap: load definition", "error", err)
|
|
||||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if len(defs) == 0 {
|
|
||||||
pluginLog.Info("golem15.sitemap: No sitemap definition was found. Try creating one first.")
|
|
||||||
http.NotFound(w, r)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
settings, err := loadSettings(db.WithContext(r.Context()))
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pluginLog.Error("golem15.sitemap: load settings", "error", err)
|
pluginLog.Error("golem15.sitemap: load settings", "error", err)
|
||||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
root := backendURL(app, r)
|
site := classes.SiteURL(p.app, settings)
|
||||||
xml, err := p.generate(r, root, defs[0], settings)
|
if site == "" {
|
||||||
|
pluginLog.Warn("golem15.sitemap: no site address; set the sitemap setting, golem15.sitemap.site_url or app.url")
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
list, err := classes.SitemapFiles(db, p.app, settings, time.Now().UTC())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
pluginLog.Error("golem15.sitemap: generate", "error", err)
|
pluginLog.Error("golem15.sitemap: index", "error", err)
|
||||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
files := make([]classes.IndexFile, 0, len(list))
|
||||||
|
for _, f := range list {
|
||||||
|
files = append(files, classes.IndexFile{Loc: site + "/" + f.Name, LastMod: f.LastMod})
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := classes.WriteIndex(&buf, files); err != nil {
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeXML(w, buf.Bytes(), false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// sitemapFile serves one file: its listed addresses in the order they were
|
||||||
|
// first seen. An unknown file, or one without a listed address, is a 404.
|
||||||
|
// sitemap-images-<n>.xml is an image sitemap file (imageFile).
|
||||||
|
func (p *Plugin) sitemapFile(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if r.PathValue("file") == classes.NewsFile {
|
||||||
|
p.newsFile(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
grp, n, ok := classes.ParseFileName(r.PathValue("file"))
|
||||||
|
if !ok {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db, err := database(p.app)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db = db.WithContext(r.Context())
|
||||||
|
settings, err := classes.LoadSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
pluginLog.Error("golem15.sitemap: load settings", "error", err)
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
site := classes.SiteURL(p.app, settings)
|
||||||
|
if grp == classes.ImagesGroup {
|
||||||
|
p.imageFile(w, r, db, settings, site, n)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var rows []models.URL
|
||||||
|
if err := db.Where("grp = ? AND file_no = ? AND excluded_reason = ''", grp, n).Order("first_seen ASC, id ASC").Find(&rows).Error; err != nil {
|
||||||
|
pluginLog.Error("golem15.sitemap: file", "file", r.PathValue("file"), "error", err)
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entries := make([]classes.FileEntry, 0, len(rows))
|
||||||
|
for _, row := range rows {
|
||||||
|
loc := classes.Absolute(site, row.URL)
|
||||||
|
if loc == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
entry := classes.FileEntry{Loc: loc, LastMod: row.LastMod}
|
||||||
|
for _, a := range row.Alternates.Get() {
|
||||||
|
if href := classes.Absolute(site, a.Href); href != "" {
|
||||||
|
entry.Alternates = append(entry.Alternates, classes.FileAlternate{Hreflang: a.Hreflang, Href: href})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
entries = append(entries, entry)
|
||||||
|
}
|
||||||
|
if len(entries) == 0 {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := classes.WriteURLSet(&buf, entries); err != nil {
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeXML(w, buf.Bytes(), true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// imageFile serves image sitemap file n: each listed page with images
|
||||||
|
// numbered into it, in the order first seen, with its images (D-31). It is
|
||||||
|
// a 404 while the image sitemap is off, and for a file without such a page.
|
||||||
|
func (p *Plugin) imageFile(w http.ResponseWriter, r *http.Request, db *gorm.DB, settings models.Settings, site string, n int) {
|
||||||
|
if !settings.ImagesEnabled {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var rows []models.URL
|
||||||
|
if err := db.Where("image_file_no = ? AND excluded_reason = ''", n).Order("first_seen ASC, id ASC").Find(&rows).Error; err != nil {
|
||||||
|
pluginLog.Error("golem15.sitemap: image file", "file", n, "error", err)
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entries := make([]classes.ImageEntry, 0, len(rows))
|
||||||
|
for _, row := range rows {
|
||||||
|
loc := classes.Absolute(site, row.URL)
|
||||||
|
if loc == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
entry := classes.ImageEntry{Loc: loc}
|
||||||
|
for _, img := range row.Images.Get() {
|
||||||
|
if abs := classes.Absolute(site, img); abs != "" {
|
||||||
|
entry.Images = append(entry.Images, abs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(entry.Images) > 0 {
|
||||||
|
entries = append(entries, entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(entries) == 0 {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := classes.WriteImageURLSet(&buf, entries); err != nil {
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeXML(w, buf.Bytes(), true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// newsFile serves sitemap-news.xml (D-31): the articles of the last two
|
||||||
|
// days (classes.NewsEntries). It is a 404 while the News sitemap is off.
|
||||||
|
func (p *Plugin) newsFile(w http.ResponseWriter, r *http.Request) {
|
||||||
|
db, err := database(p.app)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
db = db.WithContext(r.Context())
|
||||||
|
settings, err := classes.LoadSettings(db)
|
||||||
|
if err != nil {
|
||||||
|
pluginLog.Error("golem15.sitemap: load settings", "error", err)
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if !settings.NewsEnabled || classes.SiteURL(p.app, settings) == "" {
|
||||||
|
http.NotFound(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
entries, err := classes.NewsEntries(db, p.app, settings, time.Now().UTC())
|
||||||
|
if err != nil {
|
||||||
|
pluginLog.Error("golem15.sitemap: news file", "error", err)
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := classes.WriteNewsURLSet(&buf, entries); err != nil {
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeXML(w, buf.Bytes(), true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeXML answers 200 with an XML body. A file carries X-Robots-Tag
|
||||||
|
// noindex, so search engines read it without indexing it as a page.
|
||||||
|
func writeXML(w http.ResponseWriter, body []byte, noindex bool) {
|
||||||
w.Header().Set("Content-Type", contentTypeXML)
|
w.Header().Set("Content-Type", contentTypeXML)
|
||||||
w.Header().Set("Cache-Control", cacheControl)
|
w.Header().Set("Cache-Control", cacheControl)
|
||||||
|
if noindex {
|
||||||
|
w.Header().Set("X-Robots-Tag", "noindex")
|
||||||
|
}
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
_, _ = w.Write([]byte(xml))
|
_, _ = w.Write(body)
|
||||||
}
|
|
||||||
|
|
||||||
// generate returns the sitemap of def with the frontend_url rewrite
|
|
||||||
// applied, from the cache when it holds it.
|
|
||||||
func (p *Plugin) generate(r *http.Request, root string, def models.Definition, settings models.Settings) (string, error) {
|
|
||||||
cache := p.cache
|
|
||||||
key := ""
|
|
||||||
if cache != nil && cache.ttl > 0 {
|
|
||||||
key = cacheKey(root, def, settings)
|
|
||||||
if xml, ok := cache.get(key); ok {
|
|
||||||
return xml, nil
|
|
||||||
}
|
|
||||||
cache.gen.Lock()
|
|
||||||
defer cache.gen.Unlock()
|
|
||||||
if xml, ok := cache.get(key); ok {
|
|
||||||
return xml, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
app := p.app
|
|
||||||
gen := &classes.Generator{Root: root, Settings: settings, Tiers: p.tiers, Events: app.Events}
|
|
||||||
if reg, ok := app.Lookup[*signpost.Registry](); ok && reg != nil {
|
|
||||||
gen.Resolver = reg
|
|
||||||
}
|
|
||||||
xml, err := gen.Generate(r.Context(), def.Items())
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
xml = classes.Rewrite(xml, classes.BackendURL(root), models.Text(settings.FrontendURL))
|
|
||||||
cache.put(key, xml)
|
|
||||||
return xml, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// loadSettings reads the settings row; without one the PHP defaults apply.
|
|
||||||
func loadSettings(db *gorm.DB) (models.Settings, error) {
|
|
||||||
var rows []models.Settings
|
|
||||||
if err := db.Where("id = ?", 1).Limit(1).Find(&rows).Error; err != nil {
|
|
||||||
return models.Settings{}, err
|
|
||||||
}
|
|
||||||
if len(rows) == 0 {
|
|
||||||
return models.DefaultSettings(), nil
|
|
||||||
}
|
|
||||||
return rows[0], nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// database returns the app's published *gorm.DB.
|
// database returns the app's published *gorm.DB.
|
||||||
@@ -236,59 +299,3 @@ func database(app *backpack.App) (*gorm.DB, error) {
|
|||||||
}
|
}
|
||||||
return db, nil
|
return db, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// backendURL is the root URL the sitemap's absolute URLs start with, PHP
|
|
||||||
// url('/') right-trimmed of slashes: app.url when it is set, else the
|
|
||||||
// request's scheme and Host. The scheme is https for a TLS connection, or
|
|
||||||
// when the immediate peer is in http.trusted_proxies and its last
|
|
||||||
// X-Forwarded-Proto value says https; a client that sends the header
|
|
||||||
// directly is ignored.
|
|
||||||
func backendURL(app *backpack.App, r *http.Request) string {
|
|
||||||
if app != nil && app.Config != nil {
|
|
||||||
if u := strings.TrimRight(strings.TrimSpace(app.Config.String("app.url")), "/"); u != "" {
|
|
||||||
return u
|
|
||||||
}
|
|
||||||
}
|
|
||||||
scheme := "http"
|
|
||||||
if isHTTPS(app, r) {
|
|
||||||
scheme = "https"
|
|
||||||
}
|
|
||||||
return strings.TrimRight(scheme+"://"+r.Host, "/")
|
|
||||||
}
|
|
||||||
|
|
||||||
func isHTTPS(app *backpack.App, r *http.Request) bool {
|
|
||||||
if r.TLS != nil {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if app == nil || app.Config == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
trusted := surf.TrustedProxies(app.Config)
|
|
||||||
if len(trusted) == 0 || !peerTrusted(r.RemoteAddr, trusted) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
values := r.Header.Values("X-Forwarded-Proto")
|
|
||||||
if len(values) == 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
hops := strings.Split(values[len(values)-1], ",")
|
|
||||||
return strings.EqualFold(strings.TrimSpace(hops[len(hops)-1]), "https")
|
|
||||||
}
|
|
||||||
|
|
||||||
func peerTrusted(remoteAddr string, trusted []netip.Prefix) bool {
|
|
||||||
host, _, err := net.SplitHostPort(remoteAddr)
|
|
||||||
if err != nil {
|
|
||||||
host = remoteAddr
|
|
||||||
}
|
|
||||||
addr, err := netip.ParseAddr(strings.Trim(host, "[]"))
|
|
||||||
if err != nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
addr = addr.Unmap()
|
|
||||||
for _, p := range trusted {
|
|
||||||
if p.Contains(addr) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,22 +1,21 @@
|
|||||||
package sitemap
|
package sitemap
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
|
||||||
"net/http/httptest"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
"git.golem15.com/golem15/summercms/modules/compass"
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TestBackendURL pins the root URL the sitemap's absolute URLs and the
|
// TestSiteURLPrecedence pins the site address every <loc> starts with
|
||||||
// frontend_url rewrite start from: app.url when set; else the request's
|
// (CONTEXT 2026-10-28): the setting, else golem15.sitemap.site_url, else
|
||||||
// Host with https for TLS, or for the last X-Forwarded-Proto hop of a peer
|
// app.url, each only when it is an absolute http(s) URL, trailing slashes
|
||||||
// in http.trusted_proxies, while a client that sends the header directly
|
// trimmed; nothing configured is "" (the request's Host is never used).
|
||||||
// gets http.
|
func TestSiteURLPrecedence(t *testing.T) {
|
||||||
func TestBackendURL(t *testing.T) {
|
|
||||||
app := func(t *testing.T, files map[string]string) *backpack.App {
|
app := func(t *testing.T, files map[string]string) *backpack.App {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
dir := t.TempDir()
|
dir := t.TempDir()
|
||||||
@@ -31,39 +30,52 @@ func TestBackendURL(t *testing.T) {
|
|||||||
}
|
}
|
||||||
return backpack.New(cfg)
|
return backpack.New(cfg)
|
||||||
}
|
}
|
||||||
trusted := app(t, map[string]string{"http.yaml": "trusted_proxies:\n - 10.0.0.0/8\n"})
|
text := func(s string) *string { return &s }
|
||||||
|
both := app(t, map[string]string{"app.yaml": "url: https://api.example.test/\n", "golem15.yaml": "sitemap:\n site_url: https://config.example.test/\n"})
|
||||||
|
appOnly := app(t, map[string]string{"app.yaml": "url: https://api.example.test/\n"})
|
||||||
for _, tc := range []struct {
|
for _, tc := range []struct {
|
||||||
name string
|
name string
|
||||||
app *backpack.App
|
app *backpack.App
|
||||||
remote string
|
settings models.Settings
|
||||||
proto []string
|
want string
|
||||||
tls bool
|
|
||||||
want string
|
|
||||||
}{
|
}{
|
||||||
{"app.url wins", app(t, map[string]string{"app.yaml": "url: https://api.example.test/\n"}), "203.0.113.9:1234", []string{"http"}, false, "https://api.example.test"},
|
{"setting wins", both, models.Settings{SiteURL: text("https://www.example.test/")}, "https://www.example.test"},
|
||||||
{"plain request", trusted, "203.0.113.9:1234", nil, false, "http://h.test"},
|
{"config key", both, models.Settings{}, "https://config.example.test"},
|
||||||
{"TLS", trusted, "203.0.113.9:1234", nil, true, "https://h.test"},
|
{"app.url", appOnly, models.Settings{}, "https://api.example.test"},
|
||||||
{"trusted proxy says https", trusted, "10.1.2.3:5000", []string{"https"}, false, "https://h.test"},
|
{"unsafe setting skipped", appOnly, models.Settings{SiteURL: text("javascript:alert(1)")}, "https://api.example.test"},
|
||||||
{"trusted proxy, last hop wins", trusted, "10.1.2.3:5000", []string{"https, http"}, false, "http://h.test"},
|
{"nothing configured", app(t, nil), models.Settings{}, ""},
|
||||||
{"trusted proxy, last header wins", trusted, "10.1.2.3:5000", []string{"http", "HTTPS"}, false, "https://h.test"},
|
{"nil app", nil, models.Settings{}, ""},
|
||||||
{"untrusted client says https", trusted, "203.0.113.9:1234", []string{"https"}, false, "http://h.test"},
|
|
||||||
{"no trusted proxies configured", app(t, nil), "10.1.2.3:5000", []string{"https"}, false, "http://h.test"},
|
|
||||||
{"nil app", nil, "10.1.2.3:5000", []string{"https"}, false, "http://h.test"},
|
|
||||||
{"IPv4-mapped trusted peer", trusted, "[::ffff:10.1.2.3]:5000", []string{"https"}, false, "https://h.test"},
|
|
||||||
{"unparsable peer", trusted, "not-an-address", []string{"https"}, false, "http://h.test"},
|
|
||||||
} {
|
} {
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
r := httptest.NewRequest("GET", "http://h.test/sitemap.xml", nil)
|
if got := classes.SiteURL(tc.app, tc.settings); got != tc.want {
|
||||||
r.RemoteAddr = tc.remote
|
t.Fatalf("SiteURL = %q, want %q", got, tc.want)
|
||||||
for _, v := range tc.proto {
|
|
||||||
r.Header.Add("X-Forwarded-Proto", v)
|
|
||||||
}
|
|
||||||
if tc.tls {
|
|
||||||
r.TLS = &tls.ConnectionState{}
|
|
||||||
}
|
|
||||||
if got := backendURL(tc.app, r); got != tc.want {
|
|
||||||
t.Fatalf("backendURL = %q, want %q", got, tc.want)
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestFileNames pins the per-group file names the index lists and the file
|
||||||
|
// route accepts.
|
||||||
|
func TestFileNames(t *testing.T) {
|
||||||
|
if got := classes.FileName("posts", 3); got != "sitemap-posts-3.xml" {
|
||||||
|
t.Fatalf("FileName = %q", got)
|
||||||
|
}
|
||||||
|
for name, want := range map[string]struct {
|
||||||
|
grp string
|
||||||
|
n int
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
"sitemap-posts-1.xml": {"posts", 1, true},
|
||||||
|
"sitemap-landing-pages-12.xml": {"landing-pages", 12, true},
|
||||||
|
"sitemap-posts-2-1.xml": {"posts-2", 1, true},
|
||||||
|
"sitemap-posts-0.xml": {"", 0, false},
|
||||||
|
"sitemap-Posts-1.xml": {"", 0, false},
|
||||||
|
"sitemap-posts.xml": {"", 0, false},
|
||||||
|
"sitemap-../x-1.xml": {"", 0, false},
|
||||||
|
} {
|
||||||
|
grp, n, ok := classes.ParseFileName(name)
|
||||||
|
if grp != want.grp || n != want.n || ok != want.ok {
|
||||||
|
t.Errorf("ParseFileName(%q) = %q %d %v, want %+v", name, grp, n, ok, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
11
schedule.go
Normal file
11
schedule.go
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package sitemap
|
||||||
|
|
||||||
|
import "git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
|
||||||
|
// Schedule runs sitemap:rebuild every night at 03:00 (app timezone), so
|
||||||
|
// the files follow content that changed without a record event.
|
||||||
|
func (p *Plugin) Schedule() []pact.ScheduledCommand {
|
||||||
|
return []pact.ScheduledCommand{{Command: "sitemap:rebuild", Cadence: pact.DailyAt(3, 0)}}
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ pact.HasSchedule = (*Plugin)(nil)
|
||||||
991
sitemap_extras_test.go
Normal file
991
sitemap_extras_test.go
Normal file
@@ -0,0 +1,991 @@
|
|||||||
|
package sitemap_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/contract"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/conga"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/fetchguard"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/party"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pier"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/surf"
|
||||||
|
)
|
||||||
|
|
||||||
|
// journalPluginID is a fake blog plugin with an article type (posts at
|
||||||
|
// /blog/<slug>) and a collection type (categories at /kategoria/<slug>)
|
||||||
|
// whose records live in contentStore. It knows nothing about the sitemap.
|
||||||
|
const journalPluginID = "acme.journal"
|
||||||
|
|
||||||
|
// The fake blog content types.
|
||||||
|
const (
|
||||||
|
postType = "acme-post"
|
||||||
|
categoryType = "acme-category"
|
||||||
|
)
|
||||||
|
|
||||||
|
// journalPlugin is acme.journal.
|
||||||
|
type journalPlugin struct{}
|
||||||
|
|
||||||
|
func (journalPlugin) ID() string { return journalPluginID }
|
||||||
|
func (journalPlugin) Requires() []string { return nil }
|
||||||
|
func (journalPlugin) Register(*backpack.App) error { return nil }
|
||||||
|
func (journalPlugin) Boot(*backpack.App) error { return nil }
|
||||||
|
|
||||||
|
func (journalPlugin) MenuItemTypes() []pact.MenuItemType {
|
||||||
|
typ := func(key, label, kind, pattern string) pact.MenuItemType {
|
||||||
|
return pact.MenuItemType{
|
||||||
|
Key: key,
|
||||||
|
Label: label,
|
||||||
|
DefaultPattern: pattern,
|
||||||
|
Placeholders: []string{"slug"},
|
||||||
|
Resolve: func(context.Context, pact.MenuItemResolve) (*pact.ResolvedMenuItem, error) {
|
||||||
|
return nil, nil
|
||||||
|
},
|
||||||
|
Content: &pact.ContentDescriptor{
|
||||||
|
Model: key,
|
||||||
|
Kind: kind,
|
||||||
|
Records: func(_ context.Context, in pact.ContentList) (pact.ContentPage, error) {
|
||||||
|
return contentStore.page(key, in), nil
|
||||||
|
},
|
||||||
|
Describe: func(context.Context, pact.ContentDescribe) (*pact.ContentRecord, error) {
|
||||||
|
return nil, nil
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return []pact.MenuItemType{
|
||||||
|
typ(postType, "Posts", pact.ContentKindArticle, "/blog/:slug"),
|
||||||
|
typ(categoryType, "Categories", pact.ContentKindCollection, "/kategoria/:slug"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ pact.HasMenuItemTypes = journalPlugin{}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
party.Register(journalPlugin{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// bootJournal boots the fake blog plugin and the sitemap on a fresh
|
||||||
|
// database with an empty content store; overrides set config keys.
|
||||||
|
func bootJournal(t *testing.T, overrides ...map[string]any) *sitemapEnv {
|
||||||
|
t.Helper()
|
||||||
|
contentStore.reset(t)
|
||||||
|
return bootPlugins(t, []string{journalPluginID, "golem15.sitemap"}, overrides...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// post is a published post in one locale at /blog/<slug>, first published
|
||||||
|
// at published, with images.
|
||||||
|
func post(id int, slug, locale string, published time.Time, images ...string) fakeRecord {
|
||||||
|
l := pact.ContentLocale{Locale: locale, URL: "/blog/" + slug, Title: "Post " + slug}
|
||||||
|
for i, img := range images {
|
||||||
|
if i == 0 {
|
||||||
|
l.Image = img
|
||||||
|
}
|
||||||
|
l.Images = append(l.Images, pact.ContentImage{URL: img})
|
||||||
|
}
|
||||||
|
return fakeRecord{ID: id, Published: true, LastMod: published, PublishedAt: &published, Locales: []pact.ContentLocale{l}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// exec runs one SQL statement on the test database.
|
||||||
|
func (e *sitemapEnv) exec(t *testing.T, sql string, args ...any) {
|
||||||
|
t.Helper()
|
||||||
|
if err := e.gdb.Exec(sql, args...).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// imageLocs lists the image:loc values of an image sitemap body.
|
||||||
|
func imageLocs(body string) []string {
|
||||||
|
var out []string
|
||||||
|
for _, m := range regexp.MustCompile(`<image:loc>([^<]*)</image:loc>`).FindAllStringSubmatch(body, -1) {
|
||||||
|
out = append(out, m[1])
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestImageSitemap is the tracer of D-31's image sitemap: a post's
|
||||||
|
// featured and body images appear, after a rebuild, in sitemap-images-1.xml
|
||||||
|
// linked from the index: the page's <loc> and one image:image/image:loc per
|
||||||
|
// image (featured first, repeated and unsafe addresses dropped, paths made
|
||||||
|
// absolute), only those two tags, at most 1000 per page; a page without
|
||||||
|
// images is not listed; images_enabled off takes the files out of the index
|
||||||
|
// and answers 404.
|
||||||
|
func TestImageSitemap(t *testing.T) {
|
||||||
|
e := bootJournal(t)
|
||||||
|
at := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
contentStore.put(postType, post(1, "a", "en", at, "/media/a.jpg", "/media/a.jpg", "https://cdn.example.test/b.png", "javascript:alert(1)", "/media/c&d.webp"))
|
||||||
|
contentStore.put(postType, post(2, "b", "en", at.Add(time.Hour)))
|
||||||
|
many := make([]string, 1200)
|
||||||
|
for i := range many {
|
||||||
|
many[i] = fmt.Sprintf("/media/many-%d.jpg", i)
|
||||||
|
}
|
||||||
|
contentStore.put(postType, post(3, "c", "en", at.Add(2*time.Hour), many...))
|
||||||
|
e.rebuild(t)
|
||||||
|
|
||||||
|
index := e.get(t, "/sitemap.xml").Body.String()
|
||||||
|
if got := locs(index); strings.Join(got, " ") != "https://api.example.test/sitemap-posts-1.xml https://api.example.test/sitemap-images-1.xml" {
|
||||||
|
t.Fatalf("index locs = %v\n%s", got, index)
|
||||||
|
}
|
||||||
|
rec := e.get(t, "/_sitemap/files/sitemap-images-1.xml")
|
||||||
|
body := rec.Body.String()
|
||||||
|
if rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != "application/xml" || rec.Header().Get("X-Robots-Tag") != "noindex" {
|
||||||
|
t.Fatalf("image file: %d %v %s", rec.Code, rec.Header(), body)
|
||||||
|
}
|
||||||
|
if !strings.Contains(body, `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">`) {
|
||||||
|
t.Fatalf("image file head:\n%s", body[:min(len(body), 300)])
|
||||||
|
}
|
||||||
|
if got := locs(body); strings.Join(got, " ") != "https://api.example.test/blog/a https://api.example.test/blog/c" {
|
||||||
|
t.Fatalf("image file pages = %v", got)
|
||||||
|
}
|
||||||
|
first := body[strings.Index(body, "<url><loc>https://api.example.test/blog/a</loc>"):]
|
||||||
|
first = first[:strings.Index(first, "</url>")]
|
||||||
|
if got := imageLocs(first); strings.Join(got, " ") != "https://api.example.test/media/a.jpg https://cdn.example.test/b.png https://api.example.test/media/c&d.webp" {
|
||||||
|
t.Fatalf("post a images = %v\n%s", got, first)
|
||||||
|
}
|
||||||
|
if n := len(imageLocs(body)); n != 3+1000 {
|
||||||
|
t.Fatalf("image file lists %d images, want 1003", n)
|
||||||
|
}
|
||||||
|
for _, banned := range []string{"image:caption", "image:title", "javascript:", "<lastmod>", "xhtml"} {
|
||||||
|
if strings.Contains(body, banned) {
|
||||||
|
t.Errorf("image file contains %q", banned)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if rec := e.get(t, "/_sitemap/files/sitemap-images-2.xml"); rec.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("image file 2: %d", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stable numbering: with a file size of 1 the second page with images
|
||||||
|
// is renumbered into its own file once, and a page that loses its images
|
||||||
|
// leaves a hole instead of moving the later file.
|
||||||
|
e.setFileSize(t, 1)
|
||||||
|
e.rebuild(t)
|
||||||
|
if got := locs(e.get(t, "/_sitemap/files/sitemap-images-2.xml").Body.String()); strings.Join(got, " ") != "https://api.example.test/blog/c" {
|
||||||
|
t.Fatalf("image file 2 after the size change = %v", got)
|
||||||
|
}
|
||||||
|
contentStore.put(postType, post(1, "a", "en", at))
|
||||||
|
e.rebuild(t)
|
||||||
|
if rec := e.get(t, "/_sitemap/files/sitemap-images-1.xml"); rec.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("image file 1 without images: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if got := locs(e.get(t, "/_sitemap/files/sitemap-images-2.xml").Body.String()); strings.Join(got, " ") != "https://api.example.test/blog/c" {
|
||||||
|
t.Fatalf("image file 2 moved = %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.exec(t, `UPDATE golem15_sitemap_settings SET images_enabled = FALSE WHERE id = 1`)
|
||||||
|
if index := e.get(t, "/sitemap.xml").Body.String(); strings.Contains(index, "sitemap-images") {
|
||||||
|
t.Fatalf("index with the image sitemap off:\n%s", index)
|
||||||
|
}
|
||||||
|
if rec := e.get(t, "/_sitemap/files/sitemap-images-2.xml"); rec.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("image file with the image sitemap off: %d", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// newsLocs lists the <loc> values of a News sitemap.
|
||||||
|
func newsLocs(body string) []string { return locs(body) }
|
||||||
|
|
||||||
|
// TestNewsSitemap pins D-31's News sitemap (RESEARCH Pitfall 9): with
|
||||||
|
// news_enabled the index lists sitemap-news.xml with the articles first
|
||||||
|
// published in the last two days (1 and 47 hours ago, not 49), newest
|
||||||
|
// first, never a record of another kind; each with the publication name
|
||||||
|
// (news_publication, else app.name), the language of its locale, the
|
||||||
|
// publication date and the title; news_sources narrows it to the listed
|
||||||
|
// types and categories; more than 1000 candidates list the newest 1000;
|
||||||
|
// the settings form refuses a malformed source and lists the values to
|
||||||
|
// use; news_enabled off takes the file out of the index and answers 404.
|
||||||
|
func TestNewsSitemap(t *testing.T) {
|
||||||
|
e := bootJournal(t)
|
||||||
|
now := time.Now().UTC().Truncate(time.Second)
|
||||||
|
fresh := post(1, "fresh", "pl", now.Add(-time.Hour))
|
||||||
|
fresh.Locales[0].Title = `Grzyby & "huby"`
|
||||||
|
fresh.Parents = []pact.ContentRef{{Type: categoryType, ID: "3"}}
|
||||||
|
contentStore.put(postType, fresh)
|
||||||
|
contentStore.put(postType, post(2, "older", "en", now.Add(-47*time.Hour)))
|
||||||
|
contentStore.put(postType, post(3, "stale", "en", now.Add(-49*time.Hour)))
|
||||||
|
cat := now.Add(-time.Hour)
|
||||||
|
contentStore.put(categoryType, fakeRecord{ID: 3, Published: true, LastMod: cat, PublishedAt: &cat, Locales: []pact.ContentLocale{{Locale: "pl", URL: "/kategoria/lecznicze", Title: "Lecznicze"}}})
|
||||||
|
e.rebuild(t)
|
||||||
|
|
||||||
|
// Off by default: not in the index, the file is a 404.
|
||||||
|
if index := e.get(t, "/sitemap.xml").Body.String(); strings.Contains(index, "sitemap-news.xml") {
|
||||||
|
t.Fatalf("index with the News sitemap off:\n%s", index)
|
||||||
|
}
|
||||||
|
if rec := e.get(t, "/_sitemap/files/sitemap-news.xml"); rec.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("News file while off: %d", rec.Code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The settings form: the Images and News tab, a malformed source is
|
||||||
|
// refused, the partial lists the values.
|
||||||
|
token := e.admin(t, permSitemap)
|
||||||
|
const base = "/golem15/sitemap/settings"
|
||||||
|
schema := e.call(t, http.MethodGet, base+"/schema/form", token, nil).Body.String()
|
||||||
|
for _, want := range []string{`"images_enabled"`, `"news_enabled"`, `"news_publication"`, `"news_sources"`, "Images and News"} {
|
||||||
|
if !strings.Contains(schema, want) {
|
||||||
|
t.Errorf("form schema lacks %s", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, bad := range []any{[]string{"posts"}, []string{"category:acme-category"}, []string{"type:a b"}} {
|
||||||
|
if rec := e.call(t, http.MethodPut, base+"/1", token, map[string]any{"news_sources": bad}); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), `"news_sources"`) {
|
||||||
|
t.Errorf("news_sources %v: %d %s", bad, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rec := e.call(t, http.MethodGet, base+"/partials/news_sources", token, nil)
|
||||||
|
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "type:acme-post") || !strings.Contains(rec.Body.String(), "category:acme-category:3") || !strings.Contains(rec.Body.String(), "Categories: Lecznicze") {
|
||||||
|
t.Fatalf("news_sources partial: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if rec := e.call(t, http.MethodPut, base+"/1", token, map[string]any{"news_enabled": true, "news_sources": []string{}}); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("enable News: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
index := e.get(t, "/sitemap.xml").Body.String()
|
||||||
|
if !strings.Contains(index, "<loc>https://api.example.test/sitemap-news.xml</loc>") {
|
||||||
|
t.Fatalf("index lacks the News file:\n%s", index)
|
||||||
|
}
|
||||||
|
rec = e.get(t, "/_sitemap/files/sitemap-news.xml")
|
||||||
|
body := rec.Body.String()
|
||||||
|
if rec.Code != http.StatusOK || rec.Header().Get("X-Robots-Tag") != "noindex" || !strings.Contains(body, `xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"`) {
|
||||||
|
t.Fatalf("News file: %d %v\n%s", rec.Code, rec.Header(), body)
|
||||||
|
}
|
||||||
|
if got := newsLocs(body); strings.Join(got, " ") != "https://api.example.test/blog/fresh https://api.example.test/blog/older" {
|
||||||
|
t.Fatalf("News articles = %v\n%s", got, body)
|
||||||
|
}
|
||||||
|
wantFresh := "<url><loc>https://api.example.test/blog/fresh</loc><news:news><news:publication><news:name>sitemap-smoke</news:name><news:language>pl</news:language></news:publication><news:publication_date>" +
|
||||||
|
now.Add(-time.Hour).Format(time.RFC3339) + "</news:publication_date><news:title>Grzyby & "huby"</news:title></news:news></url>"
|
||||||
|
if !strings.Contains(body, wantFresh) {
|
||||||
|
t.Fatalf("News entry of the fresh post:\n%s\nwant %s", body, wantFresh)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The publication name setting and the sources.
|
||||||
|
e.exec(t, `UPDATE golem15_sitemap_settings SET news_publication = 'Gazeta', news_sources = '["category:acme-category:3"]' WHERE id = 1`)
|
||||||
|
body = e.get(t, "/_sitemap/files/sitemap-news.xml").Body.String()
|
||||||
|
if got := newsLocs(body); strings.Join(got, " ") != "https://api.example.test/blog/fresh" || !strings.Contains(body, "<news:name>Gazeta</news:name>") {
|
||||||
|
t.Fatalf("News with a category source = %v\n%s", got, body)
|
||||||
|
}
|
||||||
|
e.exec(t, `UPDATE golem15_sitemap_settings SET news_sources = '["type:acme-post"]' WHERE id = 1`)
|
||||||
|
if got := newsLocs(e.get(t, "/_sitemap/files/sitemap-news.xml").Body.String()); len(got) != 2 {
|
||||||
|
t.Fatalf("News with a type source = %v", got)
|
||||||
|
}
|
||||||
|
e.exec(t, `UPDATE golem15_sitemap_settings SET news_sources = '["type:acme-category"]' WHERE id = 1`)
|
||||||
|
if got := newsLocs(e.get(t, "/_sitemap/files/sitemap-news.xml").Body.String()); len(got) != 0 {
|
||||||
|
t.Fatalf("a collection type in the News sitemap = %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// More than 1000 candidates: the newest 1000.
|
||||||
|
e.exec(t, `UPDATE golem15_sitemap_settings SET news_sources = '[]' WHERE id = 1`)
|
||||||
|
for i := 0; i < 1005; i++ {
|
||||||
|
contentStore.put(postType, post(100+i, fmt.Sprintf("bulk-%d", i), "en", now.Add(-2*time.Hour-time.Duration(i)*time.Minute)))
|
||||||
|
}
|
||||||
|
e.rebuild(t)
|
||||||
|
got := newsLocs(e.get(t, "/_sitemap/files/sitemap-news.xml").Body.String())
|
||||||
|
if len(got) != 1000 || got[0] != "https://api.example.test/blog/fresh" || got[999] != "https://api.example.test/blog/bulk-998" {
|
||||||
|
t.Fatalf("News with 1007 candidates lists %d, first %v last %v", len(got), got[:1], got[len(got)-1:])
|
||||||
|
}
|
||||||
|
|
||||||
|
e.exec(t, `UPDATE golem15_sitemap_settings SET news_enabled = FALSE WHERE id = 1`)
|
||||||
|
if index := e.get(t, "/sitemap.xml").Body.String(); strings.Contains(index, "sitemap-news.xml") {
|
||||||
|
t.Fatalf("index after turning News off:\n%s", index)
|
||||||
|
}
|
||||||
|
if rec := e.get(t, "/_sitemap/files/sitemap-news.xml"); rec.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("News file after turning it off: %d", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// job returns the sitemap's registered job of kind.
|
||||||
|
func (e *sitemapEnv) job(t *testing.T, kind string) pact.Job {
|
||||||
|
t.Helper()
|
||||||
|
for _, p := range e.plugins {
|
||||||
|
hj, ok := p.(pact.HasJobs)
|
||||||
|
if !ok || p.ID() != "golem15.sitemap" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, j := range hj.Jobs() {
|
||||||
|
if info, ok := conga.Describe(j); ok && info.Kind == kind {
|
||||||
|
return j
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatalf("the sitemap registers no job %s", kind)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeIndexNow is the IndexNow engine of a test: it records each request
|
||||||
|
// and answers status.
|
||||||
|
type fakeIndexNow struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
status int
|
||||||
|
requests []*http.Request
|
||||||
|
bodies []map[string]any
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeIndexNow) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||||
|
raw, _ := io.ReadAll(r.Body)
|
||||||
|
body := map[string]any{}
|
||||||
|
_ = json.Unmarshal(raw, &body)
|
||||||
|
f.mu.Lock()
|
||||||
|
f.requests = append(f.requests, r)
|
||||||
|
f.bodies = append(f.bodies, body)
|
||||||
|
status := f.status
|
||||||
|
f.mu.Unlock()
|
||||||
|
return &http.Response{StatusCode: status, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("")), Request: r}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// queuedIndexNow decodes the URL lists of the queued IndexNow jobs, oldest
|
||||||
|
// first.
|
||||||
|
func (e *sitemapEnv) queuedIndexNow(t *testing.T) [][]string {
|
||||||
|
t.Helper()
|
||||||
|
var rows []string
|
||||||
|
if err := e.gdb.Raw(`SELECT args::text FROM river_job WHERE kind = ? ORDER BY id`, classes.IndexNowKind).Scan(&rows).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
out := make([][]string, 0, len(rows))
|
||||||
|
for _, raw := range rows {
|
||||||
|
var args classes.IndexNowArgs
|
||||||
|
if err := json.Unmarshal([]byte(raw), &args); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
out = append(out, args.URLs)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// indexNowKey reads the stored key.
|
||||||
|
func (e *sitemapEnv) indexNowKey(t *testing.T) string {
|
||||||
|
t.Helper()
|
||||||
|
var key *string
|
||||||
|
if err := e.gdb.Raw(`SELECT indexnow_key FROM golem15_sitemap_settings WHERE id = 1`).Scan(&key).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if key == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return *key
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestIndexNow drives D-31's IndexNow in production: enabling and saving
|
||||||
|
// generates a 32-hex key whose file answers text/plain (another name 404);
|
||||||
|
// a rebuild with a new and a removed address queues one job with both; the
|
||||||
|
// job posts {host, key, urlList} to api.indexnow.org and records the
|
||||||
|
// answer (202); 403 and 422 are recorded without retry, 429 fails the job
|
||||||
|
// so it retries; S2 shows each state; an address of another host is never
|
||||||
|
// sent; a new key makes the old file 404. Outside production nothing is
|
||||||
|
// queued or sent.
|
||||||
|
func TestIndexNow(t *testing.T) {
|
||||||
|
e := bootJournal(t, map[string]any{envOverride: "production"})
|
||||||
|
token := e.admin(t, permSitemap)
|
||||||
|
const base = "/golem15/sitemap/settings"
|
||||||
|
s2 := func() string {
|
||||||
|
t.Helper()
|
||||||
|
rec := e.call(t, http.MethodGet, base+"/partials/indexnow_status", token, nil)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("S2: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
return rec.Body.String()
|
||||||
|
}
|
||||||
|
if got := s2(); !strings.Contains(got, "A key is generated when you turn IndexNow on and save.") || !strings.Contains(got, "No notification sent yet.") {
|
||||||
|
t.Fatalf("S2 before a key:\n%s", got)
|
||||||
|
}
|
||||||
|
schema := e.call(t, http.MethodGet, base+"/schema/form", token, nil).Body.String()
|
||||||
|
for _, want := range []string{`"indexnow_enabled"`, `"indexnow_new_key"`, `"indexnow_status"`, "IndexNow"} {
|
||||||
|
if !strings.Contains(schema, want) {
|
||||||
|
t.Errorf("form schema lacks %s", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A rebuild before IndexNow is on queues nothing.
|
||||||
|
at := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
contentStore.put(postType, post(1, "a", "en", at))
|
||||||
|
e.rebuild(t)
|
||||||
|
if q := e.queuedIndexNow(t); len(q) != 0 {
|
||||||
|
t.Fatalf("queued while off: %v", q)
|
||||||
|
}
|
||||||
|
|
||||||
|
if rec := e.call(t, http.MethodPut, base+"/1", token, map[string]any{"indexnow_enabled": true}); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("enable IndexNow: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
key := e.indexNowKey(t)
|
||||||
|
if !regexp.MustCompile(`^[0-9a-f]{32}$`).MatchString(key) {
|
||||||
|
t.Fatalf("key = %q", key)
|
||||||
|
}
|
||||||
|
rec := e.get(t, "/_sitemap/indexnow/"+key+".txt")
|
||||||
|
if rec.Code != http.StatusOK || rec.Body.String() != key || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") {
|
||||||
|
t.Fatalf("key file: %d %q %v", rec.Code, rec.Body.String(), rec.Header())
|
||||||
|
}
|
||||||
|
for _, name := range []string{"0123456789abcdef0123456789abcdef.txt", "short.txt", key + ".xml"} {
|
||||||
|
if rec := e.get(t, "/_sitemap/indexnow/"+name); rec.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("key file %s: %d", name, rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := s2(); !strings.Contains(got, "Key: "+key+", served at https://api.example.test/"+key+".txt") {
|
||||||
|
t.Fatalf("S2 with a key:\n%s", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// One new address and one record deleted as the admin deletes it
|
||||||
|
// (pact.RecordDeleted): one job with both (L2 WR-01).
|
||||||
|
contentStore.put(postType, post(2, "b", "en", at))
|
||||||
|
e.deleteRecord(t, postType, postType, 1)
|
||||||
|
e.rebuild(t)
|
||||||
|
q := e.queuedIndexNow(t)
|
||||||
|
if len(q) != 1 || strings.Join(q[0], " ") != "https://api.example.test/blog/b https://api.example.test/blog/a" {
|
||||||
|
t.Fatalf("queued = %v", q)
|
||||||
|
}
|
||||||
|
// A content-only edit (pact.RecordSaved, the address kept) is sent as
|
||||||
|
// changed; a rebuild with nothing new queues nothing.
|
||||||
|
edited := post(2, "b", "en", at)
|
||||||
|
edited.Locales[0].Title = "Post b, edited"
|
||||||
|
e.editRecord(t, postType, postType, edited, pact.RecordChange{Attribute: "title"})
|
||||||
|
e.rebuild(t)
|
||||||
|
if got := e.queuedIndexNow(t); len(got) != 2 || strings.Join(got[1], " ") != "https://api.example.test/blog/b" {
|
||||||
|
t.Fatalf("queued after the edit = %v", got)
|
||||||
|
}
|
||||||
|
e.rebuild(t)
|
||||||
|
if got := e.queuedIndexNow(t); len(got) != 2 {
|
||||||
|
t.Fatalf("a rebuild with nothing new queued %v", got[2:])
|
||||||
|
}
|
||||||
|
var marks int64
|
||||||
|
e.gdb.Raw(`SELECT COUNT(*) FROM golem15_sitemap_urls WHERE indexnow_pending_at IS NOT NULL`).Scan(&marks)
|
||||||
|
if marks != 0 {
|
||||||
|
t.Fatalf("%d IndexNow marks left after the rebuild", marks)
|
||||||
|
}
|
||||||
|
|
||||||
|
engine := &fakeIndexNow{status: http.StatusAccepted}
|
||||||
|
ctx := fetchguard.WithTransport(t.Context(), engine)
|
||||||
|
job := e.job(t, classes.IndexNowKind)
|
||||||
|
args := classes.IndexNowArgs{URLs: append(q[0], "https://evil.test/x", "http://api.example.test.evil.test/y")}
|
||||||
|
if err := job.Work(ctx, args); err != nil {
|
||||||
|
t.Fatalf("IndexNow job: %v", err)
|
||||||
|
}
|
||||||
|
if len(engine.requests) != 1 {
|
||||||
|
t.Fatalf("%d requests", len(engine.requests))
|
||||||
|
}
|
||||||
|
req, body := engine.requests[0], engine.bodies[0]
|
||||||
|
if req.Method != http.MethodPost || req.URL.String() != "https://api.indexnow.org/indexnow" || !strings.HasPrefix(req.Header.Get("Content-Type"), "application/json") {
|
||||||
|
t.Fatalf("request = %s %s %v", req.Method, req.URL, req.Header)
|
||||||
|
}
|
||||||
|
list, _ := body["urlList"].([]any)
|
||||||
|
if body["host"] != "api.example.test" || body["key"] != key || len(list) != 2 || body["keyLocation"] != nil {
|
||||||
|
t.Fatalf("body = %v", body)
|
||||||
|
}
|
||||||
|
var last struct {
|
||||||
|
Status int `gorm:"column:indexnow_last_status"`
|
||||||
|
Count int `gorm:"column:indexnow_last_count"`
|
||||||
|
}
|
||||||
|
e.gdb.Raw(`SELECT indexnow_last_status, indexnow_last_count FROM golem15_sitemap_settings WHERE id = 1`).Scan(&last)
|
||||||
|
if last.Status != 202 || last.Count != 2 {
|
||||||
|
t.Fatalf("recorded = %+v", last)
|
||||||
|
}
|
||||||
|
if got := s2(); !strings.Contains(got, ", 2 addresses, answer 202.") || strings.Contains(got, "summer-callout--warning") {
|
||||||
|
t.Fatalf("S2 after 202:\n%s", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, c := range []struct {
|
||||||
|
status int
|
||||||
|
retry bool
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{http.StatusForbidden, false, "The engines could not read the key file at https://api.example.test/" + key + ".txt."},
|
||||||
|
{http.StatusUnprocessableEntity, false, "The engines refused the addresses because they do not match the site address."},
|
||||||
|
{http.StatusBadRequest, false, "answer 400."},
|
||||||
|
{http.StatusTooManyRequests, true, "Too many notifications; the next attempt is at "},
|
||||||
|
} {
|
||||||
|
engine.status = c.status
|
||||||
|
err := job.Work(ctx, classes.IndexNowArgs{URLs: q[0]})
|
||||||
|
if (err != nil) != c.retry {
|
||||||
|
t.Errorf("status %d: job error %v, want retry %v", c.status, err, c.retry)
|
||||||
|
}
|
||||||
|
if got := s2(); !strings.Contains(got, c.want) {
|
||||||
|
t.Errorf("S2 after %d lacks %q:\n%s", c.status, c.want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A new key: the old file answers 404 at once.
|
||||||
|
if rec := e.call(t, http.MethodPut, base+"/1", token, map[string]any{"indexnow_enabled": true, "indexnow_new_key": true}); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("new key: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
fresh := e.indexNowKey(t)
|
||||||
|
if fresh == key || len(fresh) != 32 {
|
||||||
|
t.Fatalf("new key = %q (old %q)", fresh, key)
|
||||||
|
}
|
||||||
|
if rec := e.get(t, "/_sitemap/indexnow/"+key+".txt"); rec.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("old key file: %d", rec.Code)
|
||||||
|
}
|
||||||
|
if rec := e.get(t, "/_sitemap/indexnow/"+fresh+".txt"); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("new key file: %d", rec.Code)
|
||||||
|
}
|
||||||
|
// A save without the checkbox keeps the key; turning IndexNow off
|
||||||
|
// takes the file down.
|
||||||
|
e.call(t, http.MethodPut, base+"/1", token, map[string]any{"indexnow_enabled": true})
|
||||||
|
if got := e.indexNowKey(t); got != fresh {
|
||||||
|
t.Fatalf("a plain save changed the key to %q", got)
|
||||||
|
}
|
||||||
|
e.call(t, http.MethodPut, base+"/1", token, map[string]any{"indexnow_enabled": false})
|
||||||
|
if rec := e.get(t, "/_sitemap/indexnow/"+fresh+".txt"); rec.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("key file while off: %d", rec.Code)
|
||||||
|
}
|
||||||
|
before := len(engine.requests)
|
||||||
|
if err := job.Work(ctx, classes.IndexNowArgs{URLs: q[0]}); err != nil || len(engine.requests) != before {
|
||||||
|
t.Fatalf("job while off: %v, %d requests", err, len(engine.requests)-before)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestIndexNowStaging pins T-33-15: outside production a rebuild queues no
|
||||||
|
// IndexNow job and the job sends nothing.
|
||||||
|
func TestIndexNowStaging(t *testing.T) {
|
||||||
|
e := bootJournal(t)
|
||||||
|
e.exec(t, `UPDATE golem15_sitemap_settings SET indexnow_enabled = TRUE, indexnow_key = '0123456789abcdef0123456789abcdef' WHERE id = 1`)
|
||||||
|
contentStore.put(postType, post(1, "a", "en", time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)))
|
||||||
|
contentStore.put(postType, post(2, "b", "en", time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)))
|
||||||
|
e.rebuild(t)
|
||||||
|
e.deleteRecord(t, postType, postType, 1)
|
||||||
|
e.editRecord(t, postType, postType, post(2, "b", "en", time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)), pact.RecordChange{Attribute: "title"})
|
||||||
|
e.rebuild(t)
|
||||||
|
if q := e.queuedIndexNow(t); len(q) != 0 {
|
||||||
|
t.Fatalf("queued outside production: %v", q)
|
||||||
|
}
|
||||||
|
var marks int64
|
||||||
|
e.gdb.Raw(`SELECT COUNT(*) FROM golem15_sitemap_urls WHERE indexnow_pending_at IS NOT NULL`).Scan(&marks)
|
||||||
|
if marks != 0 {
|
||||||
|
t.Fatalf("%d IndexNow marks left outside production", marks)
|
||||||
|
}
|
||||||
|
engine := &fakeIndexNow{status: http.StatusOK}
|
||||||
|
if err := e.job(t, classes.IndexNowKind).Work(fetchguard.WithTransport(t.Context(), engine), classes.IndexNowArgs{URLs: []string{"https://api.example.test/blog/a"}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(engine.requests) != 0 {
|
||||||
|
t.Fatalf("%d requests outside production", len(engine.requests))
|
||||||
|
}
|
||||||
|
if rec := e.get(t, "/_sitemap/indexnow/0123456789abcdef0123456789abcdef.txt"); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("key file outside production: %d", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// htmlJSON fetches an HTML sitemap API path and decodes its answer.
|
||||||
|
func (e *sitemapEnv) htmlJSON(t *testing.T, path string, status int) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
rec := e.get(t, path)
|
||||||
|
if rec.Code != status {
|
||||||
|
t.Fatalf("GET %s: %d, want %d: %s", path, rec.Code, status, rec.Body.String())
|
||||||
|
}
|
||||||
|
if rec.Header().Get("X-Robots-Tag") != "noindex" {
|
||||||
|
t.Errorf("GET %s lacks X-Robots-Tag noindex: %v", path, rec.Header())
|
||||||
|
}
|
||||||
|
out := map[string]any{}
|
||||||
|
if status == http.StatusOK {
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
||||||
|
t.Fatalf("decode %s: %v", rec.Body.String(), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// titlesOfEntries lists the titles of decoded entries, children in
|
||||||
|
// brackets.
|
||||||
|
func titlesOfEntries(v any) string {
|
||||||
|
list, _ := v.([]any)
|
||||||
|
var parts []string
|
||||||
|
for _, item := range list {
|
||||||
|
e, _ := item.(map[string]any)
|
||||||
|
s, _ := e["title"].(string)
|
||||||
|
if kids, ok := e["children"]; ok {
|
||||||
|
s += "[" + titlesOfEntries(kids) + "]"
|
||||||
|
}
|
||||||
|
parts = append(parts, s)
|
||||||
|
}
|
||||||
|
return strings.Join(parts, ", ")
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestHTMLGroups pins D-34's HTML sitemap API: the overview of a locale
|
||||||
|
// lists the groups in the L3 order (pages, offers, categories, posts) with
|
||||||
|
// titles in the locale, categories nested by parent, posts newest first,
|
||||||
|
// others alphabetical, the first html_page_size links and more when there
|
||||||
|
// are more; a group page pages the rest; past the last page, an unknown
|
||||||
|
// group and the HTML sitemap off are 404; excluded addresses never appear;
|
||||||
|
// every answer is noindex. The settings tab validates its values and
|
||||||
|
// contract.Listing answers the HTML sitemap and key file settings.
|
||||||
|
func TestHTMLGroups(t *testing.T) {
|
||||||
|
contentStore.reset(t)
|
||||||
|
e := bootPlugins(t, []string{contentPluginID, journalPluginID, filterPluginID, "golem15.sitemap"})
|
||||||
|
at := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
pl := func(id int, url, title string) fakeRecord {
|
||||||
|
return fakeRecord{ID: id, Published: true, LastMod: at, Locales: []pact.ContentLocale{{Locale: "pl", URL: url, Title: title}}}
|
||||||
|
}
|
||||||
|
contentStore.put(pageType, pl(1, "/pages/o-nas", "O nas"))
|
||||||
|
contentStore.put(pageType, pl(2, "/pages/kontakt", "Kontakt"))
|
||||||
|
contentStore.put(pageType, pl(3, "/pages/noindex-me", "Ukryta"))
|
||||||
|
contentStore.put(pageType, fakeRecord{ID: 4, Published: true, LastMod: at, Locales: []pact.ContentLocale{{Locale: "en", URL: "/pages/about", Title: "About"}}})
|
||||||
|
contentStore.put(offerType, pl(1, "/offers/zestaw", "Zestaw"))
|
||||||
|
cat := func(id int, slug, title string, parent int) fakeRecord {
|
||||||
|
r := pl(id, "/kategoria/"+slug, title)
|
||||||
|
if parent > 0 {
|
||||||
|
r.Parents = []pact.ContentRef{{Type: categoryType, ID: fmt.Sprint(parent)}}
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
contentStore.put(categoryType, cat(1, "grzyby", "Grzyby", 0))
|
||||||
|
contentStore.put(categoryType, cat(2, "lecznicze", "Lecznicze", 1))
|
||||||
|
contentStore.put(categoryType, cat(3, "jadalne", "Jadalne", 1))
|
||||||
|
contentStore.put(categoryType, cat(4, "inne", "Inne", 0))
|
||||||
|
for i := 1; i <= 160; i++ {
|
||||||
|
contentStore.put(postType, post(i, fmt.Sprintf("p%03d", i), "pl", at.Add(time.Duration(i)*time.Hour)))
|
||||||
|
}
|
||||||
|
e.exec(t, `INSERT INTO golem15_sitemap_types (type_key, include, slug, titles, updated_at) VALUES (?, TRUE, '', '{"pl":"Wpisy","en":"Posts"}', NOW())`, postType)
|
||||||
|
e.rebuild(t)
|
||||||
|
|
||||||
|
ov := e.htmlJSON(t, "/_sitemap/api/v1/html?locale=pl", http.StatusOK)
|
||||||
|
groups, _ := ov["groups"].([]any)
|
||||||
|
var order []string
|
||||||
|
byKey := map[string]map[string]any{}
|
||||||
|
for _, g := range groups {
|
||||||
|
m := g.(map[string]any)
|
||||||
|
order = append(order, m["slug"].(string))
|
||||||
|
byKey[m["slug"].(string)] = m
|
||||||
|
}
|
||||||
|
if strings.Join(order, " ") != "pages offers categories posts" {
|
||||||
|
t.Fatalf("group order = %v\n%v", order, ov)
|
||||||
|
}
|
||||||
|
if got := titlesOfEntries(byKey["pages"]["entries"]); got != "Kontakt, O nas" {
|
||||||
|
t.Errorf("pages = %s", got)
|
||||||
|
}
|
||||||
|
if got := titlesOfEntries(byKey["categories"]["entries"]); got != "Grzyby[Jadalne, Lecznicze], Inne" {
|
||||||
|
t.Errorf("categories tree = %s", got)
|
||||||
|
}
|
||||||
|
posts := byKey["posts"]
|
||||||
|
entries, _ := posts["entries"].([]any)
|
||||||
|
if posts["title"] != "Wpisy" || posts["total"] != float64(160) || posts["more"] != true || len(entries) != 150 {
|
||||||
|
t.Fatalf("posts group = title %v total %v more %v entries %d", posts["title"], posts["total"], posts["more"], len(entries))
|
||||||
|
}
|
||||||
|
if first := entries[0].(map[string]any); first["title"] != "Post p160" || first["url"] != "https://api.example.test/blog/p160" {
|
||||||
|
t.Errorf("newest post first: %v", first)
|
||||||
|
}
|
||||||
|
if byKey["categories"]["title"] != "Categories" || byKey["pages"]["more"] != false {
|
||||||
|
t.Errorf("categories title %v, pages more %v", byKey["categories"]["title"], byKey["pages"]["more"])
|
||||||
|
}
|
||||||
|
all := fmt.Sprint(ov)
|
||||||
|
for _, banned := range []string{"Ukryta", "noindex-me", "About"} {
|
||||||
|
if strings.Contains(all, banned) {
|
||||||
|
t.Errorf("the pl overview lists %q", banned)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if en := fmt.Sprint(e.htmlJSON(t, "/_sitemap/api/v1/html?locale=en", http.StatusOK)); !strings.Contains(en, "About") || strings.Contains(en, "Kontakt") {
|
||||||
|
t.Errorf("the en overview: %s", en)
|
||||||
|
}
|
||||||
|
|
||||||
|
page2 := e.htmlJSON(t, "/_sitemap/api/v1/html/posts?locale=pl&page=2", http.StatusOK)
|
||||||
|
if p2, _ := page2["entries"].([]any); page2["page"] != float64(2) || page2["pages"] != float64(2) || page2["group"] != "posts" || page2["title"] != "Wpisy" || len(p2) != 10 {
|
||||||
|
t.Fatalf("posts page 2 = %v", page2)
|
||||||
|
}
|
||||||
|
if got := titlesOfEntries(page2["entries"]); !strings.HasPrefix(got, "Post p010, Post p009") || !strings.HasSuffix(got, "Post p001") {
|
||||||
|
t.Errorf("posts page 2 = %s", got)
|
||||||
|
}
|
||||||
|
if p1 := e.htmlJSON(t, "/_sitemap/api/v1/html/posts?locale=pl", http.StatusOK); p1["page"] != float64(1) {
|
||||||
|
t.Errorf("posts without page = %v", p1["page"])
|
||||||
|
}
|
||||||
|
if got := titlesOfEntries(e.htmlJSON(t, "/_sitemap/api/v1/html/categories?locale=pl", http.StatusOK)["entries"]); got != "Grzyby[Jadalne, Lecznicze], Inne" {
|
||||||
|
t.Errorf("categories page = %s", got)
|
||||||
|
}
|
||||||
|
for _, path := range []string{
|
||||||
|
"/_sitemap/api/v1/html/posts?locale=pl&page=3",
|
||||||
|
"/_sitemap/api/v1/html/posts?locale=pl&page=0",
|
||||||
|
"/_sitemap/api/v1/html/posts?locale=pl&page=x",
|
||||||
|
"/_sitemap/api/v1/html/unknown?locale=pl",
|
||||||
|
"/_sitemap/api/v1/html/offers?locale=en",
|
||||||
|
"/_sitemap/api/v1/html?locale=%3Cx%3E",
|
||||||
|
} {
|
||||||
|
e.htmlJSON(t, path, http.StatusNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The settings tab.
|
||||||
|
token := e.admin(t, permSitemap)
|
||||||
|
const base = "/golem15/sitemap/settings"
|
||||||
|
schema := e.call(t, http.MethodGet, base+"/schema/form", token, nil).Body.String()
|
||||||
|
for _, want := range []string{`"html_enabled"`, `"html_path"`, `"html_page_size"`, "HTML sitemap"} {
|
||||||
|
if !strings.Contains(schema, want) {
|
||||||
|
t.Errorf("form schema lacks %s", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, c := range []struct {
|
||||||
|
body map[string]any
|
||||||
|
field string
|
||||||
|
}{
|
||||||
|
{map[string]any{"html_page_size": 49}, "html_page_size"},
|
||||||
|
{map[string]any{"html_page_size": 501}, "html_page_size"},
|
||||||
|
{map[string]any{"html_path": "mapa"}, "html_path"},
|
||||||
|
{map[string]any{"html_path": "/mapa?x=1"}, "html_path"},
|
||||||
|
{map[string]any{"html_path": "//evil.test"}, "html_path"},
|
||||||
|
} {
|
||||||
|
if rec := e.call(t, http.MethodPut, base+"/1", token, c.body); rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), `"`+c.field+`"`) {
|
||||||
|
t.Errorf("%v: %d %s", c.body, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
listing, ok := e.app.Lookup[contract.Listing]()
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("no contract.Listing")
|
||||||
|
}
|
||||||
|
ls, err := listing.Settings(t.Context())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !ls.HTMLEnabled || ls.HTMLPageSize != 150 || ls.HTMLPaths["pl"] != "/mapa-strony" || ls.HTMLPaths["en"] != "/sitemap" || ls.KeyFile != "" {
|
||||||
|
t.Fatalf("listing settings = %+v", ls)
|
||||||
|
}
|
||||||
|
if rec := e.call(t, http.MethodPut, base+"/1", token, map[string]any{"html_path": "/site-map", "html_page_size": 100}); rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("save the HTML tab: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
e.exec(t, `UPDATE golem15_sitemap_settings SET indexnow_enabled = TRUE, indexnow_key = '0123456789abcdef0123456789abcdef' WHERE id = 1`)
|
||||||
|
ls, _ = listing.Settings(t.Context())
|
||||||
|
if ls.HTMLPageSize != 100 || ls.HTMLPaths["en"] != "/site-map" || ls.HTMLPaths["pl"] != "/mapa-strony" || ls.KeyFile != "0123456789abcdef0123456789abcdef.txt" {
|
||||||
|
t.Fatalf("listing settings after the save = %+v", ls)
|
||||||
|
}
|
||||||
|
if p := e.htmlJSON(t, "/_sitemap/api/v1/html/posts?locale=pl&page=2", http.StatusOK); p["pages"] != float64(2) || len(p["entries"].([]any)) != 60 {
|
||||||
|
t.Errorf("posts page 2 at size 100 = pages %v", p["pages"])
|
||||||
|
}
|
||||||
|
|
||||||
|
e.call(t, http.MethodPut, base+"/1", token, map[string]any{"html_enabled": false})
|
||||||
|
e.htmlJSON(t, "/_sitemap/api/v1/html?locale=pl", http.StatusNotFound)
|
||||||
|
e.htmlJSON(t, "/_sitemap/api/v1/html/posts?locale=pl", http.StatusNotFound)
|
||||||
|
if ls, _ := listing.Settings(t.Context()); ls.HTMLEnabled {
|
||||||
|
t.Error("listing says the HTML sitemap is on")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// api sends a management API request with a bearer token (none when "")
|
||||||
|
// and a JSON body.
|
||||||
|
func (e *sitemapEnv) api(t *testing.T, method, path, token string, body any) *httptest.ResponseRecorder {
|
||||||
|
t.Helper()
|
||||||
|
var reader io.Reader
|
||||||
|
if body != nil {
|
||||||
|
raw, err := json.Marshal(body)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
reader = bytes.NewReader(raw)
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(method, path, reader)
|
||||||
|
req.Host = "api.example.test"
|
||||||
|
req.RemoteAddr = fmt.Sprintf("198.51.100.%d:4000", adminSeq.Add(1)%250+1)
|
||||||
|
req.Header.Set("Accept-Language", "en")
|
||||||
|
if body != nil {
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
if token != "" {
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
}
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
e.h.ServeHTTP(rec, req)
|
||||||
|
return rec
|
||||||
|
}
|
||||||
|
|
||||||
|
// apiJSON sends a management API request, fails unless it answers status
|
||||||
|
// and decodes the answer.
|
||||||
|
func (e *sitemapEnv) apiJSON(t *testing.T, status int, method, path, token string, body any) map[string]any {
|
||||||
|
t.Helper()
|
||||||
|
rec := e.api(t, method, path, token, body)
|
||||||
|
if rec.Code != status {
|
||||||
|
t.Fatalf("%s %s = %d, want %d: %s", method, path, rec.Code, status, rec.Body.String())
|
||||||
|
}
|
||||||
|
if rec.Header().Get("X-Robots-Tag") != "noindex" {
|
||||||
|
t.Errorf("%s %s lacks X-Robots-Tag noindex", method, path)
|
||||||
|
}
|
||||||
|
out := map[string]any{}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
||||||
|
t.Fatalf("decode %s: %v", rec.Body.String(), err)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSitemapTools pins D-10 for the sitemap: GET and PUT
|
||||||
|
// /_sitemap/api/v1/settings and POST /_sitemap/api/v1/rebuild need a
|
||||||
|
// backend administrator with the sitemap permission (401 without one, 403
|
||||||
|
// without the permission); PUT checks like the form (422, nothing
|
||||||
|
// stored), merges the HTML sitemap addresses, writes content types,
|
||||||
|
// generates the IndexNow key and queues a rebuild; an MCP dispatch runs as
|
||||||
|
// the linked administrator; the MCP catalog declares get_settings,
|
||||||
|
// update_settings and rebuild bound to those routes behind the permission.
|
||||||
|
func TestSitemapTools(t *testing.T) {
|
||||||
|
e := bootJournal(t)
|
||||||
|
contentStore.put(postType, post(1, "a", "en", time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC), "/media/a.jpg"))
|
||||||
|
e.rebuild(t)
|
||||||
|
routes := []struct{ method, path string }{
|
||||||
|
{http.MethodGet, "/_sitemap/api/v1/settings"},
|
||||||
|
{http.MethodPut, "/_sitemap/api/v1/settings"},
|
||||||
|
{http.MethodPost, "/_sitemap/api/v1/rebuild"},
|
||||||
|
}
|
||||||
|
other := e.admin(t)
|
||||||
|
for _, r := range routes {
|
||||||
|
if rec := e.api(t, r.method, r.path, "", map[string]any{}); rec.Code != http.StatusUnauthorized {
|
||||||
|
t.Errorf("%s %s without a token: %d %s", r.method, r.path, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if rec := e.api(t, r.method, r.path, other, map[string]any{}); rec.Code != http.StatusForbidden {
|
||||||
|
t.Errorf("%s %s without the permission: %d %s", r.method, r.path, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
token := e.admin(t, permSitemap)
|
||||||
|
data := e.apiJSON(t, http.StatusOK, http.MethodGet, "/_sitemap/api/v1/settings", token, nil)["data"].(map[string]any)
|
||||||
|
got := fmt.Sprint(data)
|
||||||
|
for _, want := range []string{"sitemap-posts-1.xml", "sitemap-images-1.xml", "https://api.example.test/sitemap.xml", "type:acme-post", "html_page_size:150", "indexnow:map["} {
|
||||||
|
if !strings.Contains(got, want) {
|
||||||
|
t.Errorf("GET settings lacks %q:\n%s", want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if types := data["types"].(map[string]any); types[postType] == nil || types[postType].(map[string]any)["slug"] != "posts" {
|
||||||
|
t.Errorf("types = %v", data["types"])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refusals name the fields and store nothing.
|
||||||
|
for _, c := range []struct {
|
||||||
|
body map[string]any
|
||||||
|
field string
|
||||||
|
}{
|
||||||
|
{map[string]any{"site_url": "https://other.test", "file_size": 0}, "file_size"},
|
||||||
|
{map[string]any{"html_page_size": 49}, "html_page_size"},
|
||||||
|
{map[string]any{"html_paths": map[string]string{"pl": "mapa"}}, "html_paths"},
|
||||||
|
{map[string]any{"news_sources": []string{"posts"}}, "news_sources"},
|
||||||
|
{map[string]any{"types": map[string]any{postType: map[string]any{"slug": "Bad Slug"}}}, "types." + postType + ".slug"},
|
||||||
|
{map[string]any{"types": map[string]any{"nope": map[string]any{"include": false}}}, "types.nope"},
|
||||||
|
} {
|
||||||
|
body := e.apiJSON(t, http.StatusUnprocessableEntity, http.MethodPut, "/_sitemap/api/v1/settings", token, c.body)
|
||||||
|
errs, _ := body["errors"].(map[string]any)
|
||||||
|
if body["error"] != "validation_failed" || errs[c.field] == nil {
|
||||||
|
t.Errorf("%v: %v", c.body, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if rec := e.api(t, http.MethodPut, "/_sitemap/api/v1/settings", token, map[string]any{"unknown_key": 1}); rec.Code != http.StatusUnprocessableEntity {
|
||||||
|
t.Errorf("unknown key: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
var site *string
|
||||||
|
e.gdb.Raw(`SELECT site_url FROM golem15_sitemap_settings WHERE id = 1`).Scan(&site)
|
||||||
|
if site != nil && *site != "" {
|
||||||
|
t.Fatalf("a refused PUT stored site_url %q", *site)
|
||||||
|
}
|
||||||
|
|
||||||
|
jobsBefore := e.riverJobs(t, classes.RebuildKind)
|
||||||
|
data = e.apiJSON(t, http.StatusOK, http.MethodPut, "/_sitemap/api/v1/settings", token, map[string]any{
|
||||||
|
"site_url": "https://www.example.test",
|
||||||
|
"news_enabled": true,
|
||||||
|
"news_sources": []string{"type:acme-post"},
|
||||||
|
"indexnow_enabled": true,
|
||||||
|
"html_paths": map[string]string{"en": "/site-map"},
|
||||||
|
"html_page_size": 200,
|
||||||
|
"types": map[string]any{postType: map[string]any{"slug": "blog", "titles": map[string]string{"en": "Blog"}}},
|
||||||
|
})["data"].(map[string]any)
|
||||||
|
settings := data["settings"].(map[string]any)
|
||||||
|
paths := settings["html_paths"].(map[string]any)
|
||||||
|
if settings["site_url"] != "https://www.example.test" || settings["news_enabled"] != true || settings["html_page_size"] != float64(200) || paths["en"] != "/site-map" || paths["pl"] != "/mapa-strony" {
|
||||||
|
t.Fatalf("settings after PUT = %v", settings)
|
||||||
|
}
|
||||||
|
key := data["indexnow"].(map[string]any)["key"].(string)
|
||||||
|
if len(key) != 32 || data["indexnow"].(map[string]any)["key_url"] != "https://www.example.test/"+key+".txt" {
|
||||||
|
t.Fatalf("indexnow after PUT = %v", data["indexnow"])
|
||||||
|
}
|
||||||
|
if pt := data["types"].(map[string]any)[postType].(map[string]any); pt["slug"] != "blog" || pt["titles"].(map[string]any)["en"] != "Blog" {
|
||||||
|
t.Fatalf("post type after PUT = %v", pt)
|
||||||
|
}
|
||||||
|
if n := e.riverJobs(t, classes.RebuildKind); n != jobsBefore+1 {
|
||||||
|
t.Fatalf("PUT queued %d rebuilds", n-jobsBefore)
|
||||||
|
}
|
||||||
|
data = e.apiJSON(t, http.StatusOK, http.MethodPut, "/_sitemap/api/v1/settings", token, map[string]any{"indexnow_new_key": true})["data"].(map[string]any)
|
||||||
|
if fresh := data["indexnow"].(map[string]any)["key"].(string); fresh == key || len(fresh) != 32 {
|
||||||
|
t.Fatalf("new key = %q (old %q)", fresh, key)
|
||||||
|
}
|
||||||
|
|
||||||
|
if body := e.apiJSON(t, http.StatusAccepted, http.MethodPost, "/_sitemap/api/v1/rebuild", token, nil); fmt.Sprint(body["data"]) != "map[queued:true]" {
|
||||||
|
t.Fatalf("rebuild = %v", body)
|
||||||
|
}
|
||||||
|
if n := e.riverJobs(t, classes.RebuildKind); n != jobsBefore+3 {
|
||||||
|
t.Fatalf("%d rebuilds queued, want %d", n, jobsBefore+3)
|
||||||
|
}
|
||||||
|
|
||||||
|
// An MCP call: in-process, without a token, as the linked administrator.
|
||||||
|
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||||
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
|
_, principal, err := cabana.ResolveBackend(e.app, req)
|
||||||
|
if err != nil || principal == nil {
|
||||||
|
t.Fatalf("principal: %v", err)
|
||||||
|
}
|
||||||
|
mcpReq := httptest.NewRequest(http.MethodGet, "/_sitemap/api/v1/settings", nil)
|
||||||
|
mcpReq.RemoteAddr = "198.51.100.7:4000"
|
||||||
|
mcpReq = mcpReq.WithContext(bouncer.WithDispatch(mcpReq.Context(), &bouncer.Dispatch{Guards: []string{"backend"}, Principal: principal}))
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
e.h.ServeHTTP(rec, mcpReq)
|
||||||
|
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"settings"`) {
|
||||||
|
t.Fatalf("MCP get_settings: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
// The catalog.
|
||||||
|
var tools []pact.MCPTool
|
||||||
|
for _, p := range e.plugins {
|
||||||
|
if m, ok := p.(pact.HasMCP); ok && p.ID() == "golem15.sitemap" {
|
||||||
|
tools = m.MCP().Tools
|
||||||
|
}
|
||||||
|
}
|
||||||
|
want := map[string]string{"get_settings": "GET /_sitemap/api/v1/settings", "update_settings": "PUT /_sitemap/api/v1/settings", "rebuild": "POST /_sitemap/api/v1/rebuild"}
|
||||||
|
if len(tools) != len(want) {
|
||||||
|
t.Fatalf("tools = %+v", tools)
|
||||||
|
}
|
||||||
|
for _, tool := range tools {
|
||||||
|
if want[tool.Name] != tool.Method+" "+tool.Path {
|
||||||
|
t.Errorf("tool %s is bound to %s %s", tool.Name, tool.Method, tool.Path)
|
||||||
|
}
|
||||||
|
if tool.Guard != "backend" || len(tool.Permissions) != 1 || tool.Permissions[0] != permSitemap {
|
||||||
|
t.Errorf("tool %s: guard %q permissions %v", tool.Name, tool.Guard, tool.Permissions)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// pier compiles the declarations against the registered routes.
|
||||||
|
router, err := surf.BuildRouter(e.app, e.plugins)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := e.app.Config.Set(pier.EnabledKey, true); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := pier.Mount(mountHost{r: router}, e.app, e.plugins); err != nil {
|
||||||
|
t.Fatalf("pier.Mount: %v", err)
|
||||||
|
}
|
||||||
|
pr, ok := e.app.Lookup[*pier.Pier]()
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("pier was not mounted")
|
||||||
|
}
|
||||||
|
if got := pr.ToolNames(); strings.Join(got, " ") != "sitemap_get_settings sitemap_rebuild sitemap_update_settings" {
|
||||||
|
t.Fatalf("compiled tools %v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// mountHost adapts a built surf router to pier.Host for a compile-only
|
||||||
|
// mount.
|
||||||
|
type mountHost struct{ r *surf.Router }
|
||||||
|
|
||||||
|
func (h mountHost) Routes() []pier.RouteInfo {
|
||||||
|
var out []pier.RouteInfo
|
||||||
|
for _, ri := range h.r.Routes() {
|
||||||
|
out = append(out, pier.RouteInfo{Method: ri.Method, Pattern: ri.Pattern, PluginID: ri.PluginID, Middleware: ri.Middleware})
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
func (h mountHost) Handler(method, pattern string) (http.Handler, bool) {
|
||||||
|
return h.r.Handler(method, pattern)
|
||||||
|
}
|
||||||
|
func (mountHost) MountStream(string, string, http.Handler, ...string) error { return nil }
|
||||||
|
func (mountHost) MountJSON(string, string, http.Handler) error { return nil }
|
||||||
|
func (h mountHost) Owner(method, path string) (string, bool) {
|
||||||
|
for _, ri := range h.r.Routes() {
|
||||||
|
if ri.Method == method && ri.Pattern == path {
|
||||||
|
return ri.PluginID, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
893
sitemap_index_test.go
Normal file
893
sitemap_index_test.go
Normal file
@@ -0,0 +1,893 @@
|
|||||||
|
package sitemap_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/console"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/contract"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
||||||
|
"git.golem15.com/golem15/sm-sitemap-plugin/updates"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"github.com/go-gormigrate/gormigrate/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// bootIndex boots the fake content plugin and the sitemap on a fresh
|
||||||
|
// database with an empty content store.
|
||||||
|
func bootIndex(t *testing.T, extra ...string) *sitemapEnv {
|
||||||
|
t.Helper()
|
||||||
|
contentStore.reset(t)
|
||||||
|
return bootPlugins(t, append([]string{contentPluginID, "golem15.sitemap"}, extra...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// rebuild runs the plugin's rebuild job once, as a worker would.
|
||||||
|
func (e *sitemapEnv) rebuild(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
for _, p := range e.plugins {
|
||||||
|
hj, ok := p.(pact.HasJobs)
|
||||||
|
if !ok || p.ID() != "golem15.sitemap" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, j := range hj.Jobs() {
|
||||||
|
if err := j.Work(context.Background(), classes.RebuildArgs{}); err != nil {
|
||||||
|
t.Fatalf("rebuild job: %v", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatal("the sitemap registers no rebuild job")
|
||||||
|
}
|
||||||
|
|
||||||
|
// setFileSize stores the file size setting.
|
||||||
|
func (e *sitemapEnv) setFileSize(t *testing.T, n int) {
|
||||||
|
t.Helper()
|
||||||
|
if err := e.gdb.Exec(`UPDATE golem15_sitemap_settings SET file_size = ? WHERE id = 1`, n).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// locs lists the <loc> values of a sitemap body in order.
|
||||||
|
func locs(body string) []string {
|
||||||
|
var out []string
|
||||||
|
for _, m := range regexp.MustCompile(`<loc>([^<]*)</loc>`).FindAllStringSubmatch(body, -1) {
|
||||||
|
out = append(out, m[1])
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSitemapIndex is the tracer of D-30: a content type's published
|
||||||
|
// records appear, after a rebuild job, in an index at /sitemap.xml that
|
||||||
|
// links per-group files of file_size addresses with absolute <loc> and a
|
||||||
|
// real <lastmod>; a draft is absent, no priority or change frequency is
|
||||||
|
// written, values are XML-escaped (T-33-09) and an unknown file is a 404.
|
||||||
|
func TestSitemapIndex(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
e.setFileSize(t, 2)
|
||||||
|
base := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
for i, slug := range []string{"a", "b", "c", "d"} {
|
||||||
|
contentStore.put(pageType, page1(i+1, slug, base.Add(time.Duration(i)*time.Hour)))
|
||||||
|
}
|
||||||
|
contentStore.put(pageType, fakeRecord{ID: 5, Published: true, LastMod: base, Locales: []pact.ContentLocale{{Locale: "en", URL: `/pages/fish&chips?x=<1>"`, Title: `Fish & "chips" <b>`}}})
|
||||||
|
contentStore.put(pageType, fakeRecord{ID: 6, Published: false, LastMod: base, Locales: []pact.ContentLocale{{Locale: "en", URL: "/pages/draft", Title: "Draft"}}})
|
||||||
|
|
||||||
|
if rec := e.get(t, "/sitemap.xml"); rec.Code != http.StatusOK || len(locs(rec.Body.String())) != 0 {
|
||||||
|
t.Fatalf("index before the first rebuild: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
e.rebuild(t)
|
||||||
|
|
||||||
|
rec := e.get(t, "/sitemap.xml")
|
||||||
|
body := rec.Body.String()
|
||||||
|
if rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != "application/xml" {
|
||||||
|
t.Fatalf("GET /sitemap.xml: %d %q %s", rec.Code, rec.Header().Get("Content-Type"), body)
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(body, `<?xml version="1.0" encoding="UTF-8"?>`) || !strings.Contains(body, `<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`) {
|
||||||
|
t.Fatalf("index head:\n%s", body)
|
||||||
|
}
|
||||||
|
want := []string{
|
||||||
|
"https://api.example.test/sitemap-pages-1.xml",
|
||||||
|
"https://api.example.test/sitemap-pages-2.xml",
|
||||||
|
"https://api.example.test/sitemap-pages-3.xml",
|
||||||
|
}
|
||||||
|
if got := locs(body); strings.Join(got, " ") != strings.Join(want, " ") {
|
||||||
|
t.Fatalf("index locs = %v, want %v\n%s", got, want, body)
|
||||||
|
}
|
||||||
|
if n := strings.Count(body, "<lastmod>"); n != 3 {
|
||||||
|
t.Fatalf("index has %d lastmod elements:\n%s", n, body)
|
||||||
|
}
|
||||||
|
if !strings.Contains(body, "<sitemap><loc>https://api.example.test/sitemap-pages-1.xml</loc><lastmod>2026-10-01T09:00:00Z</lastmod></sitemap>") {
|
||||||
|
t.Fatalf("file 1 lastmod is not the newest of its addresses:\n%s", body)
|
||||||
|
}
|
||||||
|
|
||||||
|
rec = e.get(t, "/_sitemap/files/sitemap-pages-1.xml")
|
||||||
|
file := rec.Body.String()
|
||||||
|
if rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != "application/xml" || rec.Header().Get("X-Robots-Tag") != "noindex" {
|
||||||
|
t.Fatalf("file 1: %d %v %s", rec.Code, rec.Header(), file)
|
||||||
|
}
|
||||||
|
if got := locs(file); strings.Join(got, " ") != "https://api.example.test/pages/a https://api.example.test/pages/b" {
|
||||||
|
t.Fatalf("file 1 locs = %v\n%s", got, file)
|
||||||
|
}
|
||||||
|
if !strings.Contains(file, "<url><loc>https://api.example.test/pages/a</loc><lastmod>2026-10-01T08:00:00Z</lastmod></url>") {
|
||||||
|
t.Fatalf("file 1 lacks a real lastmod:\n%s", file)
|
||||||
|
}
|
||||||
|
file3 := e.get(t, "/_sitemap/files/sitemap-pages-3.xml").Body.String()
|
||||||
|
if !strings.Contains(file3, "<loc>https://api.example.test/pages/fish&chips?x=<1>"</loc>") {
|
||||||
|
t.Fatalf("file 3 does not escape the address:\n%s", file3)
|
||||||
|
}
|
||||||
|
all := body + file + e.get(t, "/_sitemap/files/sitemap-pages-2.xml").Body.String() + file3
|
||||||
|
for _, banned := range []string{"<priority>", "<changefreq>", "/pages/draft", "xml-stylesheet", "xmlns:xhtml"} {
|
||||||
|
if strings.Contains(all, banned) {
|
||||||
|
t.Errorf("the sitemap contains %q:\n%s", banned, all)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, path := range []string{
|
||||||
|
"/_sitemap/files/sitemap-pages-4.xml",
|
||||||
|
"/_sitemap/files/sitemap-posts-1.xml",
|
||||||
|
"/_sitemap/files/sitemap-pages-0.xml",
|
||||||
|
"/_sitemap/files/other.xml",
|
||||||
|
"/sitemap.xsl",
|
||||||
|
} {
|
||||||
|
if rec := e.get(t, path); rec.Code != http.StatusNotFound {
|
||||||
|
t.Errorf("GET %s: %d, want 404", path, rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// permSitemap is the permission of the sitemap settings.
|
||||||
|
const permSitemap = "golem15.sitemap.access_definitions"
|
||||||
|
|
||||||
|
// riverJobs counts the queued jobs of kind.
|
||||||
|
func (e *sitemapEnv) riverJobs(t *testing.T, kind string) int64 {
|
||||||
|
t.Helper()
|
||||||
|
var n int64
|
||||||
|
if err := e.gdb.Raw(`SELECT COUNT(*) FROM river_job WHERE kind = ?`, kind).Scan(&n).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestSettingsSingleton drives the settings singleton (UI-SPEC C26): one
|
||||||
|
// tile opens it, the form has the Files, Content types and Additional
|
||||||
|
// addresses tabs, a save stores the values and dispatches a rebuild, the
|
||||||
|
// errors.* refusals answer 422 and leave the row as it was, a type switched
|
||||||
|
// off leaves the files with reason type and an additional address is listed
|
||||||
|
// in the pages group with its lastmod; S1 shows files.empty before the
|
||||||
|
// first build, files.building while the asked-for rebuild has not run, and
|
||||||
|
// the files with the left-out counts after it.
|
||||||
|
func TestSettingsSingleton(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
token := e.admin(t, permSitemap)
|
||||||
|
const base = "/golem15/sitemap/settings"
|
||||||
|
base0 := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
contentStore.put(pageType, page1(1, "a", base0))
|
||||||
|
contentStore.put(offerType, fakeRecord{ID: 1, Published: true, LastMod: base0, Locales: []pact.ContentLocale{{Locale: "en", URL: "/offers/x", Title: "Offer"}}})
|
||||||
|
|
||||||
|
// One tile, linked to the singleton; the Phase 17 tiles are gone.
|
||||||
|
rec := e.call(t, http.MethodGet, "/settings", token, nil)
|
||||||
|
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"controller":"golem15.sitemap.settings"`) ||
|
||||||
|
strings.Contains(rec.Body.String(), "golem15.sitemap.definitions") || strings.Contains(rec.Body.String(), "sitemap_settings") {
|
||||||
|
t.Fatalf("settings index: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
rec = e.call(t, http.MethodGet, base+"/singleton", token, nil)
|
||||||
|
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"id":1`) {
|
||||||
|
t.Fatalf("GET singleton: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
rec = e.call(t, http.MethodGet, base+"/schema/form", token, nil)
|
||||||
|
schema := rec.Body.String()
|
||||||
|
if rec.Code != http.StatusOK || !strings.Contains(schema, `"singleton":true`) {
|
||||||
|
t.Fatalf("form schema: %d %s", rec.Code, schema)
|
||||||
|
}
|
||||||
|
for _, want := range []string{`"site_url"`, `"file_size"`, `"extra_urls"`, `"type_acme_page_include"`, `"type_acme_page_slug"`, `"type_acme_page_title"`, `"type_acme_offer_include"`, "Files", "Content types", "Additional addresses"} {
|
||||||
|
if !strings.Contains(schema, want) {
|
||||||
|
t.Errorf("form schema lacks %s", want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
files := func() string {
|
||||||
|
t.Helper()
|
||||||
|
rec := e.call(t, http.MethodGet, base+"/partials/sitemap_files", token, nil)
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("S1: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
return rec.Body.String()
|
||||||
|
}
|
||||||
|
if s1 := files(); !strings.Contains(s1, "No files yet.") || strings.Contains(s1, "Rebuilding now.") {
|
||||||
|
t.Fatalf("S1 before the first build:\n%s", s1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Refusals leave the row as it was.
|
||||||
|
for _, c := range []struct {
|
||||||
|
name string
|
||||||
|
body map[string]any
|
||||||
|
field string
|
||||||
|
}{
|
||||||
|
{"file size 0", map[string]any{"file_size": 0}, "file_size"},
|
||||||
|
{"file size 50 001", map[string]any{"file_size": 50001}, "file_size"},
|
||||||
|
{"javascript site", map[string]any{"site_url": "javascript:alert(1)//"}, "site_url"},
|
||||||
|
{"relative site", map[string]any{"site_url": "/x"}, "site_url"},
|
||||||
|
{"bad address", map[string]any{"extra_urls": []map[string]any{{"url": "javascript:alert(1)", "lastmod": ""}}}, "extra_urls.0.url"},
|
||||||
|
{"bad lastmod", map[string]any{"extra_urls": []map[string]any{{"url": "/x", "lastmod": "yesterday"}}}, "extra_urls.0.lastmod"},
|
||||||
|
{"bad slug", map[string]any{"type_acme_page_slug": "Bad Slug"}, "type_acme_page_slug"},
|
||||||
|
{"duplicate slug", map[string]any{"type_acme_page_slug": "things", "type_acme_offer_slug": "things"}, "type_acme_offer_slug"},
|
||||||
|
{"reserved slug", map[string]any{"type_acme_page_slug": "images"}, "type_acme_page_slug"},
|
||||||
|
} {
|
||||||
|
rec := e.call(t, http.MethodPut, base+"/1", token, c.body)
|
||||||
|
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), `"`+c.field+`"`) {
|
||||||
|
t.Errorf("%s: %d %s", c.name, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var types int64
|
||||||
|
e.gdb.Raw(`SELECT COUNT(*) FROM golem15_sitemap_types`).Scan(&types)
|
||||||
|
if types != 0 || e.riverJobs(t, classes.RebuildKind) != 0 {
|
||||||
|
t.Fatalf("a refused save wrote %d type rows and queued %d rebuilds", types, e.riverJobs(t, classes.RebuildKind))
|
||||||
|
}
|
||||||
|
|
||||||
|
// A save stores everything and dispatches one rebuild.
|
||||||
|
rec = e.call(t, http.MethodPut, base+"/1", token, map[string]any{
|
||||||
|
"site_url": "https://www.example.test/",
|
||||||
|
"file_size": 500,
|
||||||
|
"extra_urls": []map[string]any{{"url": "/kontakt", "lastmod": "2026-09-30"}, {"url": "/o-nas", "lastmod": ""}},
|
||||||
|
"type_acme_page_include": true,
|
||||||
|
"type_acme_page_slug": "",
|
||||||
|
"type_acme_page_title": "Our pages",
|
||||||
|
"type_acme_offer_include": false,
|
||||||
|
"type_acme_offer_slug": "offers",
|
||||||
|
"type_acme_offer_title": "",
|
||||||
|
})
|
||||||
|
if rec.Code != http.StatusOK {
|
||||||
|
t.Fatalf("PUT settings: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
if n := e.riverJobs(t, classes.RebuildKind); n != 1 {
|
||||||
|
t.Fatalf("the save queued %d rebuild jobs, want 1", n)
|
||||||
|
}
|
||||||
|
var row struct {
|
||||||
|
SiteURL string `gorm:"column:site_url"`
|
||||||
|
FileSize int `gorm:"column:file_size"`
|
||||||
|
}
|
||||||
|
e.gdb.Raw(`SELECT site_url, file_size FROM golem15_sitemap_settings WHERE id = 1`).Scan(&row)
|
||||||
|
if row.SiteURL != "https://www.example.test/" || row.FileSize != 500 {
|
||||||
|
t.Fatalf("stored settings = %+v", row)
|
||||||
|
}
|
||||||
|
var stored []struct {
|
||||||
|
TypeKey string `gorm:"column:type_key"`
|
||||||
|
Include bool `gorm:"column:include"`
|
||||||
|
Slug string `gorm:"column:slug"`
|
||||||
|
Titles string `gorm:"column:titles"`
|
||||||
|
}
|
||||||
|
e.gdb.Raw(`SELECT type_key, include, slug, titles::text AS titles FROM golem15_sitemap_types ORDER BY type_key`).Scan(&stored)
|
||||||
|
if len(stored) != 2 || stored[0].TypeKey != offerType || stored[0].Include || stored[0].Slug != "" ||
|
||||||
|
stored[1].TypeKey != pageType || !stored[1].Include || !strings.Contains(stored[1].Titles, "Our pages") {
|
||||||
|
t.Fatalf("type rows = %+v", stored)
|
||||||
|
}
|
||||||
|
if s1 := files(); !strings.Contains(s1, "Rebuilding now.") {
|
||||||
|
t.Fatalf("S1 while the rebuild is queued:\n%s", s1)
|
||||||
|
}
|
||||||
|
rec = e.call(t, http.MethodGet, base+"/1", token, nil)
|
||||||
|
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"type_acme_page_title"`) || !strings.Contains(rec.Body.String(), "Our pages") {
|
||||||
|
t.Fatalf("GET settings: %d %s", rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
e.rebuild(t)
|
||||||
|
index := e.get(t, "/sitemap.xml").Body.String()
|
||||||
|
if got := locs(index); strings.Join(got, " ") != "https://www.example.test/sitemap-pages-1.xml" {
|
||||||
|
t.Fatalf("index after the save = %v\n%s", got, index)
|
||||||
|
}
|
||||||
|
pages := e.get(t, "/_sitemap/files/sitemap-pages-1.xml").Body.String()
|
||||||
|
if got := locs(pages); strings.Join(got, " ") != "https://www.example.test/pages/a https://www.example.test/kontakt https://www.example.test/o-nas" {
|
||||||
|
t.Fatalf("pages file = %v\n%s", got, pages)
|
||||||
|
}
|
||||||
|
if !strings.Contains(pages, "<loc>https://www.example.test/kontakt</loc><lastmod>2026-09-30T00:00:00Z</lastmod>") || !strings.Contains(pages, "<url><loc>https://www.example.test/o-nas</loc></url>") {
|
||||||
|
t.Fatalf("additional addresses lack their lastmod:\n%s", pages)
|
||||||
|
}
|
||||||
|
var reason string
|
||||||
|
e.gdb.Raw(`SELECT excluded_reason FROM golem15_sitemap_urls WHERE type_key = ?`, offerType).Scan(&reason)
|
||||||
|
if reason != "type" {
|
||||||
|
t.Fatalf("the switched-off type's row has reason %q", reason)
|
||||||
|
}
|
||||||
|
if listing, ok := e.app.Lookup[contract.Listing](); !ok {
|
||||||
|
t.Fatal("no contract.Listing")
|
||||||
|
} else if ls, err := listing.Settings(t.Context()); err != nil || strings.Join(ls.TypesOff, ",") != offerType {
|
||||||
|
t.Fatalf("listing TypesOff = %v err=%v, want [%s]", ls.TypesOff, err, offerType)
|
||||||
|
}
|
||||||
|
s1 := files()
|
||||||
|
for _, want := range []string{"sitemap.xml", "sitemap-pages-1.xml", `"href":"/_sitemap/files/sitemap-pages-1.xml"`, `"href":"/sitemap.xml"`, "Left out of the sitemaps", "Content type turned off", "https://www.example.test/sitemap.xml"} {
|
||||||
|
if !strings.Contains(s1, want) {
|
||||||
|
t.Errorf("S1 lacks %q:\n%s", want, s1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(s1, "Rebuilding now.") || strings.Contains(s1, "No files yet.") {
|
||||||
|
t.Errorf("S1 after the rebuild:\n%s", s1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without the permission every route answers 403.
|
||||||
|
other := e.admin(t)
|
||||||
|
for _, c := range []struct{ method, path string }{
|
||||||
|
{http.MethodGet, base + "/singleton"},
|
||||||
|
{http.MethodPut, base + "/1"},
|
||||||
|
{http.MethodGet, base + "/partials/sitemap_files"},
|
||||||
|
} {
|
||||||
|
if rec := e.call(t, c.method, c.path, other, map[string]any{}); rec.Code != http.StatusForbidden {
|
||||||
|
t.Errorf("%s %s without permission: %d %s", c.method, c.path, rec.Code, rec.Body.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestMigrateDefinitions pins the D-32 data move of migration
|
||||||
|
// 202610280002: the url items of the served definition (theme default)
|
||||||
|
// become the additional addresses as given (no lastmod, unsafe and repeated
|
||||||
|
// ones skipped), frontend_url becomes site_url and frontend_default_locale
|
||||||
|
// default_locale; reference items are dropped, the definitions table and
|
||||||
|
// the Phase 17 columns keep their data, and a rollback removes only the
|
||||||
|
// copied values.
|
||||||
|
func TestMigrateDefinitions(t *testing.T) {
|
||||||
|
sqlDB := freshDB(t)
|
||||||
|
gdb, err := lagoon.Use(t.Context(), sqlDB)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
all := updates.All()
|
||||||
|
opts := &gormigrate.Options{TableName: "sitemap_migrations", IDColumnName: "id", IDColumnSize: 255, UseTransaction: true}
|
||||||
|
upTo := 0
|
||||||
|
for i, m := range all {
|
||||||
|
if m.ID == "202610110002_create_golem15_sitemap_settings" {
|
||||||
|
upTo = i + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if upTo == 0 {
|
||||||
|
t.Fatal("the Phase 17 settings migration is missing")
|
||||||
|
}
|
||||||
|
if err := gormigrate.New(gdb, opts, all[:upTo]).Migrate(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
items := `[{"type":"url","url":"/","changefreq":"always","priority":"1.0"},` +
|
||||||
|
`{"type":"acme-post","reference":"7","nesting":true},` +
|
||||||
|
`{"type":"url","url":"/o-nas"},` +
|
||||||
|
`{"type":"url","url":"javascript:alert(1)"},` +
|
||||||
|
`{"type":"url","url":"/"},` +
|
||||||
|
`{"type":"url","url":"https://www.example.test/kontakt"},` +
|
||||||
|
`{"type":"url","url":"kontakt-pl"},` +
|
||||||
|
`{"type":"url","url":"/blog/zażółć gęślą"},` +
|
||||||
|
`{"type":"url","url":"https://www.example.test/x?a=1&b=2"},` +
|
||||||
|
`{"type":"url","url":{"bad":true}}]`
|
||||||
|
for _, stmt := range []struct {
|
||||||
|
sql string
|
||||||
|
args []any
|
||||||
|
}{
|
||||||
|
{`INSERT INTO golem15_sitemap_definitions (theme, data) VALUES (?, ?)`, []any{"default", items}},
|
||||||
|
{`INSERT INTO golem15_sitemap_definitions (theme, data) VALUES (?, ?)`, []any{"other", `[{"type":"url","url":"/other"}]`}},
|
||||||
|
{`UPDATE golem15_sitemap_settings SET frontend_url = ?, frontend_default_locale = ?, priority_blog = ? WHERE id = 1`, []any{"https://www.example.test/", "pl", "0.7"}},
|
||||||
|
} {
|
||||||
|
if err := gdb.Exec(stmt.sql, stmt.args...).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := gormigrate.New(gdb, opts, all).Migrate(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
s, err := classes.LoadSettings(gdb)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
// L2 WR-04: one malformed item no longer drops the definition, a
|
||||||
|
// relative path gets its slash and a space is percent-encoded; the &
|
||||||
|
// URL and javascript: are dropped (and logged).
|
||||||
|
if got := extraURLs(s.Extra()); got != "/ /o-nas https://www.example.test/kontakt /kontakt-pl /blog/zażółć%20gęślą" {
|
||||||
|
t.Fatalf("extra_urls = %q", got)
|
||||||
|
}
|
||||||
|
for _, e := range s.Extra() {
|
||||||
|
if e.LastMod != "" {
|
||||||
|
t.Fatalf("a copied address has a lastmod: %+v", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if models.Text(s.SiteURL) != "https://www.example.test/" || models.Text(s.DefaultLocale) != "pl" || s.EffectiveFileSize() != 1000 {
|
||||||
|
t.Fatalf("settings = %+v", s)
|
||||||
|
}
|
||||||
|
var defs int64
|
||||||
|
gdb.Raw(`SELECT COUNT(*) FROM golem15_sitemap_definitions`).Scan(&defs)
|
||||||
|
var data string
|
||||||
|
gdb.Raw(`SELECT data FROM golem15_sitemap_definitions WHERE theme = 'default'`).Scan(&data)
|
||||||
|
if defs != 2 || data != items {
|
||||||
|
t.Fatalf("the definitions table changed: %d rows, data %s", defs, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := gormigrate.New(gdb, opts, all).RollbackTo("202610110002_create_golem15_sitemap_settings"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var old struct {
|
||||||
|
FrontendURL string `gorm:"column:frontend_url"`
|
||||||
|
Locale string `gorm:"column:frontend_default_locale"`
|
||||||
|
Blog string `gorm:"column:priority_blog"`
|
||||||
|
}
|
||||||
|
gdb.Raw(`SELECT frontend_url, frontend_default_locale, priority_blog FROM golem15_sitemap_settings WHERE id = 1`).Scan(&old)
|
||||||
|
if old.FrontendURL != "https://www.example.test/" || old.Locale != "pl" || old.Blog != "0.7" {
|
||||||
|
t.Fatalf("the rollback changed the Phase 17 settings: %+v", old)
|
||||||
|
}
|
||||||
|
gdb.Raw(`SELECT COUNT(*) FROM golem15_sitemap_definitions`).Scan(&defs)
|
||||||
|
if defs != 2 {
|
||||||
|
t.Fatalf("the rollback changed the definitions: %d rows", defs)
|
||||||
|
}
|
||||||
|
var columns int64
|
||||||
|
gdb.Raw(`SELECT COUNT(*) FROM information_schema.columns WHERE table_name = 'golem15_sitemap_settings' AND column_name IN ('site_url', 'extra_urls')`).Scan(&columns)
|
||||||
|
if columns != 0 {
|
||||||
|
t.Fatalf("the rollback left %d copied columns", columns)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fileNos lists the file numbers of the listed rows of typ in record order.
|
||||||
|
func (e *sitemapEnv) fileNos(t *testing.T, typ string) []int {
|
||||||
|
t.Helper()
|
||||||
|
var out []int
|
||||||
|
if err := e.gdb.Raw(`SELECT file_no FROM golem15_sitemap_urls WHERE type_key = ? AND excluded_reason = '' ORDER BY record_id::int, locale`, typ).Scan(&out).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func intsEq(a []int, b ...int) bool {
|
||||||
|
if len(a) != len(b) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
for i := range a {
|
||||||
|
if a[i] != b[i] {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestStableNumbering pins D-30's numbering invariant over real rebuilds:
|
||||||
|
// 5 addresses at size 2 fill files 1,1,2,2,3; a deleted record leaves a
|
||||||
|
// hole in file 1 and files 2 and 3 keep their addresses; two new records go
|
||||||
|
// to file 3, then a new file 4; only a file size change renumbers.
|
||||||
|
func TestStableNumbering(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
e.setFileSize(t, 2)
|
||||||
|
base := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
for i := 1; i <= 5; i++ {
|
||||||
|
contentStore.put(pageType, page1(i, string(rune('a'+i-1)), base))
|
||||||
|
}
|
||||||
|
e.rebuild(t)
|
||||||
|
if got := e.fileNos(t, pageType); !intsEq(got, 1, 1, 2, 2, 3) {
|
||||||
|
t.Fatalf("first build: %v", got)
|
||||||
|
}
|
||||||
|
file2 := e.get(t, "/_sitemap/files/sitemap-pages-2.xml").Body.String()
|
||||||
|
|
||||||
|
contentStore.remove(pageType, 2)
|
||||||
|
e.rebuild(t)
|
||||||
|
if got := e.fileNos(t, pageType); !intsEq(got, 1, 2, 2, 3) {
|
||||||
|
t.Fatalf("after a delete: %v", got)
|
||||||
|
}
|
||||||
|
if got := locs(e.get(t, "/_sitemap/files/sitemap-pages-1.xml").Body.String()); len(got) != 1 || got[0] != "https://api.example.test/pages/a" {
|
||||||
|
t.Fatalf("file 1 after the delete: %v", got)
|
||||||
|
}
|
||||||
|
if again := e.get(t, "/_sitemap/files/sitemap-pages-2.xml").Body.String(); again != file2 {
|
||||||
|
t.Fatalf("file 2 changed after a delete in file 1:\n%s\n%s", file2, again)
|
||||||
|
}
|
||||||
|
var reason string
|
||||||
|
e.gdb.Raw(`SELECT excluded_reason FROM golem15_sitemap_urls WHERE type_key = ? AND record_id = '2'`, pageType).Scan(&reason)
|
||||||
|
if reason != "deleted" {
|
||||||
|
t.Fatalf("the deleted record's row has reason %q", reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
contentStore.put(pageType, page1(6, "f", base))
|
||||||
|
contentStore.put(pageType, page1(7, "g", base))
|
||||||
|
e.rebuild(t)
|
||||||
|
if got := e.fileNos(t, pageType); !intsEq(got, 1, 2, 2, 3, 3, 4) {
|
||||||
|
t.Fatalf("after two appends: %v", got)
|
||||||
|
}
|
||||||
|
index := locs(e.get(t, "/sitemap.xml").Body.String())
|
||||||
|
if len(index) != 4 || index[3] != "https://api.example.test/sitemap-pages-4.xml" {
|
||||||
|
t.Fatalf("index after appends: %v", index)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.setFileSize(t, 3)
|
||||||
|
e.rebuild(t)
|
||||||
|
if got := e.fileNos(t, pageType); !intsEq(got, 1, 1, 1, 2, 2, 2) {
|
||||||
|
t.Fatalf("after a file size change: %v", got)
|
||||||
|
}
|
||||||
|
if index := locs(e.get(t, "/sitemap.xml").Body.String()); len(index) != 2 {
|
||||||
|
t.Fatalf("index after renumbering: %v", index)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// lastmodOf reads the lastmod of one row.
|
||||||
|
func (e *sitemapEnv) lastmodOf(t *testing.T, typ, id, locale string) time.Time {
|
||||||
|
t.Helper()
|
||||||
|
var mod *time.Time
|
||||||
|
if err := e.gdb.Raw(`SELECT lastmod FROM golem15_sitemap_urls WHERE type_key = ? AND record_id = ? AND locale = ?`, typ, id, locale).Scan(&mod).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if mod == nil {
|
||||||
|
t.Fatalf("%s %s %s has no lastmod", typ, id, locale)
|
||||||
|
}
|
||||||
|
return mod.UTC()
|
||||||
|
}
|
||||||
|
|
||||||
|
// saved fires a RecordSaved of a fake page.
|
||||||
|
func (e *sitemapEnv) saved(t *testing.T, id string, changes ...pact.RecordChange) {
|
||||||
|
t.Helper()
|
||||||
|
if err := e.app.Events.Fire(context.Background(), &pact.RecordSaved{Model: pageModel, ID: id, Changes: changes}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestLastmod pins event-driven lastmod (D-30, RESEARCH Pitfall 4): a save
|
||||||
|
// whose changes touch a real attribute moves the lastmod of that record's
|
||||||
|
// rows (only the changed locale's row for a translated change); a no-op
|
||||||
|
// save or one that changes only ignored attributes does not; a rebuild
|
||||||
|
// never moves lastmod, even when the record's own LastMod moved; a deleted
|
||||||
|
// record leaves the files at once.
|
||||||
|
func TestLastmod(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
base := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
contentStore.put(pageType, page1(1, "a", base))
|
||||||
|
contentStore.put(pageType, fakeRecord{ID: 2, Published: true, LastMod: base, Locales: []pact.ContentLocale{
|
||||||
|
{Locale: "en", URL: "/pages/b", Title: "B"},
|
||||||
|
{Locale: "pl", URL: "/pl/strony/b", Title: "B pl"},
|
||||||
|
}})
|
||||||
|
e.rebuild(t)
|
||||||
|
if got := e.lastmodOf(t, pageType, "1", "en"); !got.Equal(base) {
|
||||||
|
t.Fatalf("first lastmod = %v, want the record's %v", got, base)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.saved(t, "1")
|
||||||
|
e.saved(t, "1", pact.RecordChange{Attribute: "updated_at"}, pact.RecordChange{Attribute: "views", Old: 1, New: 2})
|
||||||
|
if got := e.lastmodOf(t, pageType, "1", "en"); !got.Equal(base) {
|
||||||
|
t.Fatalf("a no-op or ignored save moved lastmod to %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
before := time.Now().Add(-time.Second)
|
||||||
|
e.saved(t, "1", pact.RecordChange{Attribute: "title", Old: "A", New: "A2"}, pact.RecordChange{Attribute: "updated_at"})
|
||||||
|
if got := e.lastmodOf(t, pageType, "1", "en"); got.Before(before) {
|
||||||
|
t.Fatalf("a title change left lastmod at %v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.saved(t, "2", pact.RecordChange{Attribute: "title", Locale: "pl", Old: "B pl", New: "B pl 2"})
|
||||||
|
if en, pl := e.lastmodOf(t, pageType, "2", "en"), e.lastmodOf(t, pageType, "2", "pl"); !en.Equal(base) || pl.Before(before) {
|
||||||
|
t.Fatalf("a pl change: en %v, pl %v", en, pl)
|
||||||
|
}
|
||||||
|
|
||||||
|
moved := e.lastmodOf(t, pageType, "1", "en")
|
||||||
|
later := page1(1, "a", base.Add(48*time.Hour))
|
||||||
|
contentStore.put(pageType, later)
|
||||||
|
e.rebuild(t)
|
||||||
|
if got := e.lastmodOf(t, pageType, "1", "en"); !got.Equal(moved) {
|
||||||
|
t.Fatalf("a rebuild moved lastmod from %v to %v", moved, got)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := e.app.Events.Fire(context.Background(), &pact.RecordDeleted{Model: pageModel, ID: "1"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := locs(e.get(t, "/_sitemap/files/sitemap-pages-1.xml").Body.String()); strings.Contains(strings.Join(got, " "), "/pages/a") {
|
||||||
|
t.Fatalf("a deleted record is still listed: %v", got)
|
||||||
|
}
|
||||||
|
// A record of a model no content type declares is ignored.
|
||||||
|
if err := e.app.Events.Fire(context.Background(), &pact.RecordSaved{Model: "other_model", ID: "2", Changes: []pact.RecordChange{{Attribute: "title"}}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDebouncedRebuild pins P33-12: record events within the delay queue
|
||||||
|
// exactly one rebuild job, scheduled after golem15.sitemap.rebuild_delay_seconds;
|
||||||
|
// once the job ran, the next event queues another; a no-op save queues none.
|
||||||
|
func TestDebouncedRebuild(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
contentStore.put(pageType, page1(1, "a", time.Now()))
|
||||||
|
e.saved(t, "1")
|
||||||
|
if n := e.riverJobs(t, classes.RebuildKind); n != 0 {
|
||||||
|
t.Fatalf("a no-op save queued %d rebuilds", n)
|
||||||
|
}
|
||||||
|
start := time.Now()
|
||||||
|
for range 3 {
|
||||||
|
e.saved(t, "1", pact.RecordChange{Attribute: "title"})
|
||||||
|
}
|
||||||
|
if n := e.riverJobs(t, classes.RebuildKind); n != 1 {
|
||||||
|
t.Fatalf("three saves queued %d rebuilds, want 1", n)
|
||||||
|
}
|
||||||
|
var at time.Time
|
||||||
|
if err := e.gdb.Raw(`SELECT scheduled_at FROM river_job WHERE kind = ?`, classes.RebuildKind).Scan(&at).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if d := at.Sub(start); d < 55*time.Second || d > 70*time.Second {
|
||||||
|
t.Fatalf("the rebuild is scheduled %v after the first save, want about 60s", d)
|
||||||
|
}
|
||||||
|
e.rebuild(t)
|
||||||
|
e.saved(t, "1", pact.RecordChange{Attribute: "title"})
|
||||||
|
if n := e.riverJobs(t, classes.RebuildKind); n != 2 {
|
||||||
|
t.Fatalf("a save after the rebuild: %d jobs, want 2", n)
|
||||||
|
}
|
||||||
|
if err := e.app.Events.Fire(context.Background(), &pact.RecordDeleted{Model: pageModel, ID: "1"}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if n := e.riverJobs(t, classes.RebuildKind); n != 2 {
|
||||||
|
t.Fatalf("a delete within the delay queued another rebuild: %d", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestRebuildCommand runs sitemap:rebuild through the console: without
|
||||||
|
// --queue it rebuilds in the process and reports the counts, with --queue
|
||||||
|
// it dispatches the rebuild job.
|
||||||
|
func TestRebuildCommand(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
contentStore.put(pageType, page1(1, "a", time.Now()))
|
||||||
|
run := func(args ...string) (int, string) {
|
||||||
|
var buf strings.Builder
|
||||||
|
root, err := bonfire.NewRootIO("summer", []bonfire.Command{console.Rebuild(e.app)}, strings.NewReader(""), &buf, &buf)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return bonfire.Execute(context.Background(), root, args), buf.String()
|
||||||
|
}
|
||||||
|
if code, out := run("sitemap:rebuild"); code != 0 || !strings.Contains(out, "Rebuilt the sitemaps: 1 addresses in 1 files (1 added, 0 changed, 0 removed).") {
|
||||||
|
t.Fatalf("sitemap:rebuild: %d\n%s", code, out)
|
||||||
|
}
|
||||||
|
if got := locs(e.get(t, "/sitemap.xml").Body.String()); len(got) != 1 {
|
||||||
|
t.Fatalf("index after the command: %v", got)
|
||||||
|
}
|
||||||
|
if code, out := run("sitemap:rebuild", "--queue"); code != 0 || !strings.Contains(out, "Queued the sitemap rebuild") || e.riverJobs(t, classes.RebuildKind) != 1 {
|
||||||
|
t.Fatalf("sitemap:rebuild --queue: %d\n%s", code, out)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestHreflangAlternates pins D-55 to D-57: every address of a record with
|
||||||
|
// more than one translated locale carries xhtml:link alternates for each
|
||||||
|
// locale, itself included, plus x-default on the default locale's address;
|
||||||
|
// a locale without an address gets none, a single-locale record none.
|
||||||
|
func TestHreflangAlternates(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
if err := e.gdb.Exec(`UPDATE golem15_sitemap_settings SET default_locale = 'pl' WHERE id = 1`).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
mod := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
// G3: a Journal-shaped record (P33-64): every enabled locale in sort
|
||||||
|
// order, the untranslated de with URL "" and the default locale's
|
||||||
|
// title, description and word count.
|
||||||
|
words := 120
|
||||||
|
contentStore.put(pageType, fakeRecord{ID: 1, Published: true, LastMod: mod, Locales: []pact.ContentLocale{
|
||||||
|
{Locale: "pl", URL: "/strony/a", Title: "Strona A", Description: "O stronie", Words: &words},
|
||||||
|
{Locale: "en", URL: "/en/pages/a", Title: "Page A", Description: "About the page", Words: &words},
|
||||||
|
{Locale: "de", URL: "", Title: "Strona A", Description: "O stronie", Words: &words},
|
||||||
|
}})
|
||||||
|
contentStore.put(pageType, fakeRecord{ID: 2, Published: true, LastMod: mod, Locales: []pact.ContentLocale{{Locale: "pl", URL: "/strony/b"}}})
|
||||||
|
e.rebuild(t)
|
||||||
|
body := e.get(t, "/_sitemap/files/sitemap-pages-1.xml").Body.String()
|
||||||
|
if !strings.Contains(body, `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">`) {
|
||||||
|
t.Fatalf("the xhtml namespace is not declared:\n%s", body)
|
||||||
|
}
|
||||||
|
alts := `<xhtml:link rel="alternate" hreflang="pl" href="https://api.example.test/strony/a"/>` +
|
||||||
|
`<xhtml:link rel="alternate" hreflang="en" href="https://api.example.test/en/pages/a"/>` +
|
||||||
|
`<xhtml:link rel="alternate" hreflang="x-default" href="https://api.example.test/strony/a"/>`
|
||||||
|
for _, loc := range []string{"https://api.example.test/en/pages/a", "https://api.example.test/strony/a"} {
|
||||||
|
if !strings.Contains(body, "<url><loc>"+loc+"</loc><lastmod>2026-10-01T08:00:00Z</lastmod>"+alts+"</url>") {
|
||||||
|
t.Errorf("%s lacks the alternates:\n%s", loc, body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if strings.Contains(body, `hreflang="de"`) {
|
||||||
|
t.Errorf("a locale without an address got an alternate:\n%s", body)
|
||||||
|
}
|
||||||
|
if !strings.Contains(body, "<url><loc>https://api.example.test/strony/b</loc><lastmod>2026-10-01T08:00:00Z</lastmod></url>") {
|
||||||
|
t.Errorf("a single-locale record got alternates:\n%s", body)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without a default locale setting, x-default is the record's first
|
||||||
|
// locale; a locale that leaves the record drops out of the alternates.
|
||||||
|
if err := e.gdb.Exec(`UPDATE golem15_sitemap_settings SET default_locale = NULL WHERE id = 1`).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
contentStore.put(pageType, fakeRecord{ID: 1, Published: true, LastMod: mod, Locales: []pact.ContentLocale{
|
||||||
|
{Locale: "en", URL: "/en/pages/a"}, {Locale: "pl", URL: "/strony/a"}, {Locale: "de", URL: "/de/seiten/a"},
|
||||||
|
}})
|
||||||
|
e.rebuild(t)
|
||||||
|
body = e.get(t, "/_sitemap/files/sitemap-pages-1.xml").Body.String()
|
||||||
|
if !strings.Contains(body, `hreflang="x-default" href="https://api.example.test/en/pages/a"`) || strings.Count(body, `hreflang="de"`) != 3 {
|
||||||
|
t.Fatalf("x-default without a default locale, or the new locale:\n%s", body)
|
||||||
|
}
|
||||||
|
contentStore.put(pageType, fakeRecord{ID: 1, Published: true, LastMod: mod, Locales: []pact.ContentLocale{{Locale: "en", URL: "/en/pages/a"}}})
|
||||||
|
e.rebuild(t)
|
||||||
|
if body = e.get(t, "/_sitemap/files/sitemap-pages-1.xml").Body.String(); strings.Contains(body, "xhtml:link") {
|
||||||
|
t.Fatalf("a record down to one locale keeps alternates:\n%s", body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestFilterExcludes pins D-95 and D-24 with a published Filter: an
|
||||||
|
// excluded address leaves the files and is counted under its reason, an
|
||||||
|
// address the Filter moves lands in sitemap-offers-1.xml, every batch is
|
||||||
|
// one page of one type (or the additional addresses), and the Filter's
|
||||||
|
// group titles reach Listing.Settings.
|
||||||
|
func TestFilterExcludes(t *testing.T) {
|
||||||
|
theFilter.mu.Lock()
|
||||||
|
theFilter.batches = nil
|
||||||
|
theFilter.mu.Unlock()
|
||||||
|
e := bootIndex(t, filterPluginID)
|
||||||
|
mod := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
contentStore.put(pageType, page1(1, "a", mod))
|
||||||
|
contentStore.put(pageType, page1(2, "noindex-me", mod))
|
||||||
|
contentStore.put(pageType, page1(3, "promo", mod))
|
||||||
|
contentStore.put(offerType, fakeRecord{ID: 1, Published: true, LastMod: mod, Locales: []pact.ContentLocale{{Locale: "en", URL: "/offers/x"}}})
|
||||||
|
if err := e.gdb.Exec(`UPDATE golem15_sitemap_settings SET extra_urls = '[{"url":"/kontakt"},{"url":"/noindex-extra"}]' WHERE id = 1`).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
e.rebuild(t)
|
||||||
|
pages := locs(e.get(t, "/_sitemap/files/sitemap-pages-1.xml").Body.String())
|
||||||
|
if strings.Join(pages, " ") != "https://api.example.test/pages/a https://api.example.test/kontakt" {
|
||||||
|
t.Fatalf("pages file = %v", pages)
|
||||||
|
}
|
||||||
|
offers := locs(e.get(t, "/_sitemap/files/sitemap-offers-1.xml").Body.String())
|
||||||
|
if strings.Join(offers, " ") != "https://api.example.test/pages/promo https://api.example.test/offers/x" {
|
||||||
|
t.Fatalf("offers file = %v", offers)
|
||||||
|
}
|
||||||
|
var n int64
|
||||||
|
e.gdb.Raw(`SELECT COUNT(*) FROM golem15_sitemap_urls WHERE excluded_reason = 'noindex'`).Scan(&n)
|
||||||
|
if n != 2 {
|
||||||
|
t.Fatalf("%d rows left out as noindex, want 2", n)
|
||||||
|
}
|
||||||
|
theFilter.mu.Lock()
|
||||||
|
batches := theFilter.batches
|
||||||
|
theFilter.mu.Unlock()
|
||||||
|
if len(batches) != 3 || len(batches[0]) != 3 || batches[0][0].TypeKey != pageType || batches[0][0].RecordID != "1" || batches[0][0].Locale != "en" ||
|
||||||
|
batches[1][0].TypeKey != offerType || batches[2][0].TypeKey != "extra" || batches[2][0].URL != "/kontakt" {
|
||||||
|
t.Fatalf("batches = %+v", batches)
|
||||||
|
}
|
||||||
|
|
||||||
|
listing, ok := e.app.Lookup[contract.Listing]()
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("the sitemap publishes no contract.Listing")
|
||||||
|
}
|
||||||
|
settings, err := listing.Settings(context.Background())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if settings.SiteURL != "https://api.example.test" || settings.IndexURL != "https://api.example.test/sitemap.xml" || len(settings.Groups) != 2 {
|
||||||
|
t.Fatalf("listing settings = %+v", settings)
|
||||||
|
}
|
||||||
|
offersGroup := settings.Groups[0]
|
||||||
|
if offersGroup.Key != "offers" || offersGroup.Slug != "offers" || offersGroup.Count != 2 || offersGroup.Titles["pl"] != "Oferty" || settings.Groups[1].Key != "pages" || settings.Groups[1].Count != 2 {
|
||||||
|
t.Fatalf("listing groups = %+v", settings.Groups)
|
||||||
|
}
|
||||||
|
s1 := e.call(t, http.MethodGet, "/golem15/sitemap/settings/partials/sitemap_files", e.admin(t, permSitemap), nil).Body.String()
|
||||||
|
if !strings.Contains(s1, `{"text":"noindex"}`) || !strings.Contains(s1, `{"text":"2"}`) {
|
||||||
|
t.Fatalf("S1 lacks the noindex count:\n%s", s1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestNoFilter pins D-95 without a Filter: everything published is listed.
|
||||||
|
func TestNoFilter(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
if _, ok := e.app.Lookup[contract.Filter](); ok {
|
||||||
|
t.Fatal("a Filter is published without the filter plugin")
|
||||||
|
}
|
||||||
|
mod := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
contentStore.put(pageType, page1(1, "noindex-me", mod))
|
||||||
|
contentStore.put(pageType, page1(2, "promo", mod))
|
||||||
|
e.rebuild(t)
|
||||||
|
if got := locs(e.get(t, "/_sitemap/files/sitemap-pages-1.xml").Body.String()); len(got) != 2 {
|
||||||
|
t.Fatalf("without a Filter: %v", got)
|
||||||
|
}
|
||||||
|
if rec := e.get(t, "/_sitemap/files/sitemap-offers-1.xml"); rec.Code != http.StatusNotFound {
|
||||||
|
t.Fatalf("an offers file without a Filter: %d", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestExtraDuplicates pins the de-duplication of the additional addresses
|
||||||
|
// against the content records: an additional address a listed record has
|
||||||
|
// (as a path or as the same absolute URL) is in the files once, counted as
|
||||||
|
// left out with the reason duplicate, and listed again once the record is
|
||||||
|
// gone.
|
||||||
|
func TestExtraDuplicates(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
mod := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
contentStore.put(pageType, page1(1, "a", mod))
|
||||||
|
contentStore.put(pageType, page1(2, "b", mod))
|
||||||
|
if err := e.gdb.Exec(`UPDATE golem15_sitemap_settings SET extra_urls = '[{"url":"/pages/a"},{"url":"https://api.example.test/pages/b"},{"url":"/kontakt"}]' WHERE id = 1`).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
e.rebuild(t)
|
||||||
|
pages := locs(e.get(t, "/_sitemap/files/sitemap-pages-1.xml").Body.String())
|
||||||
|
if strings.Join(pages, " ") != "https://api.example.test/pages/a https://api.example.test/pages/b https://api.example.test/kontakt" {
|
||||||
|
t.Fatalf("pages file = %v, want each address once", pages)
|
||||||
|
}
|
||||||
|
var n int64
|
||||||
|
e.gdb.Raw(`SELECT COUNT(*) FROM golem15_sitemap_urls WHERE type_key = 'extra' AND excluded_reason = ?`, models.ReasonDuplicate).Scan(&n)
|
||||||
|
if n != 2 {
|
||||||
|
t.Fatalf("%d additional addresses left out as duplicate, want 2", n)
|
||||||
|
}
|
||||||
|
s1 := e.call(t, http.MethodGet, "/golem15/sitemap/settings/partials/sitemap_files", e.admin(t, permSitemap), nil).Body.String()
|
||||||
|
if !strings.Contains(s1, "Already listed by a content type") {
|
||||||
|
t.Fatalf("S1 lacks the duplicate reason:\n%s", s1)
|
||||||
|
}
|
||||||
|
|
||||||
|
contentStore.remove(pageType, 2)
|
||||||
|
e.rebuild(t)
|
||||||
|
pages = locs(e.get(t, "/_sitemap/files/sitemap-pages-1.xml").Body.String())
|
||||||
|
// The additional address's row has been in the table since the first
|
||||||
|
// rebuild, so it keeps its place.
|
||||||
|
if strings.Join(pages, " ") != "https://api.example.test/pages/a https://api.example.test/pages/b https://api.example.test/kontakt" {
|
||||||
|
t.Fatalf("pages file after the record is gone = %v, want the additional address listed again", pages)
|
||||||
|
}
|
||||||
|
e.gdb.Raw(`SELECT COUNT(*) FROM golem15_sitemap_urls WHERE type_key = 'extra' AND excluded_reason = ?`, models.ReasonDuplicate).Scan(&n)
|
||||||
|
if n != 1 {
|
||||||
|
t.Fatalf("%d additional addresses left out as duplicate after the record is gone, want 1", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestListing pins contract.Listing.Entries: a group's listed addresses in
|
||||||
|
// pages of Limit with Next and Total, absolute URLs with title and
|
||||||
|
// lastmod, the locale filter keeping addresses without a locale, and an
|
||||||
|
// unknown group empty.
|
||||||
|
func TestListing(t *testing.T) {
|
||||||
|
e := bootIndex(t)
|
||||||
|
mod := time.Date(2026, 10, 1, 8, 0, 0, 0, time.UTC)
|
||||||
|
for i := 1; i <= 5; i++ {
|
||||||
|
contentStore.put(pageType, page1(i, string(rune('a'+i-1)), mod))
|
||||||
|
}
|
||||||
|
contentStore.put(pageType, fakeRecord{ID: 6, Published: true, LastMod: mod, Locales: []pact.ContentLocale{{Locale: "pl", URL: "/strony/f", Title: "F"}}})
|
||||||
|
if err := e.gdb.Exec(`UPDATE golem15_sitemap_settings SET extra_urls = '[{"url":"/kontakt"}]' WHERE id = 1`).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
e.rebuild(t)
|
||||||
|
listing, ok := e.app.Lookup[contract.Listing]()
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("no contract.Listing")
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
var all []string
|
||||||
|
after := ""
|
||||||
|
for range 10 {
|
||||||
|
page, err := listing.Entries(ctx, contract.EntriesQuery{Group: "pages", After: after, Limit: 3})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if page.Total != 7 {
|
||||||
|
t.Fatalf("Total = %d", page.Total)
|
||||||
|
}
|
||||||
|
for _, en := range page.Entries {
|
||||||
|
all = append(all, en.URL)
|
||||||
|
}
|
||||||
|
if page.Next == "" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
after = page.Next
|
||||||
|
}
|
||||||
|
if len(all) != 7 || all[0] != "https://api.example.test/pages/a" || all[6] != "https://api.example.test/kontakt" {
|
||||||
|
t.Fatalf("paged entries = %v", all)
|
||||||
|
}
|
||||||
|
first, err := listing.Entries(ctx, contract.EntriesQuery{Group: "pages", Limit: 1})
|
||||||
|
if err != nil || len(first.Entries) != 1 || first.Entries[0].Title != "Page a" || first.Entries[0].TypeKey != pageType || first.Entries[0].RecordID != "1" ||
|
||||||
|
first.Entries[0].LastMod == nil || !first.Entries[0].LastMod.Equal(mod) || first.Next == "" {
|
||||||
|
t.Fatalf("first entry = %+v %v", first, err)
|
||||||
|
}
|
||||||
|
pl, err := listing.Entries(ctx, contract.EntriesQuery{Group: "pages", Locale: "pl"})
|
||||||
|
if err != nil || pl.Total != 2 || pl.Entries[0].URL != "https://api.example.test/strony/f" || pl.Entries[1].URL != "https://api.example.test/kontakt" {
|
||||||
|
t.Fatalf("pl entries = %+v %v", pl, err)
|
||||||
|
}
|
||||||
|
none, err := listing.Entries(ctx, contract.EntriesQuery{Group: "nope"})
|
||||||
|
if err != nil || none.Total != 0 || len(none.Entries) != 0 || none.Next != "" {
|
||||||
|
t.Fatalf("unknown group = %+v %v", none, err)
|
||||||
|
}
|
||||||
|
// contract.Rebuilder (P33-59) queues the debounced rebuild a record
|
||||||
|
// event queues, once per debounce window.
|
||||||
|
rb, ok := e.app.Lookup[contract.Rebuilder]()
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("no contract.Rebuilder")
|
||||||
|
}
|
||||||
|
for range 2 {
|
||||||
|
if err := rb.RequestRebuild(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var pending *time.Time
|
||||||
|
if err := e.gdb.Raw(`SELECT rebuild_pending_until FROM golem15_sitemap_settings WHERE id = 1`).Scan(&pending).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if pending == nil {
|
||||||
|
t.Fatal("RequestRebuild set no rebuild_pending_until")
|
||||||
|
}
|
||||||
|
if n := e.riverJobs(t, classes.RebuildKind); n != 1 {
|
||||||
|
t.Fatalf("two requests queued %d rebuilds, want 1", n)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@ package sitemap_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -15,101 +14,35 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
sitemap "git.golem15.com/golem15/sm-sitemap-plugin"
|
_ "git.golem15.com/golem15/sm-sitemap-plugin"
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/classes"
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/console"
|
|
||||||
"git.golem15.com/golem15/sm-sitemap-plugin/models"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
"git.golem15.com/golem15/summercms/modules/bonfire"
|
"git.golem15.com/golem15/summercms/modules/bonfire"
|
||||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||||
"git.golem15.com/golem15/summercms/modules/compass"
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
"git.golem15.com/golem15/summercms/modules/pact"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/party"
|
"git.golem15.com/golem15/summercms/modules/party"
|
||||||
"git.golem15.com/golem15/summercms/modules/signpost"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/surf"
|
"git.golem15.com/golem15/summercms/modules/surf"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
// testTypesPluginID is the fake content plugin that registers menu item
|
// sitemapEnv is a booted application with the sitemap and the fake
|
||||||
// types for the sitemap smoke tests. The real Journal and sitemap
|
// content plugin.
|
||||||
// combination is proven by the host application's tests.
|
|
||||||
const testTypesPluginID = "acme.sitemaptypes"
|
|
||||||
|
|
||||||
// acmeTypes is a content plugin with one menu item type, acme-post, whose
|
|
||||||
// reference "7" resolves to a fixed post with two alternates.
|
|
||||||
type acmeTypes struct{}
|
|
||||||
|
|
||||||
func (acmeTypes) ID() string { return testTypesPluginID }
|
|
||||||
func (acmeTypes) Requires() []string { return nil }
|
|
||||||
func (acmeTypes) Register(*backpack.App) error { return nil }
|
|
||||||
func (acmeTypes) Boot(*backpack.App) error { return nil }
|
|
||||||
func (acmeTypes) MenuItemTypes() []pact.MenuItemType {
|
|
||||||
mtime := time.Date(2026, 3, 4, 10, 0, 0, 0, time.UTC)
|
|
||||||
return []pact.MenuItemType{acmeList(), {
|
|
||||||
Key: "acme-post",
|
|
||||||
Label: "Acme post",
|
|
||||||
DefaultPattern: "/news/:slug",
|
|
||||||
References: func(context.Context) ([]pact.MenuItemReference, error) {
|
|
||||||
return []pact.MenuItemReference{{Value: "7", Label: "Hello"}}, nil
|
|
||||||
},
|
|
||||||
Resolve: func(_ context.Context, in pact.MenuItemResolve) (*pact.ResolvedMenuItem, error) {
|
|
||||||
if in.Reference != "7" {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
return &pact.ResolvedMenuItem{
|
|
||||||
Title: "Hello",
|
|
||||||
URL: "/news/hello",
|
|
||||||
MTime: &mtime,
|
|
||||||
Alternates: []pact.MenuItemAlternate{
|
|
||||||
{Locale: "pl", URL: "/news/hello"},
|
|
||||||
{Locale: "en", URL: "/en/news/hello"},
|
|
||||||
},
|
|
||||||
}, nil
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
}
|
|
||||||
|
|
||||||
// acmeList is a list type of the fake plugin: no URL of its own, one post
|
|
||||||
// with two alternates as its item.
|
|
||||||
func acmeList() pact.MenuItemType {
|
|
||||||
return pact.MenuItemType{
|
|
||||||
Key: "acme-list",
|
|
||||||
Label: "Acme posts",
|
|
||||||
DefaultPattern: "/news/:slug",
|
|
||||||
PatternFrom: "acme-post",
|
|
||||||
DynamicItems: true,
|
|
||||||
Resolve: func(context.Context, pact.MenuItemResolve) (*pact.ResolvedMenuItem, error) {
|
|
||||||
return &pact.ResolvedMenuItem{Items: []pact.ResolvedMenuItem{{
|
|
||||||
Title: "A",
|
|
||||||
URL: "/news/a",
|
|
||||||
Alternates: []pact.MenuItemAlternate{
|
|
||||||
{Locale: "pl", URL: "/news/a"},
|
|
||||||
{Locale: "en", URL: "/en/news/a"},
|
|
||||||
},
|
|
||||||
}}}, nil
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ pact.HasMenuItemTypes = acmeTypes{}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
party.Register(acmeTypes{})
|
|
||||||
}
|
|
||||||
|
|
||||||
// sitemapEnv is a booted application with the sitemap and the fake types.
|
|
||||||
type sitemapEnv struct {
|
type sitemapEnv struct {
|
||||||
h http.Handler
|
h http.Handler
|
||||||
app *backpack.App
|
app *backpack.App
|
||||||
gdb *gorm.DB
|
gdb *gorm.DB
|
||||||
|
plugins []party.Plugin
|
||||||
}
|
}
|
||||||
|
|
||||||
// bootSitemap boots the application. The sitemap cache is off
|
// envOverride is the override key that sets the app environment
|
||||||
// (golem15.sitemap.cache_seconds 0): the smoke tests change listeners and
|
// (SUMMER_ENV) instead of a config key; development by default.
|
||||||
// registry content between requests. overrides set further config keys.
|
const envOverride = "__env"
|
||||||
func bootSitemap(t *testing.T, overrides ...map[string]any) *sitemapEnv {
|
|
||||||
|
// bootPlugins boots the application with the plugins ids on a fresh
|
||||||
|
// database; overrides set further config keys (envOverride the
|
||||||
|
// environment).
|
||||||
|
func bootPlugins(t *testing.T, ids []string, overrides ...map[string]any) *sitemapEnv {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
sqlDB := freshDB(t)
|
sqlDB := freshDB(t)
|
||||||
gdb, err := lagoon.Use(t.Context(), sqlDB)
|
gdb, err := lagoon.Use(t.Context(), sqlDB)
|
||||||
@@ -120,9 +53,15 @@ func bootSitemap(t *testing.T, overrides ...map[string]any) *sitemapEnv {
|
|||||||
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: sitemap-smoke\nlocale: en\nfallback_locale: en\nurl: https://api.example.test\n"), 0o644); err != nil {
|
if err := os.WriteFile(filepath.Join(dir, "app.yaml"), []byte("name: sitemap-smoke\nlocale: en\nfallback_locale: en\nurl: https://api.example.test\n"), 0o644); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
env := "development"
|
||||||
|
for _, o := range overrides {
|
||||||
|
if v, ok := o[envOverride].(string); ok {
|
||||||
|
env = v
|
||||||
|
}
|
||||||
|
}
|
||||||
cfg, err := compass.Open(compass.Options{
|
cfg, err := compass.Open(compass.Options{
|
||||||
Dir: dir,
|
Dir: dir,
|
||||||
Environ: []string{"SUMMER_ENV=development", "SUMMER_ADMIN__JWT__SECRET=sitemap-smoke-test-only-hs256-secret-key"},
|
Environ: []string{"SUMMER_ENV=" + env, "SUMMER_ADMIN__JWT__SECRET=sitemap-smoke-test-only-hs256-secret-key"},
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -132,11 +71,12 @@ func bootSitemap(t *testing.T, overrides ...map[string]any) *sitemapEnv {
|
|||||||
"http.body_limits.upload_bytes": 8388608,
|
"http.body_limits.upload_bytes": 8388608,
|
||||||
"mail.driver": "log",
|
"mail.driver": "log",
|
||||||
"mail.from": "noreply@example.test",
|
"mail.from": "noreply@example.test",
|
||||||
sitemap.CacheConfigKey: 0,
|
|
||||||
}
|
}
|
||||||
for _, o := range overrides {
|
for _, o := range overrides {
|
||||||
for key, value := range o {
|
for key, value := range o {
|
||||||
settings[key] = value
|
if key != envOverride {
|
||||||
|
settings[key] = value
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for key, value := range settings {
|
for key, value := range settings {
|
||||||
@@ -148,7 +88,7 @@ func bootSitemap(t *testing.T, overrides ...map[string]any) *sitemapEnv {
|
|||||||
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
|
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
plugins, err := party.Activate(app, []string{testTypesPluginID, "golem15.sitemap"})
|
plugins, err := party.Activate(app, ids)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -159,7 +99,7 @@ func bootSitemap(t *testing.T, overrides ...map[string]any) *sitemapEnv {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
return &sitemapEnv{h: h, app: app, gdb: gdb}
|
return &sitemapEnv{h: h, app: app, gdb: gdb, plugins: plugins}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *sitemapEnv) get(t *testing.T, path string) *httptest.ResponseRecorder {
|
func (e *sitemapEnv) get(t *testing.T, path string) *httptest.ResponseRecorder {
|
||||||
@@ -171,113 +111,6 @@ func (e *sitemapEnv) get(t *testing.T, path string) *httptest.ResponseRecorder {
|
|||||||
return rec
|
return rec
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *sitemapEnv) storeDefinition(t *testing.T, items []models.DefinitionItem) models.Definition {
|
|
||||||
t.Helper()
|
|
||||||
theme := models.DefinitionTheme
|
|
||||||
def := models.Definition{Theme: &theme}
|
|
||||||
def.SetItems(items)
|
|
||||||
if err := e.gdb.Create(&def).Error; err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return def
|
|
||||||
}
|
|
||||||
|
|
||||||
func text(s string) *string { return &s }
|
|
||||||
|
|
||||||
// TestSitemapCacheAndThrottle pins WR-05: with the cache on, a repeated GET
|
|
||||||
// is served from memory (a listener added later does not run), a save of
|
|
||||||
// the definition is served at once, and the 61st request of a client within
|
|
||||||
// a minute is a 429.
|
|
||||||
func TestSitemapCacheAndThrottle(t *testing.T) {
|
|
||||||
e := bootSitemap(t, map[string]any{sitemap.CacheConfigKey: 60})
|
|
||||||
def := e.storeDefinition(t, []models.DefinitionItem{
|
|
||||||
{Type: models.ItemTypeURL, URL: text("/"), Changefreq: text("always"), Priority: text("1.0")},
|
|
||||||
{Type: "acme-post", Reference: text("7"), URLPattern: text(""), Nesting: true, Changefreq: text("weekly"), Priority: text("0.5")},
|
|
||||||
})
|
|
||||||
requests := 0
|
|
||||||
get := func() *httptest.ResponseRecorder {
|
|
||||||
requests++
|
|
||||||
return e.get(t, "/sitemap.xml")
|
|
||||||
}
|
|
||||||
first := get()
|
|
||||||
if first.Code != http.StatusOK || !strings.Contains(first.Body.String(), "<loc>https://api.example.test/</loc>") {
|
|
||||||
t.Fatalf("first GET: %d %s", first.Code, first.Body.String())
|
|
||||||
}
|
|
||||||
e.app.Events.Listen("acme.skipall", func(_ context.Context, ev *classes.BeforeAddItem) error {
|
|
||||||
ev.Skip = true
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if again := get(); again.Code != http.StatusOK || again.Body.String() != first.Body.String() {
|
|
||||||
t.Fatalf("a repeated GET was generated again:\n%s", again.Body.String())
|
|
||||||
}
|
|
||||||
def.SetItems(append(def.Items(), models.DefinitionItem{Type: models.ItemTypeURL, URL: text("/x")}))
|
|
||||||
if err := e.gdb.Save(&def).Error; err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if saved := get(); saved.Code != http.StatusOK || strings.Contains(saved.Body.String(), "<url>") {
|
|
||||||
t.Fatalf("a saved definition was served from the cache:\n%s", saved.Body.String())
|
|
||||||
}
|
|
||||||
for requests < 60 {
|
|
||||||
if rec := get(); rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("request %d: %d", requests, rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if rec := get(); rec.Code != http.StatusTooManyRequests {
|
|
||||||
t.Fatalf("request %d: %d, want 429", requests, rec.Code)
|
|
||||||
}
|
|
||||||
if rec := e.get(t, "/sitemap.xsl"); rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("/sitemap.xsl is throttled with the sitemap: %d", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestSitemapTracer stores a definition with a url item and a registry
|
|
||||||
// item, GETs /sitemap.xml and compares the body with the PHP golden.
|
|
||||||
func TestSitemapTracer(t *testing.T) {
|
|
||||||
e := bootSitemap(t)
|
|
||||||
|
|
||||||
if rec := e.get(t, "/sitemap.xml"); rec.Code != http.StatusNotFound {
|
|
||||||
t.Fatalf("no definition: %d, want 404", rec.Code)
|
|
||||||
}
|
|
||||||
|
|
||||||
def := e.storeDefinition(t, nil)
|
|
||||||
rec := e.get(t, "/sitemap.xml")
|
|
||||||
if rec.Code != http.StatusOK || rec.Body.Len() != 0 || rec.Header().Get("Content-Type") != "application/xml" {
|
|
||||||
t.Fatalf("empty definition: %d %q %q", rec.Code, rec.Header().Get("Content-Type"), rec.Body.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
def.SetItems([]models.DefinitionItem{
|
|
||||||
{Type: models.ItemTypeURL, URL: text("/"), Changefreq: text("always"), Priority: text("1.0")},
|
|
||||||
{Type: "acme-post", Reference: text("7"), URLPattern: text(""), Nesting: true, Changefreq: text("weekly"), Priority: text("0.5")},
|
|
||||||
})
|
|
||||||
if err := e.gdb.Save(&def).Error; err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
rec = e.get(t, "/sitemap.xml")
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("GET /sitemap.xml: %d %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
if ct := rec.Header().Get("Content-Type"); ct != "application/xml" {
|
|
||||||
t.Fatalf("Content-Type = %q", ct)
|
|
||||||
}
|
|
||||||
want, err := os.ReadFile(filepath.Join("classes", "testdata", "tracer.golden"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if got := rec.Body.String(); got != string(want) {
|
|
||||||
t.Fatalf("/sitemap.xml differs from the PHP golden\n got: %q\nwant: %q", got, want)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The stored data keeps the PHP item keys.
|
|
||||||
var raw string
|
|
||||||
if err := e.gdb.Raw(`SELECT data FROM golem15_sitemap_definitions WHERE id = ?`, def.ID).Scan(&raw).Error; err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
const wantData = `[{"changefreq":"always","priority":"1.0","nesting":false,"type":"url","url":"/","reference":null,"cmsPage":null,"urlPattern":null},{"changefreq":"weekly","priority":"0.5","nesting":true,"type":"acme-post","url":null,"reference":"7","cmsPage":null,"urlPattern":""}]`
|
|
||||||
if raw != wantData {
|
|
||||||
t.Fatalf("stored data = %s", raw)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeFile(t *testing.T, dir, name, body string) string {
|
func writeFile(t *testing.T, dir, name, body string) string {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
path := filepath.Join(dir, name)
|
path := filepath.Join(dir, name)
|
||||||
@@ -292,163 +125,6 @@ func testOutput() (bonfire.Output, *bytes.Buffer) {
|
|||||||
return bonfire.NewOutput(strings.NewReader(""), &buf, &buf), &buf
|
return bonfire.NewOutput(strings.NewReader(""), &buf, &buf), &buf
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSitemapImportSmoke copies a Winter export through sitemap:import-winter,
|
|
||||||
// then checks the frontend_url rewrite, the stylesheet route, a
|
|
||||||
// BeforeAddItem listener and sitemap:import.
|
|
||||||
func TestSitemapImportSmoke(t *testing.T) {
|
|
||||||
e := bootSitemap(t)
|
|
||||||
ctx := context.Background()
|
|
||||||
reg, ok := e.app.Lookup[*signpost.Registry]()
|
|
||||||
if !ok {
|
|
||||||
t.Fatal("signpost registry is not published")
|
|
||||||
}
|
|
||||||
dir := t.TempDir()
|
|
||||||
data := `[{"changefreq":"always","priority":"1.0","nesting":"0","type":"url","url":"/","code":null,"reference":null,"cmsPage":null,"urlPattern":null,"exists":false,"fillable":["changefreq"]},` +
|
|
||||||
`{"changefreq":"monthly","priority":"0.5","nesting":"0","type":"static-page","url":null,"reference":"about","cmsPage":null,"urlPattern":null},` +
|
|
||||||
`{"changefreq":"weekly","priority":"0.4","nesting":"1","type":"blog-posts","url":null,"reference":null,"cmsPage":"blog/post","urlPattern":"/news/:slug"},` +
|
|
||||||
`{"changefreq":"weekly","priority":"0.4","nesting":"0","type":"acme-post","url":null,"reference":"99","cmsPage":null,"urlPattern":null},` +
|
|
||||||
`{"changefreq":"daily","priority":"0.7","nesting":"false","type":"cms-page","url":"","reference":"news","cmsPage":"","urlPattern":""}]`
|
|
||||||
quotedRaw, _ := json.Marshal(data)
|
|
||||||
quoted := string(quotedRaw)
|
|
||||||
defs := writeFile(t, dir, "definitions.jsonl", `{"id": 3, "theme": "site-theme", "data": `+quoted+`, "created_at": "2026-01-01 10:00:00", "updated_at": "2026-01-02 10:00:00"}`+"\n")
|
|
||||||
settings := writeFile(t, dir, "settings.json", `{"frontend_url":"https://www.example.test/","frontend_default_locale":"pl","enable_priority_tiers":"0","priority_homepage":"0.9","legacy_key":"x"}`)
|
|
||||||
|
|
||||||
out, buf := testOutput()
|
|
||||||
report, err := console.ImportWinterFiles(ctx, e.gdb, reg, console.WinterOptions{
|
|
||||||
DefinitionsFile: defs, SettingsFile: settings, Maps: map[string]string{"blog-posts": "acme-list"},
|
|
||||||
PageURLs: map[string]string{"news": "/news"},
|
|
||||||
}, out)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("import-winter: %v\n%s", err, buf.String())
|
|
||||||
}
|
|
||||||
if report.Kept != 3 || report.Dropped != 2 || report.Remapped != 2 || !report.Settings {
|
|
||||||
t.Fatalf("report = %+v\n%s", report, buf.String())
|
|
||||||
}
|
|
||||||
for _, want := range []string{
|
|
||||||
"item 1 (type 'static-page', reference 'about'): dropped (static and CMS page types are not supported)",
|
|
||||||
"item 2 (type 'blog-posts'): type 'blog-posts' mapped to 'acme-list'",
|
|
||||||
"item 2 (type 'blog-posts'): cmsPage 'blog/post' dropped",
|
|
||||||
"item 3 (type 'acme-post', reference '99'): dropped (reference '99' is not among the current references of 'acme-post')",
|
|
||||||
"item 4 (type 'cms-page', reference 'news'): copied as type 'url' with url '/news'",
|
|
||||||
"setting 'legacy_key' ignored",
|
|
||||||
"theme 'site-theme'",
|
|
||||||
} {
|
|
||||||
if !strings.Contains(buf.String(), want) {
|
|
||||||
t.Errorf("report lacks %q:\n%s", want, buf.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var def models.Definition
|
|
||||||
if err := e.gdb.Where("theme = ?", models.DefinitionTheme).First(&def).Error; err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if items := def.Items(); len(items) != 3 || items[0].Type != "url" || items[1].Type != "acme-list" || models.Text(items[1].URLPattern) != "/news/:slug" ||
|
|
||||||
items[2].Type != "url" || models.Text(items[2].URL) != "/news" || items[2].Reference != nil {
|
|
||||||
t.Fatalf("copied items = %+v", items)
|
|
||||||
}
|
|
||||||
var st models.Settings
|
|
||||||
if err := e.gdb.First(&st, 1).Error; err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if models.Text(st.FrontendURL) != "https://www.example.test/" || st.EnablePriorityTiers || st.Priority(models.PriorityHomepage) != "0.9" || st.Priority(models.PriorityBlog) != "0.6" {
|
|
||||||
t.Fatalf("copied settings = %+v", st)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A second copy without --force is refused.
|
|
||||||
out, buf = testOutput()
|
|
||||||
if _, err := console.ImportWinterFiles(ctx, e.gdb, reg, console.WinterOptions{DefinitionsFile: defs}, out); err == nil || !strings.Contains(err.Error(), "--force") {
|
|
||||||
t.Fatalf("second import: %v\n%s", err, buf.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// The frontend URL replaces the backend URL in loc, hreflang and the
|
|
||||||
// stylesheet href; the list type expands per alternate.
|
|
||||||
rec := e.get(t, "/sitemap.xml")
|
|
||||||
body := rec.Body.String()
|
|
||||||
if rec.Code != http.StatusOK || rec.Header().Get("Cache-Control") != "no-cache, private" {
|
|
||||||
t.Fatalf("GET /sitemap.xml: %d %v", rec.Code, rec.Header())
|
|
||||||
}
|
|
||||||
for _, want := range []string{
|
|
||||||
`href="https://www.example.test/sitemap.xsl"`,
|
|
||||||
`<loc>https://www.example.test/</loc>`,
|
|
||||||
`<loc>https://www.example.test/news</loc>`,
|
|
||||||
`<loc>https://www.example.test/news/a</loc>`,
|
|
||||||
`<loc>https://www.example.test/en/news/a</loc>`,
|
|
||||||
`hreflang="en" href="https://www.example.test/en/news/a"/>`,
|
|
||||||
} {
|
|
||||||
if !strings.Contains(body, want) {
|
|
||||||
t.Errorf("sitemap lacks %s:\n%s", want, body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if strings.Contains(body, "api.example.test") {
|
|
||||||
t.Errorf("the backend URL is left in the sitemap:\n%s", body)
|
|
||||||
}
|
|
||||||
|
|
||||||
// /sitemap.xsl answers the PHP file.
|
|
||||||
rec = e.get(t, "/sitemap.xsl")
|
|
||||||
want, err := os.ReadFile(filepath.Join("assets", "sitemap.xsl"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != "text/xsl; charset=UTF-8" || !bytes.Equal(rec.Body.Bytes(), want) {
|
|
||||||
t.Fatalf("GET /sitemap.xsl: %d %q (%d bytes)", rec.Code, rec.Header().Get("Content-Type"), rec.Body.Len())
|
|
||||||
}
|
|
||||||
|
|
||||||
// A BeforeAddItem listener that sets Skip drops its URL.
|
|
||||||
e.app.Events.Listen("acme.skip", func(_ context.Context, ev *classes.BeforeAddItem) error {
|
|
||||||
if ev.Info.URL == "/en/news/a" {
|
|
||||||
ev.Skip = true
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
body = e.get(t, "/sitemap.xml").Body.String()
|
|
||||||
if strings.Contains(body, "<loc>https://www.example.test/en/news/a</loc>") || !strings.Contains(body, "<loc>https://www.example.test/news/a</loc>") {
|
|
||||||
t.Fatalf("the skipped URL is still written:\n%s", body)
|
|
||||||
}
|
|
||||||
|
|
||||||
// sitemap:import replaces the url items and keeps the dynamic ones first.
|
|
||||||
manifest := writeFile(t, dir, "urls.json", `[{"url":"/x","changefreq":"daily"},{"url":"/y","priority":"0.9"}]`)
|
|
||||||
out, buf = testOutput()
|
|
||||||
if err := console.ImportFile(ctx, e.gdb, manifest, "", false, out); err != nil {
|
|
||||||
t.Fatalf("sitemap:import: %v", err)
|
|
||||||
}
|
|
||||||
if err := e.gdb.Where("theme = ?", models.DefinitionTheme).First(&def).Error; err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
items := def.Items()
|
|
||||||
if len(items) != 3 || items[0].Type != "acme-list" || models.Text(items[1].URL) != "/x" || models.Text(items[1].Priority) != "0.5" || models.Text(items[2].Changefreq) != "monthly" {
|
|
||||||
t.Fatalf("imported items = %+v", items)
|
|
||||||
}
|
|
||||||
if !strings.Contains(buf.String(), "Imported 2 URLs into sitemap definition for theme 'default'.") || !strings.Contains(buf.String(), "Kept 1 existing non-URL (dynamic) items.") {
|
|
||||||
t.Fatalf("sitemap:import output:\n%s", buf.String())
|
|
||||||
}
|
|
||||||
bad := writeFile(t, dir, "bad.json", `[{"url":"/x"},{"changefreq":"daily"}]`)
|
|
||||||
if err := console.ImportFile(ctx, e.gdb, bad, "", true, out); err == nil || err.Error() != "Entry 1 is missing a 'url' field" {
|
|
||||||
t.Fatalf("missing url: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// T-17-15: a frontend URL written straight into the row (one stored
|
|
||||||
// before the save check existed) is not applied; the sitemap keeps the
|
|
||||||
// backend URL and none of the value reaches it.
|
|
||||||
for _, value := range []string{"javascript:alert(document.domain)//", `https://x"/><y a="`} {
|
|
||||||
if err := e.gdb.Model(&models.Settings{}).Where("id = ?", 1).Update("frontend_url", value).Error; err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
rec := e.get(t, "/sitemap.xml")
|
|
||||||
body := rec.Body.String()
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("GET /sitemap.xml with frontend_url %q: %d %s", value, rec.Code, body)
|
|
||||||
}
|
|
||||||
if lower := strings.ToLower(body); strings.Contains(lower, "javascript") || strings.Contains(lower, "<y a=") {
|
|
||||||
t.Errorf("frontend_url %q reached the sitemap:\n%s", value, body)
|
|
||||||
}
|
|
||||||
if !strings.Contains(body, `href="https://api.example.test/sitemap.xsl"`) || !strings.Contains(body, "<loc>https://api.example.test/x</loc>") {
|
|
||||||
t.Errorf("frontend_url %q: the sitemap is not on the backend URL:\n%s", value, body)
|
|
||||||
}
|
|
||||||
if strings.Contains(body, "www.example.test") {
|
|
||||||
t.Errorf("frontend_url %q: the earlier frontend URL is left in the sitemap:\n%s", value, body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var adminSeq atomic.Uint64
|
var adminSeq atomic.Uint64
|
||||||
|
|
||||||
// call sends an admin API request with an optional bearer token and JSON
|
// call sends an admin API request with an optional bearer token and JSON
|
||||||
@@ -512,153 +188,3 @@ func (e *sitemapEnv) admin(t *testing.T, permissions ...string) string {
|
|||||||
}
|
}
|
||||||
return body.Data.AccessToken
|
return body.Data.AccessToken
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestSitemapAdminSmoke drives the definition singleton, the item repeater
|
|
||||||
// with its dependent reference, the settings form and the permission.
|
|
||||||
func TestSitemapAdminSmoke(t *testing.T) {
|
|
||||||
e := bootSitemap(t)
|
|
||||||
const perm = "golem15.sitemap.access_definitions"
|
|
||||||
token := e.admin(t, perm)
|
|
||||||
const base = "/golem15/sitemap/definitions"
|
|
||||||
|
|
||||||
// The singleton route creates the definition once.
|
|
||||||
var ids []float64
|
|
||||||
for range 2 {
|
|
||||||
rec := e.call(t, http.MethodGet, base+"/singleton", token, nil)
|
|
||||||
var body struct {
|
|
||||||
Data struct {
|
|
||||||
ID float64 `json:"id"`
|
|
||||||
} `json:"data"`
|
|
||||||
}
|
|
||||||
if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &body) != nil || body.Data.ID == 0 {
|
|
||||||
t.Fatalf("GET singleton: %d %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
ids = append(ids, body.Data.ID)
|
|
||||||
}
|
|
||||||
var n int64
|
|
||||||
e.gdb.Model(&models.Definition{}).Count(&n)
|
|
||||||
if ids[0] != ids[1] || n != 1 {
|
|
||||||
t.Fatalf("singleton ids %v, %d rows", ids, n)
|
|
||||||
}
|
|
||||||
id := fmt.Sprintf("%d", int(ids[0]))
|
|
||||||
|
|
||||||
// The form schema compiles: a singleton with the type options and the
|
|
||||||
// dependent reference.
|
|
||||||
rec := e.call(t, http.MethodGet, base+"/schema/form", token, nil)
|
|
||||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"singleton":true`) || !strings.Contains(rec.Body.String(), `"acme-post"`) || !strings.Contains(rec.Body.String(), `"dependsOn":"type"`) {
|
|
||||||
t.Fatalf("form schema: %d %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
rec = e.call(t, http.MethodGet, base+"/fields/data.reference/dependent-options?values%5Btype%5D=acme-post", token, nil)
|
|
||||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"value":"7"`) {
|
|
||||||
t.Fatalf("dependent options: %d %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Saving rows stores PHP-keyed item JSON.
|
|
||||||
rows := []map[string]any{
|
|
||||||
{"type": "url", "url": "/", "reference": "", "urlPattern": "", "priority": "1.0", "changefreq": "always", "nesting": false},
|
|
||||||
{"type": "acme-post", "url": "", "reference": "7", "urlPattern": "/n/:slug", "priority": "0.5", "changefreq": "weekly", "nesting": true},
|
|
||||||
}
|
|
||||||
rec = e.call(t, http.MethodPut, base+"/"+id, token, map[string]any{"data": rows})
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("PUT rows: %d %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
var raw string
|
|
||||||
if err := e.gdb.Raw(`SELECT data FROM golem15_sitemap_definitions WHERE id = ?`, id).Scan(&raw).Error; err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
const wantData = `[{"changefreq":"always","priority":"1.0","nesting":false,"type":"url","url":"/","reference":null,"cmsPage":null,"urlPattern":""},{"changefreq":"weekly","priority":"0.5","nesting":true,"type":"acme-post","url":"","reference":"7","cmsPage":null,"urlPattern":"/n/:slug"}]`
|
|
||||||
if raw != wantData {
|
|
||||||
t.Fatalf("stored data = %s", raw)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A reference not offered for its row type is a 422 on the row.
|
|
||||||
rows[1]["reference"] = "99"
|
|
||||||
rec = e.call(t, http.MethodPut, base+"/"+id, token, map[string]any{"data": rows})
|
|
||||||
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), "data.1.reference") {
|
|
||||||
t.Fatalf("PUT unknown reference: %d %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// A missing reference for a type that takes one (WR-03), a javascript:
|
|
||||||
// URL and a protocol-relative pattern (CR-01) are 422s on their rows.
|
|
||||||
for _, c := range []struct {
|
|
||||||
row int
|
|
||||||
key, value string
|
|
||||||
field string
|
|
||||||
message string
|
|
||||||
}{
|
|
||||||
{1, "reference", "", "data.1.reference", "golem15.sitemap::lang.item.reference_required"},
|
|
||||||
{1, "reference", " ", "data.1.reference", ""},
|
|
||||||
{0, "url", "javascript://%0aalert(1)%0a//x", "data.0.url", "golem15.sitemap::lang.errors.url_scheme"},
|
|
||||||
{1, "urlPattern", "//evil.test/:slug", "data.1.urlPattern", "golem15.sitemap::lang.errors.url_pattern"},
|
|
||||||
} {
|
|
||||||
bad := []map[string]any{{}, {}}
|
|
||||||
for i := range rows {
|
|
||||||
for k, v := range rows[i] {
|
|
||||||
bad[i][k] = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
bad[1]["reference"] = "7"
|
|
||||||
bad[c.row][c.key] = c.value
|
|
||||||
rec = e.call(t, http.MethodPut, base+"/"+id, token, map[string]any{"data": bad})
|
|
||||||
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), `"`+c.field+`"`) {
|
|
||||||
t.Fatalf("PUT %s=%q: %d %s", c.key, c.value, rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
if c.message != "" && !strings.Contains(rec.Body.String(), c.message) {
|
|
||||||
t.Fatalf("PUT %s=%q: want %s: %s", c.key, c.value, c.message, rec.Body.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := e.gdb.Raw(`SELECT data FROM golem15_sitemap_definitions WHERE id = ?`, id).Scan(&raw).Error; err != nil || raw != wantData {
|
|
||||||
t.Fatalf("a refused save changed the data: %s %v", raw, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The settings form saves the frontend URL.
|
|
||||||
rec = e.call(t, http.MethodPut, "/settings/sitemap_settings", token, map[string]any{"frontend_url": "https://www.example.test", "enable_priority_tiers": true})
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("PUT settings: %d %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
var st models.Settings
|
|
||||||
if err := e.gdb.First(&st, 1).Error; err != nil || models.Text(st.FrontendURL) != "https://www.example.test" {
|
|
||||||
t.Fatalf("settings = %+v %v", st, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// T-17-15: a frontend URL that is not a plain http(s) URL is a 422 on
|
|
||||||
// frontend_url and the stored row keeps its value.
|
|
||||||
for _, value := range []string{"javascript:alert(document.domain)//", `https://x"/><y a="`, "https://www.example.test "} {
|
|
||||||
rec = e.call(t, http.MethodPut, "/settings/sitemap_settings", token, map[string]any{"frontend_url": value, "enable_priority_tiers": true})
|
|
||||||
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), `"frontend_url"`) || !strings.Contains(rec.Body.String(), "golem15.sitemap::lang.errors.frontend_url") {
|
|
||||||
t.Fatalf("PUT settings frontend_url=%q: %d %s", value, rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
var kept models.Settings
|
|
||||||
if err := e.gdb.First(&kept, 1).Error; err != nil || models.Text(kept.FrontendURL) != "https://www.example.test" {
|
|
||||||
t.Fatalf("a refused save of frontend_url=%q changed the settings: %+v %v", value, kept, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
rec = e.call(t, http.MethodGet, "/settings", token, nil)
|
|
||||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"controller":"golem15.sitemap.definitions"`) {
|
|
||||||
t.Fatalf("settings index: %d %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// An empty frontend URL saves: the sitemap keeps the backend URL.
|
|
||||||
rec = e.call(t, http.MethodPut, "/settings/sitemap_settings", token, map[string]any{"frontend_url": "", "enable_priority_tiers": true})
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("PUT settings with an empty frontend_url: %d %s", rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
var cleared models.Settings
|
|
||||||
if err := e.gdb.First(&cleared, 1).Error; err != nil || models.Text(cleared.FrontendURL) != "" {
|
|
||||||
t.Fatalf("settings after an empty frontend_url = %+v %v", cleared, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Without the permission every route answers 403.
|
|
||||||
other := e.admin(t)
|
|
||||||
for _, c := range []struct{ method, path string }{
|
|
||||||
{http.MethodGet, base + "/singleton"},
|
|
||||||
{http.MethodPut, base + "/" + id},
|
|
||||||
{http.MethodGet, "/settings/sitemap_settings"},
|
|
||||||
{http.MethodPut, "/settings/sitemap_settings"},
|
|
||||||
} {
|
|
||||||
if rec := e.call(t, c.method, c.path, other, map[string]any{}); rec.Code != http.StatusForbidden {
|
|
||||||
t.Errorf("%s %s without permission: %d %s", c.method, c.path, rec.Code, rec.Body.String())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,465 +0,0 @@
|
|||||||
<?php
|
|
||||||
/**
|
|
||||||
* Golden generator for the Go sitemap port.
|
|
||||||
*
|
|
||||||
* Runs the PHP Golem15.Sitemap generation code (Definition::generateSitemap,
|
|
||||||
* getXmlObject, getUrlSet, addItemToSet, lookupManifestLastmod,
|
|
||||||
* getPriorityForUrl and the routes.php frontend_url rewrite, copied below
|
|
||||||
* with the Winter facades replaced by the case's inputs) and the vendored
|
|
||||||
* Winter URL generator (Url::to, Url::buildUrl) over a JSON input, and
|
|
||||||
* writes the bytes PHP produces. The Go tests compare their output with the
|
|
||||||
* committed goldens, so CI needs no PHP.
|
|
||||||
*
|
|
||||||
* Usage (from the plugin root, with a WinterCMS vendor directory):
|
|
||||||
*
|
|
||||||
* WINTER_VENDOR=/path/to/winter-app/vendor \
|
|
||||||
* php tests/php/gen-goldens.php classes/testdata/tracer.json classes/testdata/tracer.golden
|
|
||||||
*
|
|
||||||
* Input shapes:
|
|
||||||
*
|
|
||||||
* {"case": {...}} one sitemap case; the golden is its XML
|
|
||||||
* {"cases": [{"name": ..., ...}]} several cases; each written as
|
|
||||||
* "=== name\n" followed by its XML
|
|
||||||
* {"root": ..., "urls": [...]} Url::to of each input, one per line
|
|
||||||
*
|
|
||||||
* A sitemap case: root (the backend root URL), items (stored definition
|
|
||||||
* items, PHP DefinitionItem keys), types (registry item type => reference =>
|
|
||||||
* resolved item {url, mtime, alternates: [[locale, url], ...], items}),
|
|
||||||
* settings (Sitemap settings values; absent keys take the PHP defaults),
|
|
||||||
* manifest (the updates manifest object), skip (URLs a beforeAddItem
|
|
||||||
* listener drops) and extra (URL => text of an <extra> element an addItem
|
|
||||||
* listener appends).
|
|
||||||
*
|
|
||||||
* A registry type's resolved item is given in the Go shape (one item per
|
|
||||||
* record with ordered alternates); this script turns it into what the PHP
|
|
||||||
* headless resolvers returned: a list type (no url) yields one entry per
|
|
||||||
* alternate for each child (a child without alternates once), any other type
|
|
||||||
* its children with their default URL.
|
|
||||||
*/
|
|
||||||
|
|
||||||
$vendor = getenv('WINTER_VENDOR');
|
|
||||||
if (!$vendor || !is_file($vendor . '/autoload.php')) {
|
|
||||||
fwrite(STDERR, "set WINTER_VENDOR to the vendor directory of a WinterCMS application\n");
|
|
||||||
exit(2);
|
|
||||||
}
|
|
||||||
require $vendor . '/autoload.php';
|
|
||||||
|
|
||||||
use Illuminate\Http\Request;
|
|
||||||
use Illuminate\Routing\RouteCollection;
|
|
||||||
use Winter\Storm\Router\UrlGenerator;
|
|
||||||
|
|
||||||
date_default_timezone_set('UTC');
|
|
||||||
|
|
||||||
if ($argc !== 3) {
|
|
||||||
fwrite(STDERR, "usage: php gen-goldens.php INPUT.json OUTPUT.golden\n");
|
|
||||||
exit(2);
|
|
||||||
}
|
|
||||||
|
|
||||||
$input = json_decode(file_get_contents($argv[1]), true);
|
|
||||||
if (!is_array($input)) {
|
|
||||||
fwrite(STDERR, "invalid JSON input\n");
|
|
||||||
exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
function urlGenerator(string $root): UrlGenerator
|
|
||||||
{
|
|
||||||
return new UrlGenerator(new RouteCollection, Request::create(rtrim($root, '/') . '/sitemap.xml'));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($input['urls'])) {
|
|
||||||
$url = urlGenerator($input['root']);
|
|
||||||
$out = '';
|
|
||||||
foreach ($input['urls'] as $path) {
|
|
||||||
$out .= $url->to($path) . "\n";
|
|
||||||
}
|
|
||||||
file_put_contents($argv[2], $out);
|
|
||||||
exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($input['case'])) {
|
|
||||||
file_put_contents($argv[2], (new GoldenSitemap($input['case']))->render());
|
|
||||||
exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
$out = '';
|
|
||||||
foreach ($input['cases'] as $case) {
|
|
||||||
$out .= '=== ' . $case['name'] . "\n" . (new GoldenSitemap($case))->render();
|
|
||||||
}
|
|
||||||
file_put_contents($argv[2], $out);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Golem15\Sitemap\Classes\DefinitionItem, unchanged properties.
|
|
||||||
*/
|
|
||||||
class GoldenDefinitionItem
|
|
||||||
{
|
|
||||||
public $changefreq;
|
|
||||||
public $priority;
|
|
||||||
public $nesting = false;
|
|
||||||
public $type = 'url';
|
|
||||||
public $url = null;
|
|
||||||
public $code = null;
|
|
||||||
public $reference = null;
|
|
||||||
public $cmsPage = null;
|
|
||||||
public $urlPattern = null;
|
|
||||||
public $exists = false;
|
|
||||||
|
|
||||||
public static function initFromArray(array $items): array
|
|
||||||
{
|
|
||||||
$result = [];
|
|
||||||
foreach ($items as $itemData) {
|
|
||||||
$obj = new self;
|
|
||||||
foreach ($itemData as $name => $value) {
|
|
||||||
if (property_exists($obj, $name)) {
|
|
||||||
$obj->$name = $value;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$result[] = $obj;
|
|
||||||
}
|
|
||||||
return $result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The generation code of Golem15\Sitemap\Models\Definition and routes.php.
|
|
||||||
*/
|
|
||||||
class GoldenSitemap
|
|
||||||
{
|
|
||||||
const MAX_URLS = 50000;
|
|
||||||
|
|
||||||
protected $case;
|
|
||||||
protected $url;
|
|
||||||
protected $items;
|
|
||||||
protected $updatesManifest = null;
|
|
||||||
protected $urlCount = 0;
|
|
||||||
protected $urlSet;
|
|
||||||
protected $xmlObject;
|
|
||||||
|
|
||||||
public function __construct(array $case)
|
|
||||||
{
|
|
||||||
$this->case = $case;
|
|
||||||
$this->url = urlGenerator($case['root']);
|
|
||||||
$this->items = GoldenDefinitionItem::initFromArray($case['items'] ?? []);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function setting(string $key, $default)
|
|
||||||
{
|
|
||||||
$settings = $this->case['settings'] ?? [];
|
|
||||||
return array_key_exists($key, $settings) ? $settings[$key] : $default;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** routes.php */
|
|
||||||
public function render(): string
|
|
||||||
{
|
|
||||||
$xml = $this->generateSitemap();
|
|
||||||
|
|
||||||
$frontendUrl = $this->setting('frontend_url', null);
|
|
||||||
if ($frontendUrl) {
|
|
||||||
$frontendUrl = rtrim($frontendUrl, '/');
|
|
||||||
$backendUrl = rtrim($this->url->to('/'), '/');
|
|
||||||
$xml = preg_replace_callback('/<loc>(.*?)<\/loc>/', function ($m) use ($backendUrl, $frontendUrl) {
|
|
||||||
return '<loc>' . str_replace($backendUrl, $frontendUrl, $m[1]) . '</loc>';
|
|
||||||
}, $xml);
|
|
||||||
$xml = preg_replace_callback('/(<xhtml:link[^>]*href=")([^"]*)(")/', function ($m) use ($backendUrl, $frontendUrl) {
|
|
||||||
return $m[1] . str_replace($backendUrl, $frontendUrl, $m[2]) . $m[3];
|
|
||||||
}, $xml);
|
|
||||||
$xml = str_replace(
|
|
||||||
'href="' . $backendUrl . '/sitemap.xsl"',
|
|
||||||
'href="' . $frontendUrl . '/sitemap.xsl"',
|
|
||||||
$xml
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return $xml;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* What the PHP headless resolvers returned for a resolved item in the
|
|
||||||
* Go shape.
|
|
||||||
*/
|
|
||||||
protected function phpResolved(array $r, bool $listChildren): array
|
|
||||||
{
|
|
||||||
$info = [];
|
|
||||||
if (!empty($r['url'])) {
|
|
||||||
$info['url'] = $r['url'];
|
|
||||||
}
|
|
||||||
if (array_key_exists('mtime', $r)) {
|
|
||||||
$info['mtime'] = $r['mtime'] === null ? null : new DateTime($r['mtime']);
|
|
||||||
}
|
|
||||||
$links = [];
|
|
||||||
foreach ($r['alternates'] ?? [] as [$locale, $href]) {
|
|
||||||
$links[$locale] = $href;
|
|
||||||
}
|
|
||||||
$info['alternateLinks'] = $links;
|
|
||||||
if (isset($r['items'])) {
|
|
||||||
$info['items'] = [];
|
|
||||||
foreach ($r['items'] as $child) {
|
|
||||||
$childInfo = $this->phpResolved($child, false);
|
|
||||||
if ($listChildren && $childInfo['alternateLinks']) {
|
|
||||||
foreach ($childInfo['alternateLinks'] as $locale => $href) {
|
|
||||||
$perLocale = $childInfo;
|
|
||||||
$perLocale['url'] = $href;
|
|
||||||
$info['items'][] = $perLocale;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
$info['items'][] = $childInfo;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return $info;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function resolveItem(GoldenDefinitionItem $item)
|
|
||||||
{
|
|
||||||
$types = $this->case['types'] ?? [];
|
|
||||||
$ref = (string) $item->reference;
|
|
||||||
if (!isset($types[$item->type][$ref])) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
$r = $types[$item->type][$ref];
|
|
||||||
return $this->phpResolved($r, empty($r['url']));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function generateSitemap(): string
|
|
||||||
{
|
|
||||||
if (!$this->items) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ($this->items as $item) {
|
|
||||||
if ($item->type === 'url') {
|
|
||||||
$this->addItemToSet($item);
|
|
||||||
} else {
|
|
||||||
$menuItemInfo = $this->resolveItem($item);
|
|
||||||
if (!is_array($menuItemInfo)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($menuItemInfo['url'])) {
|
|
||||||
$this->addItemToSet($item, $menuItemInfo);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($menuItemInfo['items'])) {
|
|
||||||
$menuItemIterator = function ($menuItems) use (&$menuItemIterator, $item) {
|
|
||||||
foreach ($menuItems as $menuItem) {
|
|
||||||
if (isset($menuItem['url'])) {
|
|
||||||
$this->addItemToSet($item, $menuItem);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isset($menuItem['items'])) {
|
|
||||||
$menuItemIterator($menuItem['items']);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
$menuItemIterator($menuItemInfo['items']);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$urlSet = $this->getUrlSet();
|
|
||||||
$xml = $this->getXmlObject();
|
|
||||||
$xml->appendChild($urlSet);
|
|
||||||
|
|
||||||
return $xml->saveXML();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getXmlObject(): DOMDocument
|
|
||||||
{
|
|
||||||
if ($this->xmlObject !== null) {
|
|
||||||
return $this->xmlObject;
|
|
||||||
}
|
|
||||||
|
|
||||||
$xml = new DOMDocument;
|
|
||||||
$xml->encoding = 'UTF-8';
|
|
||||||
$xss = $xml->createProcessingInstruction('xml-stylesheet',
|
|
||||||
'type="text/xsl" href="' . UrlGenerator::buildUrl($this->url->current(), ['path' => 'sitemap.xsl']) . '"'
|
|
||||||
);
|
|
||||||
$xml->appendChild($xss);
|
|
||||||
|
|
||||||
return $this->xmlObject = $xml;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getUrlSet(): DOMElement
|
|
||||||
{
|
|
||||||
if ($this->urlSet !== null) {
|
|
||||||
return $this->urlSet;
|
|
||||||
}
|
|
||||||
|
|
||||||
$xml = $this->getXmlObject();
|
|
||||||
$urlSet = $xml->createElement('urlset');
|
|
||||||
$urlSet->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
|
|
||||||
$urlSet->setAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml');
|
|
||||||
$urlSet->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
|
|
||||||
$urlSet->setAttribute('xsi:schemaLocation', 'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd');
|
|
||||||
|
|
||||||
return $this->urlSet = $urlSet;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function addItemToSet(GoldenDefinitionItem $item, ?array $itemInfo = null): void
|
|
||||||
{
|
|
||||||
$xml = $this->getXmlObject();
|
|
||||||
$urlSet = $this->getUrlSet();
|
|
||||||
|
|
||||||
if ($this->urlCount >= self::MAX_URLS) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isset($itemInfo['url'])) {
|
|
||||||
$itemInfo['url'] = $this->url->to($item->url);
|
|
||||||
}
|
|
||||||
|
|
||||||
$lastModified = $itemInfo['mtime'] ?? null;
|
|
||||||
|
|
||||||
if ($lastModified === null) {
|
|
||||||
$lastModified = $this->lookupManifestLastmod($itemInfo['url']);
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($lastModified instanceof \DateTime) {
|
|
||||||
$lastModified = $lastModified->getTimestamp();
|
|
||||||
}
|
|
||||||
$itemInfo['lastModified'] = $lastModified ? date('c', $lastModified) : null;
|
|
||||||
|
|
||||||
// golem15.sitemap.beforeAddItem: a listener that drops the case's
|
|
||||||
// skip URLs.
|
|
||||||
if (in_array($itemInfo['url'], $this->case['skip'] ?? [], true)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (empty($itemInfo['url'])) {
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
$itemInfo['url'] = $this->url->to($itemInfo['url']);
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->urlCount++;
|
|
||||||
|
|
||||||
$tierPriority = $this->getPriorityForUrl($itemInfo['url']);
|
|
||||||
$effectivePriority = $tierPriority ?? $item->priority;
|
|
||||||
|
|
||||||
$urlElement = $xml->createElement('url');
|
|
||||||
|
|
||||||
$loc = $xml->createElement('loc');
|
|
||||||
$loc->appendChild($xml->createTextNode($itemInfo['url']));
|
|
||||||
$urlElement->appendChild($loc);
|
|
||||||
|
|
||||||
if (!empty($itemInfo['lastModified'])) {
|
|
||||||
$lastmod = $xml->createElement('lastmod');
|
|
||||||
$lastmod->appendChild($xml->createTextNode((string) $itemInfo['lastModified']));
|
|
||||||
$urlElement->appendChild($lastmod);
|
|
||||||
}
|
|
||||||
|
|
||||||
$changefreq = $xml->createElement('changefreq');
|
|
||||||
$changefreq->appendChild($xml->createTextNode((string) $item->changefreq));
|
|
||||||
$urlElement->appendChild($changefreq);
|
|
||||||
|
|
||||||
$priority = $xml->createElement('priority');
|
|
||||||
$priority->appendChild($xml->createTextNode((string) $effectivePriority));
|
|
||||||
$urlElement->appendChild($priority);
|
|
||||||
|
|
||||||
if (!empty($itemInfo['alternateLinks']) && count($itemInfo['alternateLinks']) > 1) {
|
|
||||||
foreach ($itemInfo['alternateLinks'] as $hreflang => $href) {
|
|
||||||
$link = $xml->createElement('xhtml:link');
|
|
||||||
$link->setAttribute('rel', 'alternate');
|
|
||||||
$link->setAttribute('hreflang', $hreflang);
|
|
||||||
$link->setAttribute('href', $this->url->to($href));
|
|
||||||
$urlElement->appendChild($link);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$urlSet->appendChild($urlElement);
|
|
||||||
|
|
||||||
// golem15.sitemap.addItem: a listener that appends the case's extra
|
|
||||||
// element to the URL.
|
|
||||||
$extra = $this->case['extra'] ?? [];
|
|
||||||
if (isset($extra[$itemInfo['url']])) {
|
|
||||||
$element = $xml->createElement('extra');
|
|
||||||
$element->appendChild($xml->createTextNode($extra[$itemInfo['url']]));
|
|
||||||
$urlElement->appendChild($element);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function lookupManifestLastmod(string $url): ?int
|
|
||||||
{
|
|
||||||
$manifest = $this->getUpdatesManifest();
|
|
||||||
if (!$manifest) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$path = parse_url($url, PHP_URL_PATH) ?: '/';
|
|
||||||
$path = $this->normalizeManifestPath($path);
|
|
||||||
|
|
||||||
if (!isset($manifest[$path])) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$timestamp = strtotime((string) $manifest[$path]);
|
|
||||||
|
|
||||||
return $timestamp ?: null;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getUpdatesManifest(): array
|
|
||||||
{
|
|
||||||
if ($this->updatesManifest !== null) {
|
|
||||||
return $this->updatesManifest;
|
|
||||||
}
|
|
||||||
|
|
||||||
$decoded = $this->case['manifest'] ?? null;
|
|
||||||
if (!is_array($decoded)) {
|
|
||||||
return $this->updatesManifest = [];
|
|
||||||
}
|
|
||||||
|
|
||||||
$normalized = [];
|
|
||||||
foreach ($decoded as $key => $value) {
|
|
||||||
$normalized[$this->normalizeManifestPath((string) $key)] = $value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $this->updatesManifest = $normalized;
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function normalizeManifestPath(string $path): string
|
|
||||||
{
|
|
||||||
$path = '/' . ltrim($path, '/');
|
|
||||||
|
|
||||||
return $path === '/' ? '/' : rtrim($path, '/');
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getPriorityForUrl(string $url): ?string
|
|
||||||
{
|
|
||||||
if (!$this->setting('enable_priority_tiers', true)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
$path = parse_url($url, PHP_URL_PATH) ?: '/';
|
|
||||||
$path = rtrim($path, '/');
|
|
||||||
|
|
||||||
if ($path === '' || $path === '/en') {
|
|
||||||
return $this->setting('priority_homepage', '1.0');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (preg_match('#^/(uslugi|en/services|realizacje|en/work)/[^/]+$#', $path)) {
|
|
||||||
return $this->setting('priority_services', '0.8');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (preg_match('#^/(blog|en/blog)/[^/]+/[^/]+$#', $path)) {
|
|
||||||
return $this->setting('priority_blog', '0.6');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (preg_match('#^/(uslugi|en/services|realizacje|en/work|blog|en/blog)(/[^/]+)?$#', $path)) {
|
|
||||||
return $this->setting('priority_categories', '0.4');
|
|
||||||
}
|
|
||||||
|
|
||||||
$legalPaths = [
|
|
||||||
'/polityka-prywatnosci', '/en/privacy-policy',
|
|
||||||
'/regulamin', '/en/terms',
|
|
||||||
'/o-nas', '/en/about',
|
|
||||||
'/kontakt', '/en/contact',
|
|
||||||
'/laboratorium-ai', '/en/ai-lab',
|
|
||||||
'/laboratorium-ai/zabawa-animacja', '/en/ai-lab/blob-playground',
|
|
||||||
];
|
|
||||||
if (in_array($path, $legalPaths)) {
|
|
||||||
return $this->setting('priority_legal', '0.2');
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user