=== EffortLess Opcode and Object Cache ===
Contributors: domclic
Donate link: https://id7.dev/donate/
Tags: opcache, object cache, redis, memcached, apcu
Requires at least: 6.0
Tested up to: 7.1
Stable tag: 1.0.10
Requires PHP: 7.4
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Shows whether PHP OPcache and a persistent object cache are active, and installs an object cache drop-in for Redis, Memcached, APCu or files.

== Description ==

WordPress Site Health reports two performance items: "Opcode cache is not enabled" and "You should use a persistent object cache". This plugin reports the state of both and, where the server allows it, changes it.

**OPcache** keeps compiled PHP code in memory. It is a setting of the PHP installation, so a plugin cannot install it. The plugin shows whether the extension is loaded, whether `opcache.enable` is on, the main OPcache settings and, when enabled, memory use, number of cached scripts and hit rate. If the extension is loaded but switched off and PHP runs as CGI or FastCGI/FPM, the plugin can add `opcache.enable=0` to the `.user.ini` file in the WordPress folder, between marker lines, leaving other content of that file as it is. PHP does not allow a `.user.ini` file to switch OPcache on after the server started with it off, so the plugin shows the lines to put in `php.ini` or the host's PHP settings instead.

**Persistent object cache.** WordPress core caches database results only during one request. With a drop-in file, `wp-content/object-cache.php`, the results are stored in Redis, Memcached, APCu or in files, and reused by later requests. The plugin writes that file from a template with your settings, and removes it again on request or when the plugin is deactivated. The drop-in implements the WordPress cache functions, including `wp_cache_get_multiple()`, `wp_cache_flush_group()` and the other multiple-key functions.

How the cache behaves:

* Entries are stored under a key made of a random per-installation salt, a version token, the group, the site ID (except for global groups) and the key.
* Flushing the whole cache or one group changes a version token. Nothing is scanned or deleted on the server; old entries are no longer read and expire.
* Entries saved without an expiry get a maximum age (default 7 days), so old data does not stay on the server for ever.
* Non-persistent groups registered by WordPress stay in memory for the request only.
* If the server cannot be reached, or the PHP extension is missing, the cache keeps working for the current request only. The status page then shows the error.
* `incr` and `decr` read, change and write the value; they are not atomic between simultaneous requests.

= Tabs and settings =

The page has one tab per cache. A green dot on a tab marks the cache that is active. A cache is "installed" when its PHP extension is loaded (Files needs no extension). Activate is only offered for installed caches. Only one object cache backend can be active at a time, because WordPress loads a single `wp-content/object-cache.php`; activating another backend replaces the drop-in.

* **OPcache tab** - status and settings of OPcache. If the extension is loaded and PHP runs as CGI or FastCGI/FPM, **Deactivate OPcache** writes `opcache.enable=0` to `.user.ini` in the WordPress folder, between marker lines; **Remove the plugin's line** takes the lines out again. If the extension is not loaded the tab explains that only the host can install it.
* **Redis tab** - host and port (a host name, an address, `tls://host`, or the path of a Unix socket, in which case the port is ignored; default `127.0.0.1` and `6379`), database 0 to 255 (default 0), and an optional password. The password field is always empty when the page loads; leaving it empty keeps the stored password, and a checkbox removes it. The password is stored in the plugin settings and written into `wp-content/object-cache.php`, because the drop-in loads before the database is available.
* **Memcached tab** - host and port (default `127.0.0.1` and `11211`).
* **APCu tab** - no settings. APCu memory belongs to one web server pool and is not shared between servers.
* **Files tab** - needs no PHP extension. Each entry is one file in `wp-content/cache/elooc-<salt>/`. The files start with a PHP exit statement, and the folder has an `index.php` and an `.htaccess`. The files and folders can be read by the PHP user only. Expired files are removed gradually: about every five minutes one request spends up to a fifth of a second cleaning the next sub-folders, and a flush moves the old files aside to be deleted the same way. Reading a file is slower than reading memory, so this helps mainly when database queries are slow (for example a remote or busy database) and the disk is fast; on a host with a fast local database the gain can be small. It does make WordPress report a persistent object cache.
* **Maximum age of an entry (days)** - on every backend tab, 1 to 30, default 7. Shared by all backends.

Buttons on a backend tab: **Activate** (tests the server with the tab's settings, then saves them and writes the drop-in; reads **Save and update** when the backend is already active; settings that fail the test are not saved), **Save and test the connection** (stores and reads back a value, writes no file, and saves the settings only if the test works), **Flush the cache** and **Deactivate** (both only for the active backend; Deactivate deletes the drop-in).

= Where the page is =

* Single site: Tools > Opcode and Object Cache.
* Multisite: Network Admin > Settings > Opcode and Object Cache for super admins, who can change everything. Each site has a read-only copy under Tools. The drop-in and the cache are shared by the whole network; entries of each site are kept apart by the site ID.

== Installation ==

1. Upload the `effortless-opcode-and-object-cache` folder to `/wp-content/plugins/`, or install the zip from Plugins > Add New > Upload Plugin.
2. Activate the plugin. On Multisite, network-activate it.
3. Open the page (see "Where the page is").
4. OPcache tab: read the status. If it is not enabled, follow the instructions shown: switching OPcache on is done in `php.ini` or at the host, not by the plugin.
5. For the object cache: make sure a Redis or Memcached server is running and the matching PHP extension (`redis` or `memcached`) is loaded, or that APCu is enabled; with none of them, choose Files. Open the tab of the backend, enter the server details if any, and click "Save and test the connection".
6. When the test succeeds, click "Activate". The cache is used from the next page load, and Site Health should stop reporting the missing persistent object cache.

== Frequently Asked Questions ==

= I configured it but nothing happens. =

* The drop-in is used from the next page load after installing it.
* "Drop-in loaded but the cache server is not reachable" means the server did not answer; the page shows the last error. Check host, port, password and that the PHP extension is loaded.
* If another plugin or the host installed `wp-content/object-cache.php`, this plugin leaves it alone and says so. Remove that file first, or use the other cache.
* APCu is often disabled for the command line (`apc.enable_cli`) and enabled for the web server; the test runs inside the web request, so it reflects the web server.
* `.user.ini` is read by PHP about every five minutes (`user_ini.cache_ttl`). Some hosts lock `opcache.enable`; then the line has no effect.

= Why can the plugin not just turn OPcache on? =

OPcache is loaded when PHP starts. A plugin runs inside PHP after that and cannot load an extension. Through `.user.ini` it can only switch `opcache.enable` off: PHP refuses to switch it on after the server started with it off.

= Does it work with page caching plugins? =

An object cache and a page cache are separate layers and can be used together.

= What happens when I deactivate the plugin? =

The drop-in it wrote is deleted, so WordPress goes back to its per-request cache. A drop-in written by something else is never deleted.

= Does it change the site's data? =

No. The cache holds copies of data. Flushing it only makes WordPress read the database again.

= Is the cache shared between several sites on one Redis server? =

Keys start with a random salt created for this installation, so two installations do not read each other's entries even in the same Redis database.

== Notes and limitations ==

* The drop-in is a PHP file in `wp-content`; PHP must be able to write to that folder to install or update it. If it cannot, the plugin shows an error and writes nothing.
* The Redis, Memcached and APCu backends need their PHP extensions. The plugin does not install them. The Files backend needs only a writable `wp-content` folder.
* OPcache cannot be installed by a plugin. If the status page says the extension is not loaded, the host has to enable it.
* Memcached and APCu limit the size of a stored value; very large values may be refused by the server and are then read from the database again.
* APCu memory is per web server pool and is not shared between servers.
* The settings are network settings on Multisite.
* Changing the backend or the server settings and clicking install rewrites the drop-in; entries in the old server are not removed and expire by themselves.
* OPcache can be switched off through `.user.ini` when the extension is loaded and PHP runs as CGI or FastCGI/FPM. Switching it on needs `php.ini` or the host.
* Activating a cache, or changing which server it uses, gives it new keys, so entries from an earlier activation are never read again. Saving only a different maximum age keeps the keys.
* If the cache server cannot be reached, or an operation on it fails, the request carries on without it and leaves a marker file in `wp-content/cache`. The next request that reaches the server flushes the cache first, so a change made during the outage cannot leave an old entry behind. After the server fails, the plugin does not try it again for 30 seconds, so a down server does not slow down every page. The same marker is used when WP-CLI changes content while APCu is the backend, because the command line has its own APCu memory.
* A flush or a flushed group leaves the old entries on a Redis or Memcached server until they expire, up to the maximum age. For Redis, use a dedicated database or set `maxmemory-policy` to `volatile-lru` or `allkeys-lru`, so the old entries are evicted when memory runs short; a write that Redis refuses for lack of memory is skipped without switching the cache off. Memcached and APCu evict the oldest entries on their own.
* Cached values are signed with a secret kept in `wp-content/object-cache.php` (readable by the PHP user only). The signature covers the key and the expiry time, so a value written or copied into the cache server by somebody else, or one that has run out, is treated as a miss.
* Deactivating the cache, or deleting the plugin, removes the cache folder of the file backend; deleting the plugin also removes the plugin's lines from `.user.ini`.

== External services ==

The plugin connects only to the Redis or Memcached server that you enter on its settings page, from your own web server. No data is sent to a third party. The "Support the development" notice contains a link to https://id7.dev/donate/ that opens only when you click it.

== Changelog ==

= 1.0.10 =
* The short description is within the 150 characters the directory shows.
* The bundled translation files and the code that loaded them are removed; translations come from translate.wordpress.org.

= 1.0.9 =
* Cached values are serialized with WordPress's `maybe_serialize()` and `maybe_unserialize()`, wrapped in an array so that integers, objects and false keep their type.
* The file backend adds a key under a lock file instead of a hard link, and `add()` reports false when another request is adding the same key or the server refuses it.
* The settings form is read field by field, and OPcache functions are called only when `opcache.restrict_api` allows it, instead of silencing their warnings.
* `object-cache.php` and `.user.ini` are written to a temporary file that is moved into place with WordPress's filesystem class.
* The donate notice class is in `class-elooc-donate-notice.php`.

= 1.0.8 =
* The list of separately flushed groups is encoded with `wp_json_encode()`.

= 1.0.7 =
* The object cache drop-in is kept as one file per class in the plugin's `dropin` folder and joined into `wp-content/object-cache.php` when it is written; the file written to `wp-content` has the same contents as before apart from the changes below.
* Cached payloads are decoded without suppressing PHP errors, because the signature is verified first, and file reads in the file backend go through the WordPress filesystem class or read only the entry header.

= 1.0.6 =
* The file backend and the marker files use WordPress's filesystem class (`WP_Filesystem_Direct`) for creating, writing, moving and deleting files instead of direct PHP calls, and the connection test of the Files backend writes its test file through the plugin's WP_Filesystem wrapper.

= 1.0.5 =
* An unserializable value or a refused write no longer switches the cache off for the rest of the request, so later deletes still reach the server.
* When the cache server cannot be reached, the next request that can reach it flushes the cache, so changes made during the outage cannot leave old entries behind. A server that failed is not retried for 30 seconds.
* Signatures cover the key and the expiry time, and are made with keyed BLAKE2b where the sodium extension exists and HMAC-SHA1 elsewhere, which costs a fraction of the previous HMAC-SHA256.
* All version tokens are read in one or two round trips instead of one per group. Deleting a key no longer downloads its value. Several keys are stored or deleted in one round trip on Redis (pipeline), Memcached and APCu.
* Redis and Memcached connections are persistent, the SELECT and PING calls that were not needed are gone, and Memcached no longer asks for its version on every request.
* Settings typed in a tab are stored only after the connection test works, so a mistyped host no longer reaches the live drop-in. Saving only a different maximum age no longer clears the cache.
* The drop-in is written readable by the PHP user only; the file backend creates its folders and files the same way, writes tokens atomically, replaces damaged entries, moves flushed files aside and cleans in short, bounded runs that read only the header of each file.
* `wp_cache_flush()` and `wp_cache_flush_group()` return false when the server did not accept the change, and the Flush button reports it.
* Result messages are kept in user meta instead of transients, so they are not lost when the cache is re-keyed.
* The admin check that the drop-in is up to date no longer creates a test file on every request, and retries a failed write only every five minutes.

= 1.0.4 =
* Activating a cache gives it new keys, so entries left on a cache server or in the cache folder by an earlier activation are not read again.
* A write that the cache server refuses (item too large, memory full) removes the older value instead of leaving it in place.
* `wp_cache_incr()` and `wp_cache_decr()` keep the time the entry has left instead of resetting it to the default age.
* `wp-content/object-cache.php` and `.user.ini` are replaced through a temporary file and a rename, and the drop-in is checked for PHP syntax errors before it is written.
* The OPcache tab no longer offers to switch OPcache on, because PHP does not allow `.user.ini` to do that; the value is read only from the plugin's own lines, including in files with Windows line endings.
* Cached values are signed with a secret, and a value that does not carry a valid signature is not unserialized.
* The file backend cleans a share of its folder every five minutes, and deactivating or deleting the plugin removes that folder; deleting the plugin also removes its lines from `.user.ini`.
* The donate notice finds the plugin page through WordPress's own screen IDs, so it also shows on sites in other languages.
* The drop-in is no longer compared with its template on every admin page load.

= 1.0.3 =
* Translation files (.pot, .po, .mo) for Spanish, Traditional Chinese, Korean, French, Japanese, German, Italian and Brazilian Portuguese are included in the `languages` folder.

= 1.0.2 =
* The page has one tab per cache: OPcache, Redis, Memcached, APCu and Files. Each tab shows whether the cache is installed and active, and has its own Activate and Deactivate buttons. A cache whose PHP extension is not loaded cannot be activated.
* OPcache can be switched on or off through `.user.ini` when the extension is loaded.
* Saving a tab no longer resets the settings of the other tabs.

= 1.0.1 =
* New backend "Files": entries are stored in `wp-content/cache`, so a persistent object cache can be used where no Redis, Memcached or APCu extension is available. "Detect" uses it when none of the other three works.

= 1.0.0 =
* First release: OPcache and object cache status, `.user.ini` helper for OPcache, and an object cache drop-in for Redis, Memcached and APCu.
