* This is used to define all esi related functions.
defined('WPINC') || exit();
private static $has_esi = false;
private static $_combine_ids = array();
private $esi_args = null;
private $_esi_preserve_list = array();
private $_nonce_actions = array( -1 => '' ); // val is cache control
const QS_ACTION = 'lsesi';
const COMBO = '__combo'; // ESI include combine='main' handler
const PARAM_ARGS = 'args';
const PARAM_INSTANCE = 'instance';
const PARAM_NAME = 'name';
const WIDGET_O_ESIENABLE = 'widget_esi_enable';
const WIDGET_O_TTL = 'widget_ttl';
* @since 4.0 Change to be after Vary init in hook 'after_setup_theme'
* Bypass ESI related funcs if disabled ESI to fix potential DIVI compatibility issue
if (Router::is_ajax() || !$this->cls('Router')->esi_enabled()) {
// Guest mode, don't need to use ESI
if (defined('LITESPEED_GUEST') && LITESPEED_GUEST) {
if (defined('LITESPEED_ESI_OFF')) {
// If page is not cacheable
if (defined('DONOTCACHEPAGE') && apply_filters('litespeed_const_DONOTCACHEPAGE', DONOTCACHEPAGE)) {
// Init ESI in `after_setup_theme` hook after detected if LITESPEED_DISABLE_ALL is ON or not
* Overwrite wp_create_nonce func
$this->_transform_nonce();
!defined('LITESPEED_ESI_INITED') && define('LITESPEED_ESI_INITED', true);
* Load delayed by hook to give the ability to bypass by LITESPEED_DISABLE_ALL const
* @since 4.0 Changed to private from public
private function _hooks() {
add_filter('template_include', array( $this, 'esi_template' ), 99999);
add_action('load-widgets.php', __NAMESPACE__ . '\Purge::purge_widget');
add_action('wp_update_comment_count', __NAMESPACE__ . '\Purge::purge_comment_widget');
if (!empty($_GET[self::QS_ACTION])) {
$this->_register_esi_actions();
* To use it, just change the original shortcode as below:
* old: [someshortcode aa='bb']
* new: [esi someshortcode aa='bb' cache='private,no-vary' ttl='600']
* 1. `cache` attribute is optional, default to 'public,no-vary'.
* 2. `ttl` attribute is optional, default is your public TTL setting.
* 3. `_ls_silence` attribute is optional, default is false.
* @since 2.8.1 Check is_admin for Elementor compatibility #726013
add_shortcode('esi', array( $this, 'shortcode' ));
* Take over all nonce calls and transform to ESI
private function _transform_nonce() {
// Load ESI nonces in conf
$nonces = $this->conf(Base::O_ESI_NONCE);
add_filter('litespeed_esi_nonces', array( $this->cls('Data'), 'load_esi_nonces' ));
if ($nonces = apply_filters('litespeed_esi_nonces', $nonces)) {
foreach ($nonces as $action) {
$this->nonce_action($action);
add_action('litespeed_nonce', array( $this, 'nonce_action' ));
* Register a new nonce action to convert it to ESI
public function nonce_action( $action ) {
// Split the Cache Control
$action = explode(' ', $action);
$control = !empty($action[1]) ? $action[1] : '';
$action = Utility::wildcard2regex($action);
if (array_key_exists($action, $this->_nonce_actions)) {
$this->_nonce_actions[$action] = $control;
// Debug2::debug('[ESI] Appended nonce action to nonce list [action] ' . $action);
* Check if an action is registered to replace ESI
public function is_nonce_action( $action ) {
// If GM not run yet, then ESI not init yet, then ESI nonce will not be allowed even nonce func replaced.
if (!defined('LITESPEED_ESI_INITED')) {
if (defined('LITESPEED_ESI_OFF')) {
foreach ($this->_nonce_actions as $k => $v) {
if (strpos($k, '*') !== false) {
if (preg_match('#' . $k . '#iU', $action)) {
} elseif ($k == $action) {
public function shortcode( $atts ) {
Debug2::debug('[ESI] ===shortcode wrong format', $atts);
return 'Wrong shortcode esi format';
$cache = 'public,no-vary';
if (!empty($atts['cache'])) {
if (!empty($atts['_ls_silence'])) {
do_action('litespeed_esi_shortcode-' . $atts[0]);
return $this->sub_esi_block('esi', 'esi-shortcode', $atts, $cache, $silence);
* Check if the requested page has esi elements. If so, return esi on
* @return string Esi On header if request has esi, empty string otherwise.
public static function has_esi() {
* Sets that the requested page has esi elements.
public static function set_has_esi() {
* Register all of the hooks related to the esi logic of the plugin.
* Specifically when the page IS an esi page.
private function _register_esi_actions() {
* For any plugin need to check if page is ESI, use `LSCACHE_IS_ESI` check after `init` hook
!defined('LSCACHE_IS_ESI') && define('LSCACHE_IS_ESI', $_GET[self::QS_ACTION]); // Reused this to ESI block ID
!empty($_SERVER['ESI_REFERER']) && defined('LSCWP_LOG') && Debug2::debug('[ESI] ESI_REFERER: ' . $_SERVER['ESI_REFERER']);
* Only when ESI's parent is not REST, replace REQUEST_URI to avoid breaking WP5 editor REST call
if (!empty($_SERVER['ESI_REFERER']) && !$this->cls('REST')->is_rest($_SERVER['ESI_REFERER'])) {
self::debug('overwrite REQUEST_URI to ESI_REFERER [from] ' . $_SERVER['REQUEST_URI'] . ' [to] ' . $_SERVER['ESI_REFERER']);
if (!empty($_SERVER['ESI_REFERER'])) {
$_SERVER['REQUEST_URI'] = $_SERVER['ESI_REFERER'];
if (substr(get_option('permalink_structure'), -1) === '/' && strpos($_SERVER['ESI_REFERER'], '?') === false) {
$_SERVER['REQUEST_URI'] = trailingslashit($_SERVER['ESI_REFERER']);
// Prevent from 301 redirecting
if (!empty($_SERVER['SCRIPT_URI'])) {
$SCRIPT_URI = parse_url($_SERVER['SCRIPT_URI']);
$SCRIPT_URI['path'] = $_SERVER['REQUEST_URI'];
Utility::compatibility();
$_SERVER['SCRIPT_URI'] = http_build_url($SCRIPT_URI);
if (!empty($_SERVER['ESI_CONTENT_TYPE']) && strpos($_SERVER['ESI_CONTENT_TYPE'], 'application/json') === 0) {
add_filter('litespeed_is_json', '__return_true');
* Make REST call be able to parse ESI
* NOTE: Not effective due to ESI req are all to `/` yet
add_action('rest_api_init', array( $this, 'load_esi_block' ), 101);
add_action('litespeed_esi_load-widget', array( $this, 'load_widget_block' ));
add_action('litespeed_esi_load-admin-bar', array( $this, 'load_admin_bar_block' ));
add_action('litespeed_esi_load-comment-form', array( $this, 'load_comment_form_block' ));
add_action('litespeed_esi_load-nonce', array( $this, 'load_nonce_block' ));
add_action('litespeed_esi_load-esi', array( $this, 'load_esi_shortcode' ));
add_action('litespeed_esi_load-' . self::COMBO, array( $this, 'load_combo' ));
* Hooked to the template_include action.
* Selects the esi template file when the post type is a LiteSpeed ESI page.
* @param string $template The template path filtered.
* @return string The new template path.
public function esi_template( $template ) {
// Check if is an ESI request
if (defined('LSCACHE_IS_ESI')) {
self::debug('calling ESI template');
return LSCWP_DIR . 'tpl/esi.tpl.php';
self::debug('calling default template');
$this->_register_not_esi_actions();
* Register all of the hooks related to the esi logic of the plugin.
* Specifically when the page is NOT an esi page.
private function _register_not_esi_actions() {
do_action('litespeed_tpl_normal');
if (!Control::is_cacheable()) {
add_filter('widget_display_callback', array( $this, 'sub_widget_block' ), 0, 3);
if (Router::is_logged_in()) {
remove_action('wp_body_open', 'wp_admin_bar_render', 0); // Remove default Admin bar. Fix https://github.com/elementor/elementor/issues/25198
remove_action('wp_footer', 'wp_admin_bar_render', 1000);
add_action('wp_footer', array( $this, 'sub_admin_bar_block' ), 1000);
// Add comment forum esi for logged-in user or commenter
if (!Router::is_ajax() && Vary::has_vary()) {
add_filter('comment_form_defaults', array( $this, 'register_comment_form_actions' ));
* Set an ESI to be combine='sub'
public static function combine( $block_id ) {
if (!isset($_SERVER['X-LSCACHE']) || strpos($_SERVER['X-LSCACHE'], 'combine') === false) {
if (in_array($block_id, self::$_combine_ids)) {
self::$_combine_ids[] = $block_id;
public function load_combo() {
Control::set_nocache('ESI combine request');
if (empty($_POST['esi_include'])) {
Debug2::debug('[ESI] 🍔 Load combo', $_POST['esi_include']);
foreach ($_POST['esi_include'] as $url) {
$qs = parse_url(htmlspecialchars_decode($url), PHP_URL_QUERY);
if (empty($qs[self::QS_ACTION])) {
$esi_id = $qs[self::QS_ACTION];
$esi_param = !empty($qs[self::QS_PARAMS]) ? $this->_parse_esi_param($qs[self::QS_PARAMS]) : false;
$inline_param = apply_filters('litespeed_esi_inline-' . $esi_id, array(), $esi_param); // Returned array need to be [ val, control, tag ]
$output .= self::_build_inline($url, $inline_param);
* Build a whole inline segment
private static function _build_inline( $url, $inline_param ) {
if (!$url || empty($inline_param['val']) || empty($inline_param['control']) || empty($inline_param['tag'])) {
$control = esc_attr($inline_param['control']);
$tag = esc_attr($inline_param['tag']);
return "<esi:inline name='$url' cache-control='" . $control . "' cache-tag='" . $tag . "'>" . $inline_param['val'] . '</esi:inline>';
* Build the esi url. This method will build the html comment wrapper as well as serialize and encode the parameter array.
* The block_id parameter should contain alphanumeric and '-_' only.
* @param string $block_id The id to use to display the correct esi block.
* @param string $wrapper The wrapper for the esi comments.
* @param array $params The esi parameters.
* @param string $control The cache control attribute if any.
* @param bool $silence If generate wrapper comment or not
* @param bool $preserved If this ESI block is used in any filter, need to temporarily convert it to a string to avoid the HTML tag being removed/filtered.
* @param bool $svar If store the value in memory or not, in memory will be faster
* @param array $inline_param If show the current value for current request( this can avoid multiple esi requests in first time cache generating process )
public function sub_esi_block(
$control = 'private,no-vary',
if (empty($block_id) || !is_array($params) || preg_match('/[^\w-]/', $block_id)) {
if (defined('LITESPEED_ESI_OFF')) {
Debug2::debug('[ESI] ESI OFF so force loading [block_id] ' . $block_id);
do_action('litespeed_esi_load-' . $block_id, $params);
// Don't add comment to esi block ( original for nonce used in tag property data-nonce='esi_block' )
$params['_ls_silence'] = true;
if ($this->cls('REST')->is_rest() || $this->cls('REST')->is_internal_rest()) {
$params = apply_filters('litespeed_esi_params', $params, $block_id);
$control = apply_filters('litespeed_esi_control', $control, $block_id);
if (!is_array($params) || !is_string($control)) {
defined('LSCWP_LOG') && Debug2::debug("[ESI] 🛑 Sub hooks returned Params: \n" . var_export($params, true) . "\ncache control: \n" . var_export($control, true));
$appended_params = array(
self::QS_ACTION => $block_id,
$appended_params['_control'] = $control;
$appended_params[self::QS_PARAMS] = base64_encode(\json_encode($params));
Debug2::debug2('[ESI] param ', $params);