=== 404ops Docstore ===
Contributors: spwhite
Tags: documents, document management, files, departments, audit log
Requires at least: 7.0
Tested up to: 7.1
Requires PHP: 8.0
Stable tag: 1.10.10
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Store, organize, search and audit documents in WordPress, grouped by department, with per-department access. No external service needed.

== Description ==

404ops Docstore is a private document library inside WordPress. Organize documents into departments, upload them (one at a time or in batches), list, download, version, expire and search them - all on your own site. **No external service is needed**: documents are stored in the plugin's own database tables and in a protected folder under your uploads directory, and the admin Search screen does keyword search over an index kept in your WordPress database.

Stored documents never get a public URL. The files sit behind server deny rules under names nobody can guess, and they are only ever handed out through a signed, access-checked download link for a signed-in user who may view that department.

Connecting a self-hosted DocStore API is optional. If you run one, a department with its own API key can keep its documents there instead; every other department keeps using the site's own storage. There is no 404ops-hosted endpoint and no default address; see "External services" for what gets transmitted when you connect one.

**Free features**

* Departments with per-department access: view, upload, edit and delete, decided by DocStore roles, per-department grants or viewer/manager assignment.
* Document storage on your own site, folders inside a department, per-department storage quotas, batch upload, download links that check access, and a REST API for the same.
* Keyword search over the text of your documents (PDF, Word, Excel and PowerPoint are read on your own server), scoped to what each user may open, plus the `[docstore_search]` shortcode for signed-in users.
* Expiry dates (flag or archive), version history (2 to 99 versions per document, default 10) and an audit log (30 to 1095 days, default 90), configured in Settings → Advanced.
* Optional: keep a department's documents in your own S3-compatible bucket; semantic search and "Ask your documents" with your own AI provider; AI agent tools through Agent Gate; a remote DocStore API connector.

**Pro add-on** (sold separately): Google Drive, Dropbox and OneDrive storage, similar-document lookup and a duplicate report, expiry reminder emails, review dates in bulk. Version and audit retention choices are included in Free.

Every grant and revocation, every upload and every deletion is written to the audit log. The FAQ explains exactly how access is decided.


== External services ==

Out of the box the plugin contacts no external service: documents, their text and the search index all stay on your site. Three optional services can be connected, and you supply all of them. It contacts nothing else on its own.

The first is a remote DocStore API that you run or point the plugin at. There is no 404ops-operated endpoint, and the plugin ships with no default address. It is used only for a department that has its own API key, and only once you enter the API URL in Settings. For such a department, its document contents, filenames, metadata and search queries are sent from your site to that address, authenticated with an `X-API-Key` header. Each call uses the department's own key, so nothing about the signed-in user is sent. Rebuilding the search index reads that department's documents back from the same service. The terms and privacy policy that apply are those of whoever operates the service. Use an `https://` address so the traffic is encrypted in transit.

The second is S3-compatible object storage (Amazon S3, Cloudflare R2, Backblaze B2, MinIO, Garage and the like) that you set up under Settings > Storage. It is used only for a department you choose to keep there. For such a department, each document's bytes are sent from your site to the endpoint you entered, under a random object key (the title and filename are not in the key), signed with the access key you supplied; downloads and deletes call the same endpoint, and the Storage tab's Test Connection writes, reads and deletes one small probe object. The terms and privacy policy that apply are those of the storage provider you chose. Pro adds Google Drive, Dropbox and OneDrive the same way, described in the Pro add-on's readme. Policy references for the hosted examples: Amazon S3 [service terms](https://aws.amazon.com/service-terms/) and [privacy notice](https://aws.amazon.com/privacy/); Cloudflare R2 [subscription terms](https://www.cloudflare.com/terms/) and [privacy policy](https://www.cloudflare.com/privacypolicy/); Backblaze B2 [terms of service](https://www.backblaze.com/company/policy/terms-of-service) and [privacy policy](https://www.backblaze.com/company/policy/privacy). For MinIO, Garage or another self-hosted/custom endpoint, review the configured server operator’s terms and privacy policy; choosing an adapter does not itself contact that software’s vendor.

If you connect an AI provider on the AI Connection screen and turn DocStore on for it, the AI features send text to that provider. Semantic search sends document text to be embedded, and Ask your documents sends your question with the document excerpts it draws on. Access and expiry are checked before any text is sent, and a department can be set to never send anything to an AI provider. The screens that send text name the provider they send it to. The provider is the one you choose: OpenAI (api.openai.com), Anthropic (api.anthropic.com), Google Gemini (generativelanguage.googleapis.com), OpenRouter (openrouter.ai), or the address you enter for Ollama or an OpenAI-compatible service. Its terms apply to what it receives. Nothing is sent to a provider until you connect one and use one of those features.

AI provider policy references for the optional shared AI connection:

* OpenAI: [API services agreement](https://openai.com/policies/services-agreement/) and [privacy policy](https://openai.com/policies/privacy-policy/).
* Anthropic: [commercial terms](https://www.anthropic.com/legal/commercial-terms) and [privacy policy](https://www.anthropic.com/legal/privacy).
* Gemini: [API terms](https://ai.google.dev/gemini-api/terms) and [Google privacy policy](https://policies.google.com/privacy).
* OpenRouter: [terms](https://openrouter.ai/terms) and [privacy policy](https://openrouter.ai/privacy). OpenRouter can route requests to another model provider; review the provider selected in your account as well.

For Ollama or an OpenAI-compatible endpoint, requests go to the server URL you configure. Review that server operator's terms and privacy policy. The plugin sends requests to the configured address; its operator determines any onward processing. The information sent and the actions that trigger a request are described above.

== Installation ==

1. Upload the plugin through `Plugins > Add New > Upload Plugin`, or copy it to `wp-content/plugins/`.
2. Activate 404ops Docstore through the `Plugins` screen.
3. Go to `404ops > DocStore`, create a department, and upload documents from the Documents screen. Nothing else needs setting up: documents are stored on your site.
4. Optional: to keep a department's documents in your own self-hosted DocStore API instead, enter its URL under Settings and the department's API key on its Edit screen.

Every 404ops plugin shares the single `404ops` item in the sidebar. DocStore's own screens - Departments, Add New, Users, Settings, Documents, Search, API Monitor and the Audit Log - are reached from the navigation row at the top of each DocStore screen, not from the sidebar.

== Frequently Asked Questions ==

= Who can see a document? =
Access is decided per department and per action (view, upload, edit, delete). A user may act on a department's documents when any of these holds:

* they are an administrator (`manage_options`);
* they hold a DocStore role (Manager, Editor, Contributor, Viewer), which applies to every department;
* the grant for that action is recorded on their profile for that department, or under General Permissions for every department;
* they are assigned to the department on the Users screen, as a viewer (view) or a manager (everything).

The Documents screen offers a user only the departments they may view and lets them upload only to those they may upload to. Front-end search and suggestions answer only for a department the signed-in user may view; a visitor who is not signed in gets nothing. Downloads are checked the same way: a download link is signed for one document and one department, and works only for a signed-in user who may view that department. For a department on the optional remote DocStore API, the plugin sends a document, a search or a delete with the department's own key, never with anything about the user, so nothing about who asked leaves your site.

= What happened to the [docstore_documents] and [docstore_browser] shortcodes? =

They are withdrawn and now display nothing. They listed WordPress posts of a document post type that this plugin never actually created, and they did not check department access. Your documents are stored in DocStore's own storage, not as WordPress posts, and nothing about them has changed. A page that still contains either shortcode shows the rest of its content as before, without the shortcode text; you can remove the shortcode whenever convenient. To let signed-in users find documents they are allowed to open, use `[docstore_search]`.

= Does this plugin require an external service? =

No. Documents are stored, listed, downloaded and searched on your own site. A self-hosted DocStore API is an optional connector: when you enter its URL under Settings, a department that has its own API key keeps its documents there, and every other department keeps using the site's own storage. There is no 404ops-operated endpoint and the plugin ships with no default address.

For a department on the connector, document contents, filenames, metadata, and search queries are transmitted from your site to that address, authenticated with an `X-API-Key` header. Because you choose the address, the terms and privacy policy that apply are those of whoever operates that service - your own, if you host it yourself. Use an `https://` URL so this traffic is encrypted in transit. The API Monitor screen shows call volume, performance, and rate-limit status for that connection.

= Where are my documents stored, and who can download them? =

Each document is a row in the plugin's own database table and a file in `wp-content/uploads/ops404-docstore-library/`, one folder per department. The files have random 32-character names with no extension, and the folder carries deny rules for Apache and IIS plus an empty index page in every folder, so they cannot be fetched or listed from the web. A document leaves your site only through a download link from the Documents screen, search or the REST API: the link is signed for that one document and department, works only for a signed-in user who may view that department, and is always sent as a download, never displayed as a page of your site. Every download is written to the audit log.

A department can instead keep its new documents in an S3-compatible bucket you configure (Settings > Storage, then the department's Edit screen); the database row stays on your site and downloads still go through this site's access check. The Move button on the department's Edit screen copies existing documents across, checks each copy against its checksum, then removes the original. Retained older versions stay on your site. A department can also have a storage quota, and its documents can be filed in folders.

Deleting a document deletes its file. Deleting a department deletes its documents. The library folder and table are removed when the plugin is deleted only if "Remove all plugin data when deleted" is set.

= What file types can I upload? =

By default DocStore accepts PDF; Word (.doc, .docx), Excel (.xls, .xlsx) and PowerPoint (.ppt, .pptx) in both their legacy and modern formats; OpenDocument Text, Spreadsheet and Presentation (.odt, .ods, .odp); RTF; CSV; plain text; Markdown; and PNG, JPEG, GIF and WebP images. An administrator can narrow this list further on Settings > Uploads.

Archives (zip, 7z, rar, tar, gz), SVG, HTML, XML, JavaScript, and any executable or script file are never accepted, no matter how Settings is configured. Every upload is also checked against its actual file content, not just its extension - a file whose bytes do not match the type it claims to be is refused and named as the type it was actually detected as.

= How does document search work? =

The DocStore > Search screen searches the text of your documents from an index kept in your own WordPress database (MySQL/MariaDB full-text search on InnoDB), not through the DocStore API. A document is indexed when it is uploaded, replaced or restored, and removed from the index when it is deleted; documents from a batch upload are indexed as they are stored (for a department on the remote connector, about a minute after the batch). Administrators can rebuild the whole index from the same screen - do this once after upgrading, so documents uploaded before this version are included. Rebuilding reads each document back from where it is stored: your site, or for a department on the optional remote connector, your DocStore API.

Search only ever covers the departments you may view: a document you could not open is never listed, counted or quoted, and expired documents are left out.

Text is read, in pure PHP and on your own server, from PDF (including PDFs that open without a password but restrict printing), Word, Excel and PowerPoint in both their modern (.docx, .xlsx, .pptx) and 97-2003 (.doc, .xls, .ppt) formats, OpenDocument, RTF, CSV, plain text and Markdown. Scanned PDFs and text inside images need OCR, which is not done - those documents are findable by their title and filename, and the Search screen shows how many there are. Password-protected files, and files that expand past safe size limits, are refused rather than read.

This is keyword search. Semantic (meaning-based) search is not part of it yet.

= Can documents expire automatically? =

Yes. Set an expiry date on a document from the Documents screen (the same "edit" permission that lets you upload governs this) and choose what happens once it passes: Flag or Archive. A daily check marks a document past its date as Expired - it stays on the Documents list with an Expired chip, but drops out of search results by default.

Archive does not delete anything. Deleting is permanent, and doing that from an unattended daily check is not a risk this plugin takes with your documents. Archive is recorded as a deliberate retirement rather than a missed date, in the document's list chip and its audit trail entry, but its effect today is the same as Flag: expired and hidden from default search, never deleted.

Every expiry set, cleared, or acted on by the daily check is written to the audit log. The dashboard also shows an "Expiring Soon" widget listing documents expiring within 7 days, scoped to the departments you can already reach.

= What happens when I re-upload a document? =

The Documents screen now has a Versions action (the same "edit" permission that governs upload). Uploading a new version keeps a copy of the document that is current right now - its file and its metadata - before the new file replaces it, so the previous version is always retained first. Every retained version is listed with its upload date, who uploaded it, its size, and a one-click Restore action; restoring promotes that version's file back as the document's current content through the same path a fresh upload takes, and keeps the content it replaced as a new version of its own - restore adds history, it never destroys it.

The 10 most recent versions are kept per document (the cap exists because retained versions live in your uploads directory: ten copies is enough to undo any recent mistake without one large PDF's history becoming half a gigabyte of disk). When the cap is exceeded the oldest retained version is dropped, file and row together. Every version added or restored is written to the audit log, and the retained files are removed with the plugin's other data only when the "Remove all plugin data when deleted" opt-in is set.

Each new version is stored as a new document id and the superseded copy is deleted once the previous content is safely retained. The plugin keeps a stable identity for the versioned document (the id it had when its history began) and tracks whichever id currently serves its content, so the Documents screen, the version list and restore keep addressing the same document across every change.

= Which IP address does DocStore use for rate limits and the audit log? =

The address of the connection that reached your site. Headers such as X-Forwarded-For and Client-IP can be set by anyone, so DocStore ignores them: otherwise a visitor could dodge a rate limit or pose as a whitelisted address by sending one. If your site is behind a proxy or CDN that sets a single header with the real visitor address, name that header from a small plugin or your theme: `add_filter( 'ops404_docstore_trusted_proxy_header', function () { return 'CF-Connecting-IP'; } );` (other common choices are `X-Forwarded-For` and `X-Real-IP`; for a list of addresses the last one is used). Only do this when all traffic reaches the site through that proxy and the proxy overwrites the header. Until you do, a site behind a proxy sees every visitor as the proxy's address.

= Where can I get help? =
Visit https://supportminer.404ops.com to open a support request.

== WP-CLI and REST ==

Department creation, user-department assignment, documents and API-key rotation are also reachable from the command line and from a small REST surface, for deploy scripts and other tooling. Both are thin wrappers over the same department, document and access-control code the admin screens use; neither adds a way to do anything the admin screens cannot already do.

**WP-CLI**

* `wp docstore department list [--format=<table|csv|json|yaml|ids|count>]` - list departments (never includes the API key).
* `wp docstore department create <name> [--description=<description>]` - create a department.
* `wp docstore department delete <id> [--yes]` - delete a department; refuses one with assigned users.
* `wp docstore user assign <user> <department> --role=<viewer|manager>` - assign a user to a department. `<user>` and `<department>` each accept an ID, or a login/email and a slug respectively.
* `wp docstore user unassign <user> <department>` - remove a user's department assignment.
* `wp docstore api-key rotate [--yes]` - replace the site's configured DocStore API key with a new one read from STDIN. Prints only a fingerprint of the new key; the key itself is never printed or logged.
* `wp docstore document list --department=<id> [--format=<table|csv|json|yaml|ids|count>]` - list a department's documents.

**REST API** (namespace `ops404-docstore/v1`)

* `GET /wp-json/ops404-docstore/v1/departments` - list the departments the current user may view.
* `POST /wp-json/ops404-docstore/v1/departments` - create a department. Requires `manage_options`.
* `DELETE /wp-json/ops404-docstore/v1/departments/<id>` - delete a department. Requires `manage_options`.
* `POST /wp-json/ops404-docstore/v1/departments/<id>/users` - assign a user to a department (`user_id`, `role`).
* `DELETE /wp-json/ops404-docstore/v1/departments/<id>/users` - remove a user's department assignment (`user_id`).
* `GET /wp-json/ops404-docstore/v1/departments/<id>/documents` - list a department's documents.
* `POST /wp-json/ops404-docstore/v1/departments/<id>/documents` - upload a document (multipart, field `file`, optional `title`). Requires the upload permission; the same file checks as the Documents screen.
* `GET /wp-json/ops404-docstore/v1/departments/<id>/documents/<document>` - one document's details, with a signed download link.
* `GET /wp-json/ops404-docstore/v1/departments/<id>/documents/<document>/download` - the file itself.
* `DELETE /wp-json/ops404-docstore/v1/departments/<id>/documents/<document>` - delete a document. Requires the delete permission.

Every route asks the same per-department, per-action gate the Documents screen uses (see "Who can see a document?" above); no response ever includes a department's API key.

== Screenshots ==

1. Documents, organized by department.
2. Search: full-text search index plus optional AI semantic search and document Q&A with your own provider.
3. Audit log with event, severity, user and date filters and CSV export.

== Changelog ==

= 1.10.9 =
* Fixed: report analytics table-clear failures and expiry selection errors without claiming successful work.

= 1.10.8 =
* Fixed: clear only DocStore cache entries; reject invalid expiry dates and report failed expiry writes. Match literal database names during schema checks.

= 1.10.7 =
* Keep recent release notes in the WordPress.org readme; the full history remains in CHANGELOG.md.


= 1.10.6 =
* Encrypt site-wide API keys on Settings/CLI saves and keep department credentials out of public metadata and authenticate stored credentials with private WordPress configuration keys.
* Preserve unreadable credentials for explicit administrator re-entry; refuse unsafe saves without substituting local storage.
* Remove obsolete automatic credential migration and keep user pagination positive and bounded.

= 1.10.5 =
* Updated: bundled shared AI client 0.4.3 with hardened connection nonce handling.
* Version and audit retention settings are now included in Free. Removing the Pro add-on does not shorten these choices.

= 1.10.4 =
* Added: guarded read-only administrative status interfaces and five bundled draft language catalogs.
* Improved: development test-session and catalog packaging checks.

= 1.10.3 =
* Maintenance: prefixed internal template variables to clear Plugin Check naming warnings.

= 1.10.2 =
* Fixed: rate limits, the IP whitelist and the audit log no longer trust an X-Forwarded-For or Client-IP header sent by the visitor; see the FAQ for sites behind a proxy.
* Fixed: search suggestions always failed their security check; they now work for people who may view the department.
* Fixed: cached search and document lists were never refreshed after a change, and editing a department inline could fail with a server error.
* Fixed: malformed posted permissions no longer cause an error, and backslashes in typed text are kept.

= 1.10.1 =
* Updated the licence client (0.3.5): Pro keeps working after a licence expires.

= 1.10.0 =
* New: PDF text is now read natively (pure PHP, on your server), alongside Word, Excel and PowerPoint in both modern and 97-2003 formats, and feeds keyword and semantic search. Scanned PDFs still need OCR, which is not done.
* New: folders inside a department (up to 8 levels), with move, rename and delete-when-empty.
* New: a storage quota per department.
* New: S3-compatible storage (Settings > Storage): choose it per department and move existing documents with the Move button on the department's Edit screen. The Pro add-on adds Google Drive, Dropbox and OneDrive.
* Fixed: layout and behaviour of every admin screen on WordPress 7.0 (pop-ups at the foot of the page, the Settings cards, delete dialogs, phone widths), the View button, Quick Edit and bulk delete, and upload progress.
* Changed: settings that did nothing (OCR, chunk size, debug mode) are removed; maximum upload size, log level, API retries and the search defaults now take effect.

Earlier versions: see CHANGELOG.md in the plugin folder.

== Upgrade Notice ==

= 1.10.6 =
Credential security: configure private AUTH_KEY and SECURE_AUTH_KEY values. Re-enter any unreadable department, S3 or cloud credentials; stored values are preserved without automatic migration.

= 1.10.5 =
Configure version and audit retention in Settings → Advanced, with or without Pro.

= 1.10.4 =
Includes checked draft translations and administrative status reporting. Human linguistic review is separate.

= 1.10.3 =
Maintenance update for internal template variable names. No changes to document handling or access permissions.

= 1.10.2 =
Rate limits, the IP whitelist and the audit log now use the address of the connection, not a header the visitor sends. If your site is behind a proxy or CDN, see the FAQ to name its header.

= 1.10.0 =
Adds native PDF indexing, folders, department quotas and S3-compatible storage, and fixes the layout of every admin screen. A database upgrade (new columns and a folders table) runs on the first request. Safe to update.

= 1.9.1 =
Readme-only update. No code change.

= 1.9.0 =
DocStore now stores documents on your own site and needs no external service. A configured DocStore API keeps serving departments that have their own API key. Safe to update.

= 1.8.2 =
Listing-only update: new screenshots and captions. No code change.

= 1.7.4 =
Listing and disclosure text only. No change to what the plugin does.

= 1.7.3 =
Bundled libraries updated. Safe to update.

= 1.7.2 =
Maintenance release: requires WordPress 7.0 or newer. Safe to update.

= 1.7.1 =
Fixes dead links in the empty Documents screen and the dashboard widget, and requires WordPress 6.9 or newer. Safe to update.

= 1.7.0 =
Fixes WordPress 6.9 deprecation notices on the Edit Department page and bundles its own prefixed copy of the 404ops UI kit. Safe to update.

= 1.6.2 =
Cleans up leftover expiry dates and version files when documents or departments are deleted. Recommended.

= 1.6.1 =
Fixes document expiry dates being lost on replace. Recommended.

= 1.6.0 =
Adds DocStore tools for AI agents through Agent Gate; every change still needs approval. Safe to update.

= 1.5.1 =
Maintenance release: AI features use a private copy of the AI client; re-enter your AI connection once. Safe to update.

= 1.5.0 =
AI features switch to a private AI client copy and the new shared AI connection settings. Re-enter your AI connection once after updating.

= 1.4.1 =
Enables semantic search with the updated AI client. Safe to update.

= 1.4.0 =
Adds optional AI document Q&A and semantic-search groundwork, using your own AI provider. Off until enabled. Safe to update.

= 1.3.1 =
Removes unused code; no change to stored documents. Safe to update.

= 1.3.0 =
Makes departments, settings saving and scheduled tasks work, and tightens CORS. The first analytics cleanup removes data older than your retention setting (90 days by default) - raise it first if needed.

= 1.2.1 =
Fixes document versions and search indexing, and creates missing database tables on update. Recommended for all sites.

= 1.2.0 =
Adds full-text document search and fixes an admin access error. Safe to update.

= 1.1.0 =
New submission and version-history features. No action needed on upgrade; existing documents are untouched until their next re-upload, which creates the first retained version.


= 1.0.4 =
Removes placeholder document data and corrects the documentation. The API URL default is now empty: if you relied on the previous `host.docker.internal` default, set the URL under DocStore > Settings.

= 1.0.3 =
Submission-readiness release. No functional changes to existing features.
