Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .wordpress-org/blueprints/blueprint.json

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- **ABNT and OSCOLA citations paste as text.** Borges already formatted both styles but could not read them back, so a pasted ABNT or OSCOLA citation with no DOI got the "Paste a DOI, PMID…" notice, or worse, came back as a book with "17. ed. Rio de Janeiro: Paz e Terra" as its publisher. ABNT citations (`FREIRE, Paulo. Pedagogia do oprimido. 17. ed. Rio de Janeiro: Paz e Terra, 1987.`) now read as books, chapters, articles (`v. 27, n. 2, p. 97-111, abr. 2020`), theses, preprints, magazine articles, software, and web pages (`Disponível em:`, `Acesso em:`), with surnames in capitals written back as names (Paulo Freire) and Portuguese month abbreviations read as dates. OSCOLA secondary sources (`Hart HLA, Punishment and Responsibility (OUP 1968)`, `Endicott TAO, ‘The Impossibility of the Rule of Law’ (1999) 19 OJLS 1`) read as books, articles, chapters, newspaper articles, encyclopedia entries, theses, preprints, and web pages, in the bibliography's name form or the footnote's (`HLA Hart`). In an OSCOLA bibliography, pasted lines that end in a page number or an access date now become one entry each instead of being joined into one. Each style's reader runs first in its own bibliography, and an ABNT surname in capitals sends a citation to the ABNT reader in any bibliography. Cases, legislation, treaties, and reviews are still declined. Like the other formatted-citation readers, these mark each entry for review. On the plugin's test lists they recover every detail the styles print in the 12-work list and all but one in the 36-work list, and on 7,846 labelled references from AnyStyle they read 30 more with no new wrong titles. The Playground demo's formatted-citation samples add one of each. ([#231](https://github.com/dknauss/Borges/issues/231))

- **DOIs for datasets and software resolve.** Borges asked only Crossref for a DOI's metadata, so a DOI registered with DataCite, which covers most datasets, software releases, and repository deposits (every Zenodo record, figshare, Dryad, many university repositories), failed with "Couldn't parse the DOI." When Crossref has no record for a DOI, the editor now asks DataCite through a new editor-only REST route, `GET /bibliography/v1/datacite?doi=…` (`edit_posts`), which calls DataCite's fixed content negotiation host and caches the answer like the other resolvers. Crossref stays first, and only its "not found" falls through, so DOIs it holds resolve exactly as before. The route keeps DataCite's CSL as sent, except that organizations sent as a bare family name (“The pandas development team”) become one name, the DOI is stored in lowercase, and the subject keywords, license, and abstract are dropped. The Playground demo's DOI samples add a Dryad dataset and a Zenodo software release. The readme's External Services section lists DataCite.

### Fixed

- **Confirmations no longer make the list jump.** After an action, its confirmation (“Moved … to position 2 of 5.”, “Copied citation.”, “Fields saved.”, “Added 3 citations.”, “Style changed to APA 7.”) was a black box at the top of the citation list, out of view when you were working further down, and when it went five seconds later the list moved up by its height and the scroll jumped back. Confirmations now appear in the editor’s own snackbar area at the bottom of the screen, as WordPress’s do (“Post updated.”), where they are always in view, take no room in the block, and are announced to screen readers. Warnings and errors that need reading, such as an import with skipped duplicates or a field that needs fixing, stay next to the add form and never disappear on a timer. The hints shown when an edit starts are now help text in the edit form (“Press Enter to save or Escape to cancel.”, and a one-line description on the field-by-field form) instead of a notice above the list, so starting an edit no longer pushes the list down.
Expand Down
5 changes: 3 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,11 @@ A Gutenberg block plugin that accepts DOI identifiers, PubMed/PMID records, BibT
- `GET /pmid/{pmid}` — resolves PubMed/PMID records through a fixed NCBI/PMC CSL endpoint; requires `edit_posts`
- `GET /pmcid/{pmcid}` — resolves PubMed Central/PMCID records through NCBI's fixed PMC CSL endpoint via the same shared resolver; requires `edit_posts`
- Both NCBI routes return the record after `bibliography_builder_normalize_ncbi_csl()` dots bare initials, drops a "Pt" issue label, and drops an NLM journal subtitle that matches `container-title-short` (#270, #271); the editor applies the same rules in `src/lib/ncbi-normalize.js` to every NCBI path. Keep the two in step.
- `GET /datacite?doi={doi}` — resolves DOIs registered with DataCite (datasets, software, Zenodo/figshare/Dryad deposits) through DataCite's fixed content negotiation host (`BIBLIOGRAPHY_BUILDER_DATACITE_CSL_API`); the editor calls it only after Crossref answers 404 for a DOI (`resolveDoiViaRegistries()` in `parser-resolvers.js`), so DOIs Crossref holds never reach it; requires `edit_posts`. Registered after `/archive`, so earlier route indices are unchanged
- `GET /arxiv?id={id}` — resolves arXiv IDs through the fixed arXiv API, mapping Atom to a CSL preprint in PHP; requires `edit_posts`
- `GET /isbn/{isbn}` — resolves checksum-valid ISBNs through Open Library's fixed ISBN edition endpoint (author names from its search endpoint), falling back to Google Books, mapping to a CSL book in PHP; requires `edit_posts`
- `GET /catalog?id={OCLC:|LCCN:|OLID:key}` — resolves OCLC numbers, LCCNs, and Open Library edition IDs through Open Library's fixed Books API (`jscmd=data`), mapping to a CSL book in PHP; requires `edit_posts`
- `GET /archive?id={identifier|ark:/13960/…}` — resolves Internet Archive items (an ARK through IA's advanced search first) from the fixed `archive.org/metadata/` host, preferring the item's Open Library edition, ISBN, then LCCN, else mapping the scan metadata; URL is always the archive.org item page; requires `edit_posts`. Both routes are registered last so earlier route indices (pinned by tests) stay stable.
- `GET /archive?id={identifier|ark:/13960/…}` — resolves Internet Archive items (an ARK through IA's advanced search first) from the fixed `archive.org/metadata/` host, preferring the item's Open Library edition, ISBN, then LCCN, else mapping the scan metadata; URL is always the archive.org item page; requires `edit_posts`. Both routes are registered after the others (only `/datacite` follows them) so earlier route indices (pinned by tests) stay stable.
- `GET /posts/{post_id}/bibliographies` — list all bibliography blocks in post
- `GET /posts/{post_id}/bibliographies/{index}` — single bibliography; supports `?format=json|text|csl-json`
- Write routes (Phase 05 M2 and M3, `includes/write-routes.php`): POST/PATCH/DELETE/PUT under `/posts/{post_id}/bibliographies/{ref}/citations`, plus PATCH `/posts/{post_id}/bibliographies/{ref}` (block settings) and POST `…/{ref}/reformat` (style switch, mirroring the editor's `handleCitationStyleChange`). They are **off unless** the `bibliography_builder_enable_write_routes` filter returns true. They need `edit_post`, are dry runs unless `dry_run=false`, and need `If-Match` (the post's ETag, a hash of its content). A write rebuilds markup with the `save()` port and splices only that block via `includes/block-locator.php`. See `docs/rest-write-routes.md`.
Expand All @@ -96,7 +97,7 @@ A Gutenberg block plugin that accepts DOI identifiers, PubMed/PMID records, BibT
- Render-time COinS enrichment (`includes/coins-enrichment.php`): a `render_block` filter (priority 11) appends to each saved `Z3988` span an `rft.au` for every author after the first, organizations and one-part names written as `Name,` (all of them, replacing `rft.aulast`/`rft.aufirst`, when a later author shares the first one's last name), so Zotero's OpenURL reader neither repeats, drops, nor moves a name (it puts every `rft.aucorp` first). `CoinsEnrichmentTest` models that reader in CI; `tools/markup-value/zotero-coins.mjs` runs Zotero's own reader, downloaded at a pinned commit since it is AGPL, and an `info:pmid/` `rft_id`, plus (via `bibliography_builder_coins_enrich_fields()`) an `rft.genre` for the item type, the book format for conference papers and reports, a chapter's pages, publisher and place, a book's edition, a journal's ISSN, and the URL as an `rft_id`, matching spans to citations by the `<li id="ref-…">` order and leaving misaligned markup alone. Like the JSON-LD enrichment, `save()` is unchanged. Filter: `bibliography_builder_enrich_coins`.
- Render-time microformats (`includes/microformats.php`): a `render_block` filter (priority 11) adds the class `h-cite` to each entry `<li id="ref-…">` and, right after its start tag, an empty `<span class="bibliography-builder-microformats" hidden>` of `<data>` elements from the stored CSL: `p-name`, a `p-author h-card` per author (ORCID as `u-url`; organizations `p-org`), `dt-published` (only the date parts the record has), `u-uid u-url` for the DOI, `u-url` for the URL, `p-publication`, and `p-publisher`. Entries are matched to citations by the ID in their anchor, not by position; the `<li>` start tag is read with a quote-aware pattern (WP_HTML_Tag_Processor cannot insert markup, and the PHPUnit bootstrap has no copy of it). Feeds skip it and `bibliography_builder_portable_markup()` strips the span for email. `save()` is unchanged. Filter: `bibliography_builder_enrich_microformats`.
- Site-wide output defaults (`includes/output-defaults.php`, `src/lib/output-defaults.js`): the `bibliography_builder_output_defaults` filter reaches the editor as the `bibliographyBuilderOutputDefaults` block editor setting, and `useOutputDefaults()` writes it into newly inserted blocks as explicit attributes. The same setting carries `headingLevel` for new blocks (2, an `<h2>`, unless `bibliography_builder_new_block_heading_level` returns 0 or 3–6), while `block.json` keeps 0 (a paragraph). Never change the `block.json` defaults for this: omitted attributes take the default, so it would invalidate saved blocks.
- The PMID, PMCID, arXiv, ISBN, catalog, and Internet Archive route callbacks, their provider constants (fixed upstream URLs, timeout, cache TTLs), and the NCBI cache helpers live in `includes/resolvers.php`, loaded by `require_once` from the main file. Route registration and the `edit_posts` permission callbacks stay in `bibliography-builder.php`.
- The PMID, PMCID, arXiv, ISBN, catalog, Internet Archive, and DataCite route callbacks, their provider constants (fixed upstream URLs, timeout, cache TTLs), and the NCBI cache helpers live in `includes/resolvers.php`, loaded by `require_once` from the main file. Route registration and the `edit_posts` permission callbacks stay in `bibliography-builder.php`.
- `includes/google-books-key.php` reads an optional Google Books API key from the `BIBLIOGRAPHY_BUILDER_GOOGLE_BOOKS_API_KEY` constant, then the `bibliography_builder_google_books_api_key` filter. It is added only to the ISBN resolver's Google Books fallback request. There is deliberately no option or settings screen: `verify-metrics.sh` enforces that the plugin persists no settings.
- WP-CLI commands (`includes/cli.php`, `includes/class-bibliography-builder-cli-command.php`, loaded only when `WP_CLI` is defined): the read-only `wp borges list`, `export`, `validate`, and `duplicates` (a site-wide report of what `deduplicate` would remove, plus cross-block repeats, from `bibliography_builder_bulk_split_duplicates()`) call the same read model and validation report as the REST routes and abilities. `wp borges reformat` and `deduplicate` write through `bibliography_builder_bulk_reformat_post()` and `…_bulk_deduplicate_post()`; they always need `--user`, the write-routes filter, `edit_others_posts`, and `edit_post` per post, and skips the rate limit (batches via `--batch-size`/`--sleep`). With no current user (no `--user`) they check no capabilities, like core's commands; with `--user` they apply the REST/abilities checks (`bibliography_builder_can_read_post()` for list and export, `bibliography_builder_can_review_post()` for validate). `validate` exits 1 on any error. Tests use the recording stub `tests/phpunit/stubs/wp-cli.php`, which Psalm also loads, and `scripts/runtime-matrix/smoke.sh` runs the real commands. See `docs/wp-cli.md`.
- Read-only Abilities API integration (WordPress 6.9+) lives in `includes/abilities.php`: `borges/get-bibliographies`, `borges/export-bibliography`, `borges/validate-citations` in a `bibliography` category. They reuse the REST read/permission helpers; on older WordPress the `wp_abilities_api_*` hooks never fire.
Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,12 @@ DOI input connects to the [CrossRef REST API](https://api.crossref.org/) to reso
- [CrossRef privacy policy](https://www.crossref.org/privacy/)
- [CrossRef terms of service](https://www.crossref.org/terms/)

When Crossref has no record for a DOI, as for most datasets, software releases, and repository deposits (Zenodo, figshare, Dryad), the DOI is looked up through the plugin's authenticated WordPress REST proxy in [DataCite's content negotiation service](https://support.datacite.org/docs/datacite-content-resolver) (`api.datacite.org/dois/`). The proxy uses a fixed upstream host and validates the DOI before making the outbound request. Only the DOI is sent.

- [DataCite content negotiation](https://support.datacite.org/docs/datacite-content-resolver)
- [DataCite privacy policy](https://datacite.org/privacy-policy/)
- [DataCite terms and conditions](https://datacite.org/terms-and-conditions/)

### PubMed/PMID and PubMed Central/PMCID metadata

PubMed/PMID and PubMed Central/PMCID input connects through the plugin's authenticated WordPress REST proxy to the [NCBI/PMC Literature Citation Exporter](https://pmc.ncbi.nlm.nih.gov/api/ctxp/) CSL endpoints. The proxy uses a fixed upstream host and validates the identifier as numeric before making the outbound request. Only the identifier is sent.
Expand Down
5 changes: 3 additions & 2 deletions SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ A standalone WordPress block plugin that transforms pasted scholarly citations (
| ------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
| `citation-js` (npm) | BibTeX parsing and fallback DOI support | Free, no API key. Pinned package versions keep parser behavior stable. |
| CrossRef API | Primary DOI metadata provider through the CORS-friendly CSL transform endpoint; `citation-js` remains available as a fallback where direct browser fetch is unavailable | Free, public, no key required |
| DataCite content negotiation | DOI fallback when CrossRef answers 404 (datasets, software, Zenodo/figshare/Dryad deposits), through the editor-only `GET /bibliography/v1/datacite?doi=` proxy to `api.datacite.org` | Free, public, no key required |
| `citeproc-php` (Composer) | Local CSL-JSON → plain-text bibliography formatting using plugin-owned GPL-compatible styles/locales | Runs locally in WordPress; no external service |
| AnyStyle (Ruby gem) | ML-based free-text citation parsing | Free to self-host; no public API. **Not needed for MVP.** |

Expand All @@ -53,7 +54,7 @@ A standalone WordPress block plugin that transforms pasted scholarly citations (

### Supported Input Formats

1. **DOI** — one or more per paste, one per line. Detected by `10.\d{4,}/` pattern. Resolved to CSL-JSON through CrossRef's CORS-friendly CSL transform endpoint, with sequential browser fetches and a `citation-js` fallback when direct fetch is unavailable.
1. **DOI** — one or more per paste, one per line. Detected by `10.\d{4,}/` pattern. Resolved to CSL-JSON through CrossRef's CORS-friendly CSL transform endpoint, with sequential browser fetches and a `citation-js` fallback when direct fetch is unavailable. When CrossRef answers 404, the DOI is tried once more through the plugin's DataCite route (`GET /bibliography/v1/datacite?doi=`), which covers the DOIs of datasets, software, and repository deposits; any other CrossRef failure is reported as it is.
2. **PubMed/PMID** — one or more `PMID:<number>` entries per paste. Resolved through the authenticated WordPress REST proxy to a fixed NCBI/PMC CSL endpoint; PMID input is validated as numeric before any outbound request.
3. **PubMed Central/PMCID** — one or more `PMC<number>` entries per paste, with or without a `PMCID:` label. Resolved through the same authenticated proxy pattern to NCBI's fixed PMC citation-exporter endpoint; the ID is reduced to its digits before any outbound request and sent upstream as bare digits (the exporter answers `id=PMC<digits>` with HTTP 400). Free-text citations carrying `PMC<4+ digits>` are routed here when they have no DOI or labeled PMID.
4. **arXiv** — `arXiv:<id>`, arxiv.org `/abs/` or `/pdf/` URLs, or arXiv DataCite DOIs (`10.48550/arXiv.<id>`), in modern (`2301.00001`) or legacy (`hep-th/9901001`) form with an optional version. Resolved through `GET /bibliography/v1/arxiv?id=<id>`, which queries the fixed `export.arxiv.org` API and maps the Atom response to a CSL `article` preprint (publisher `arXiv`, number `arXiv:<id>`, the arXiv DOI, and the abstract URL). A bare number is not treated as an arXiv ID. arXiv lookups run one at a time in the editor to respect arXiv's request-rate guidance.
Expand Down Expand Up @@ -604,7 +605,7 @@ Formatted bibliography strings are generated locally through `citeproc-php` usin

### Parse Failures

- **Unresolvable DOI** (CrossRef returns 404): skip the entry, include it in the failure count, surface the raw input in the error message so the user can correct and retry.
- **Unresolvable DOI** (CrossRef returns 404 and DataCite has no record either): skip the entry, include it in the failure count, surface the raw input in the error message so the user can correct and retry.
- **Malformed BibTeX**: `citation-js` throws on invalid syntax. Catch, skip, and report.
- **Network failure** (DOI resolution requires fetch): surface a "Could not connect to CrossRef. Check your internet connection." notice. Allow retry.

Expand Down
49 changes: 49 additions & 0 deletions bibliography-builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,23 @@ function bibliography_builder_rest_archive_permissions_check() {
);
}

/**
* Permission callback for editor-only DataCite DOI resolver requests.
*
* @return true|WP_Error
*/
function bibliography_builder_rest_datacite_permissions_check() {
if ( current_user_can( 'edit_posts' ) ) {
return true;
}

return new WP_Error(
'bibliography_builder_datacite_forbidden',
__( 'Sorry, you are not allowed to resolve DataCite DOIs.', 'borges-bibliography-builder' ),
array( 'status' => 403 )
);
}

/**
* Register REST routes.
*
Expand Down Expand Up @@ -596,6 +613,38 @@ static function ( $value ) {
),
)
);

// DataCite DOI resolver: the editor's fallback when Crossref has no record
// for a DOI. Registered after the others so their route indices stay stable.
register_rest_route(
'bibliography/v1',
'/datacite',
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'bibliography_builder_rest_resolve_datacite',
'permission_callback' => 'bibliography_builder_rest_datacite_permissions_check',
'args' => array(
'doi' => array(
'description' => __(
'DOI registered with DataCite to resolve to CSL-JSON.',
'borges-bibliography-builder'
),
'type' => 'string',
'required' => true,
'validate_callback' =>
/**
* Validates the DOI parameter.
*
* @param mixed $value Value to check.
* @return bool
*/
static function ( $value ) {
return '' !== bibliography_builder_normalize_doi( $value );
},
),
),
)
);
}


Expand Down
Loading
Loading