* LiteSpeed persistent data manager.
* Handles DB tables, schema upgrades, URL-to-file mappings, and list loaders.
defined( 'WPINC' ) || exit();
* Data layer for LiteSpeed Cache.
class Data extends Root {
* Versioned DB updaters for network-wide options.
* @var array<string,array<string>>
'5.3-a5' => [ 'litespeed_update_5_3' ],
'7.0-b26' => [ 'litespeed_update_7' ],
'7.0.1-b1' => [ 'litespeed_update_7_0_1' ],
'7.7-b28' => [ 'litespeed_update_7_7' ],
* Versioned DB updaters for per-site options in multisite.
* @var array<string,array<string>>
private $_db_site_updater = [
// '2.0' => [ 'litespeed_update_site_2_0' ],
* Map from URL-file type to integer code.
private $_url_file_types = [
/** Table: image optimization results. */
const TB_IMG_OPTM = 'litespeed_img_optm';
/** Table: image optimization working queue. */
const TB_IMG_OPTMING = 'litespeed_img_optming';
/** Table: cached avatars. */
const TB_AVATAR = 'litespeed_avatar';
/** Table: crawler URLs. */
const TB_CRAWLER = 'litespeed_crawler';
/** Table: crawler blacklist. */
const TB_CRAWLER_BLACKLIST = 'litespeed_crawler_blacklist';
/** Table: logical URLs. */
const TB_URL = 'litespeed_url';
/** Table: URL → generated file mapping. */
const TB_URL_FILE = 'litespeed_url_file';
public function __construct() {}
* Ensure required tables exist based on current configuration.
* Called on activation and when options are (re)loaded.
public function correct_tb_existence() {
if ( $this->conf( Base::O_DISCUSS_AVATAR_CACHE ) ) {
$this->tb_create( 'avatar' );
if ( $this->conf( Base::O_CRAWLER ) ) {
$this->tb_create( 'crawler' );
$this->tb_create( 'crawler_blacklist' );
$this->tb_create( 'url' );
$this->tb_create( 'url_file' );
// Image optm tables are managed on-demand.
* Upgrade global configuration/data to match plugin version.
* @param string $ver Currently stored version string.
* @return string|void 'upgrade' on success, or void if no-op.
public function conf_upgrade( $ver ) {
// Skip count check if `Use Primary Site Configurations` is on (deprecated note kept intentionally).
if ( $this->_get_upgrade_lock() ) {
$this->_set_upgrade_lock( true );
require_once LSCWP_DIR . 'src/data.upgrade.func.php';
if ( $this->conf( Base::O_DEBUG ) ) {
$this->cls( 'Debug2' )->init();
foreach ( $this->_db_updater as $k => $v ) {
if ( version_compare( $ver, $k, '<' ) ) {
self::debug( "Updating [ori_v] $ver \t[to] $k \t[func] $v2" );
$this->cls( 'Conf' )->load_options();
$this->correct_tb_existence();
$this->cls( 'Activation' )->update_files();
// Update version to latest.
Conf::delete_option( Base::_VER );
Conf::add_option( Base::_VER, Core::VER );
self::debug( 'Updated version to ' . Core::VER );
$this->_set_upgrade_lock( false );
if ( ! defined( 'LSWCP_EMPTYCACHE' ) ) {
define( 'LSWCP_EMPTYCACHE', true );
* Upgrade per-site configuration/data to match plugin version (multisite).
* @param string $ver Currently stored version string.
public function conf_site_upgrade( $ver ) {
if ( $this->_get_upgrade_lock() ) {
$this->_set_upgrade_lock( true );
require_once LSCWP_DIR . 'src/data.upgrade.func.php';
foreach ( $this->_db_site_updater as $k => $v ) {
if ( version_compare( $ver, $k, '<' ) ) {
self::debug( "Updating site [ori_v] $ver \t[to] $k \t[func] $v2" );
$this->cls( 'Conf' )->load_site_options();
Conf::delete_site_option( Base::_VER );
Conf::add_site_option( Base::_VER, Core::VER );
self::debug( 'Updated site_version to ' . Core::VER );
$this->_set_upgrade_lock( false );
if ( ! defined( 'LSWCP_EMPTYCACHE' ) ) {
define( 'LSWCP_EMPTYCACHE', true );
* Whether an upgrade lock is in effect.
* @return int|false Timestamp if locked and recent, false otherwise.
private function _get_upgrade_lock() {
$is_upgrading = (int) get_option( 'litespeed.data.upgrading' );
$this->_set_upgrade_lock( false ); // Seed option to avoid repeated DB reads later.
if ( $is_upgrading && ( time() - $is_upgrading ) < 3600 ) {
* Show the upgrading banner if upgrade script is running.
public function check_upgrading_msg() {
$is_upgrading = $this->_get_upgrade_lock();
/* translators: %s: time string */
__( 'The database has been upgrading in the background since %s. This message will disappear once upgrade is complete.', 'litespeed-cache' ),
'<code>' . Utility::readable_time( $is_upgrading ) . '</code>'
* Set/clear the upgrade process lock.
* @param bool $lock True to set, false to clear.
private function _set_upgrade_lock( $lock ) {
update_option( 'litespeed.data.upgrading', -1 );
update_option( 'litespeed.data.upgrading', time() );
* Get a fully-qualified table name by slug.
* @param string $tb Table slug (e.g., 'url_file').
public function tb( $tb ) {
return $wpdb->prefix . self::TB_IMG_OPTM;
return $wpdb->prefix . self::TB_IMG_OPTMING;
return $wpdb->prefix . self::TB_AVATAR;
return $wpdb->prefix . self::TB_CRAWLER;
case 'crawler_blacklist':
return $wpdb->prefix . self::TB_CRAWLER_BLACKLIST;
return $wpdb->prefix . self::TB_URL;
return $wpdb->prefix . self::TB_URL_FILE;
* Check if a table exists.
* @param string $tb Table slug.
public function tb_exist( $tb ) {
$save_state = $wpdb->suppress_errors;
$wpdb->suppress_errors( true );
$describe = $wpdb->get_var( 'DESCRIBE `' . $this->tb( $tb ) . '`' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared
$wpdb->suppress_errors( $save_state );
return null !== $describe;
* Get the SQL structure (columns/indexes) for a given table slug.
* @param string $tb Table slug.
* @return string SQL columns/indexes definition.
private function _tb_structure( $tb ) {
return File::read( LSCWP_DIR . 'src/data_structure/' . $tb . '.sql' );
* Create a table by slug if it doesn't exist.
* @param string $tb Table slug.
public function tb_create( $tb ) {
self::debug2( '[Data] Checking table ' . $tb );
// Check if table exists first.
if ( $this->tb_exist( $tb ) ) {
self::debug2( '[Data] Existed' );
self::debug( 'Creating ' . $tb );
'CREATE TABLE IF NOT EXISTS `%1$s` (%2$s) %3$s;',
$this->_tb_structure( $tb ),
$wpdb->get_charset_collate()
$res = $wpdb->query( $sql ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared
self::debug( 'Warning! Creating table failed!', $sql );
Admin_Display::error( Error::msg( 'failed_tb_creation', [ '<code>' . $tb . '</code>', '<code>' . $sql . '</code>' ] ) );
* @param string $tb Table slug.
public function tb_del( $tb ) {
if ( ! $this->tb_exist( $tb ) ) {
self::debug( 'Deleting table ' . $tb );
$q = 'DROP TABLE IF EXISTS ' . $this->tb( $tb );
$wpdb->query( $q ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared
* Drop all generated tables (except image optimization working tables).
public function tables_del() {
$this->tb_del( 'avatar' );
$this->tb_del( 'crawler' );
$this->tb_del( 'crawler_blacklist' );
$this->tb_del( 'url_file' );
// Deleting img_optm only can be done when destroy all optm images
* TRUNCATE a table by slug.
* @param string $tb Table slug.
public function table_truncate( $tb ) {
$q = 'TRUNCATE TABLE ' . $this->tb( $tb );
$wpdb->query( $q ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared
* Clean URL-file rows for a given file type and prune orphaned URLs.
* @param string $file_type One of 'css','js','ccss','ucss'.
public function url_file_clean( $file_type ) {
if ( ! $this->tb_exist( 'url_file' ) ) {
if ( ! isset( $this->_url_file_types[ $file_type ] ) ) {
$type = $this->_url_file_types[ $file_type ];
$tb_url = $this->tb( 'url' );
$tb_url_file = $this->tb( 'url_file' );
// Delete all of this type.
$q = "DELETE FROM `$tb_url_file` WHERE `type` = %d";
$wpdb->query( $wpdb->prepare( $q, $type ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared
// Prune orphaned rows in URL table.
LEFT JOIN `{$tb_url_file}` AS f ON d.`id` = f.`url_id`
WHERE f.`url_id` IS NULL";
$wpdb->query( $sql ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared
* Persist (or rotate) the mapping from URL+vary to a generated file.
* @param string $request_url Full request URL.
* @param string $vary Vary string (may be long; will be md5 if >32).
* @param string $file_type One of 'css','js','ccss','ucss'.
* @param string $filecon_md5 MD5 of the generated file content.
* @param string $path Base path where files live.
* @param bool $mobile Whether mapping is for mobile.
* @param bool $webp Whether mapping is for webp.
public function save_url( $request_url, $vary, $file_type, $filecon_md5, $path, $mobile = false, $webp = false ) {
if ( strlen( $vary ) > 32 ) {
if ( ! isset( $this->_url_file_types[ $file_type ] ) ) {
$type = $this->_url_file_types[ $file_type ];
$tb_url = $this->tb( 'url' );
$tb_url_file = $this->tb( 'url_file' );
// Ensure URL row exists.
$q = "SELECT * FROM `$tb_url` WHERE url=%s";
$url_row = $wpdb->get_row( $wpdb->prepare( $q, $request_url ), ARRAY_A ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared
$q = "INSERT INTO `$tb_url` SET url=%s";
$wpdb->query( $wpdb->prepare( $q, $request_url ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared
$url_id = (int) $wpdb->insert_id;
$url_id = (int) $url_row['id'];