JFIF $ d d 7 * Z qn )ZP 0 !1 A "#a$2Qr D8 a Ri [f \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H ~ , l s / 9 ć: [=/#f ; ) x { ٛE Q )~ = 𘙲r*2~ a _V = ' ku m F D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq 1dđ #̩ ͑ 0 ; H ] u 搂 @:~ ו K L N s h } O I R* 8 :2 ! lD JV o ( 3 = M ( z Ȱ+i *N A r6K n S l ) ! J J Ӂ* % ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c P A\IL Nj! J ۱+ O\ ͔ ] ޒ S J ȧ c%A N ol ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0 'G=i 2N +0 e 2 ]] 9 VT P O 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P < 0 x < !1AQ "Raq 02Br #S CTb ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV YT D I 6 2 '8Y2 7'\T P.6 d &˦ @V q i |8 -O Ε ] ʔ U= T L 8= ;6c | !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U#6w + +s &r+n ڐ { @ 29gL u " T Ù M=6 (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 ! OS r D 5 7 % | ?x> L | / nD 6?/8 w # [ ) L 7 +6〼T A T g ! %5 Mm Z /c -{1_Je "| ^$ 'O & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@ u6 BԒ i YN * f 0 _ GhKW u lT <nj- 0{ M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q $ H8o Q˼EV ~ k 0 h' L Pp M -M" m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @~p # !1QAa q ? AL0L x LU 4 d ; x " 16ad0 7.\ߋ 0 = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X &Q З non]я u ג./ ; gZ$ M QР 2M ]h ni 0 P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _ 1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3 6 #Ik+ v { v i ( ވ ? a e) X xy/*@Q Ǽ Ծ ) $ IWO l c G; !i k{ gOŀ L ('x T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ) X 5 c QɎMy W ? Q *!R > 6=7)Xj 5`J ] e 8%t ! + ' ! 1Q 5 !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $ v , ,m 㵜5u bV =sY+ @d { N ! dn O < .- B; _w J t 6;Q Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш e黅X ۢ F :)[ F G X ƹ / w _c MeD ,ʡc c . W D tA $ j@ : ) - #u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P 6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L ! ~ y5 g9T̅J kbM' +s :S +B) v @ M j e C f j E 0 Y\Qn z G 1 д~ W o{T 9?` Rm yhsy3 !HAD ] m c1 ~ 2 L S u7x T ;j$ `} 4-> L# vzŏ I L S ֭ T { r jGK C ; b pU= - ` Bs K. S F w4 M q] Z dH S 0 ) tLg
<?php
/**
* The avatar cache class.
*
* Caches remote (e.g., Gravatar) avatars locally and rewrites URLs
* to serve cached copies with a TTL. Supports on-demand generation
* during page render and batch generation via cron.
*
* @since 3.0
* @package LiteSpeed
*/
namespace LiteSpeed;
defined( 'WPINC' ) || exit();
/**
* Class Avatar
*/
class Avatar extends Base {
const TYPE_GENERATE = 'generate';
/**
* Avatar cache TTL (seconds).
*
* @var int
*/
private $_conf_cache_ttl;
/**
* Avatar DB table name.
*
* @var string
*/
private $_tb;
/**
* In-request map from original URL => rewritten URL to avoid duplicates.
*
* @var array<string,string>
*/
private $_avatar_realtime_gen_dict = [];
/**
* Init.
*
* @since 1.4
*/
public function __construct() {
$this->_tb = Data::cls()->tb( 'avatar' );
if ( ! $this->conf( self::O_DISCUSS_AVATAR_CACHE ) ) {
return;
}
self::debug2( '[Avatar] init' );
$this->_conf_cache_ttl = $this->conf( self::O_DISCUSS_AVATAR_CACHE_TTL );
add_filter( 'get_avatar_url', [ $this, 'crawl_avatar' ] );
$this->_summary = self::get_summary();
}
/**
* Check whether DB table is needed.
*
* @since 3.0
* @access public
* @return bool
*/
public function need_db() {
return (bool) $this->conf( self::O_DISCUSS_AVATAR_CACHE );
}
/**
* Serve static avatar by md5 (used by local static route).
*
* @since 3.0
* @access public
* @param string $md5 MD5 hash of original avatar URL.
* @return void
*/
public function serve_static( $md5 ) {
global $wpdb;
self::debug( '[Avatar] is avatar request' );
// No generation for any request when avatar cache is off — fall through to the regular WP 404, same as the no-matched-record path below.
if ( ! $this->conf( self::O_DISCUSS_AVATAR_CACHE ) ) {
self::debug( '[Avatar] bypassed serving as avatar cache is off' );
return;
}
if ( strlen( $md5 ) !== 32 ) {
self::debug( '[Avatar] wrong md5 ' . $md5 );
return;
}
$url = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
'SELECT url FROM `' . $this->_tb . '` WHERE md5 = %s', // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$md5
)
);
if ( ! $url ) {
self::debug( '[Avatar] no matched url for md5 ' . $md5 );
return;
}
$generated_url = $this->_generate( $url );
if ( $generated_url === $url ) {
self::debug( '[Avatar] generation failed; bypassing redirect' );
return;
}
wp_safe_redirect( $generated_url );
exit;
}
/**
* Localize/replace avatar URL with cached one (filter callback).
*
* @since 3.0
* @access public
* @param string $url Original avatar URL.
* @return string Rewritten/cached avatar URL (or original).
*/
public function crawl_avatar( $url ) {
if ( ! $url ) {
return $url;
}
// Check if already generated in this request.
if ( ! empty( $this->_avatar_realtime_gen_dict[ $url ] ) ) {
self::debug2( '[Avatar] already in dict [url] ' . $url );
return $this->_avatar_realtime_gen_dict[ $url ];
}
$realpath = $this->_realpath( $url );
$mtime = file_exists( $realpath ) ? filemtime( $realpath ) : false;
if ( $mtime && time() - (int) $mtime <= $this->_conf_cache_ttl ) {
self::debug2( '[Avatar] cache file exists [url] ' . $url );
return $this->_rewrite( $url, $mtime );
}
// Only handle gravatar or known remote avatar providers; keep generic check for "gravatar.com".
if ( strpos( $url, 'gravatar.com' ) === false ) {
return $url;
}
// Throttle generation.
if ( ! empty( $this->_summary['curr_request'] ) && time() - (int) $this->_summary['curr_request'] < 300 ) {
self::debug2( '[Avatar] Bypass generating due to interval limit [url] ' . $url );
return $url;
}
// Generate immediately and track for this request.
$this->_avatar_realtime_gen_dict[ $url ] = $this->_generate( $url );
return $this->_avatar_realtime_gen_dict[ $url ];
}
/**
* Count queued avatars (expired ones) for cron.
*
* @since 3.0
* @access public
* @return int|false
*/
public function queue_count() {
global $wpdb;
// Avatar cache option is the module-level switch: no queue and no table creation side effect when off.
if ( ! $this->conf( self::O_DISCUSS_AVATAR_CACHE ) ) {
return 0;
}
if ( ! Data::cls()->tb_exist( 'avatar' ) ) {
Data::cls()->tb_create( 'avatar' );
}
$cnt = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
'SELECT COUNT(*) FROM `' . $this->_tb . '` WHERE dateline < %d', // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
time() - $this->_conf_cache_ttl
)
);
return (int) $cnt;
}
/**
* Build final local URL for cached avatar.
*
* @since 3.0
* @param string $url Original URL.
* @param int|null $time Optional filemtime for cache busting.
* @return string Local URL.
*/
private function _rewrite( $url, $time = null ) {
$qs = $time ? '?ver=' . $time : '';
return LITESPEED_STATIC_URL . '/avatar/' . $this->_filepath( $url ) . $qs;
}
/**
* Generate filesystem realpath for cache file.
*
* @since 3.0
* @access private
* @param string $url Original URL.
* @return string Absolute filesystem path.
*/
private function _realpath( $url ) {
return LITESPEED_STATIC_DIR . '/avatar/' . $this->_filepath( $url );
}
/**
* Get relative filepath for cached avatar.
*
* @since 4.0
* @param string $url Original URL.
* @return string Relative path under avatar/ (may include blog id).
*/
private function _filepath( $url ) {
$filename = md5( $url ) . '.jpg';
if ( is_multisite() ) {
$filename = get_current_blog_id() . '/' . $filename;
}
return $filename;
}
/**
* Cron generation for expired avatars.
*
* @since 3.0
* @access public
* @param bool $force Bypass throttle.
* @return void
*/
public static function cron( $force = false ) {
global $wpdb;
$_instance = self::cls();
if ( ! $_instance->conf( self::O_DISCUSS_AVATAR_CACHE ) ) {
self::debug( '[Avatar] bypassed cron as avatar cache is off' );
return;
}
if ( ! $_instance->queue_count() ) {
self::debug( '[Avatar] no queue' );
return;
}
// For cron, need to check request interval too.
if ( ! $force ) {
if ( ! empty( $_instance->_summary['curr_request'] ) && time() - (int) $_instance->_summary['curr_request'] < 300 ) {
self::debug( '[Avatar] curr_request too close' );
return;
}
}
$list = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
'SELECT url FROM `' . $_instance->_tb . '` WHERE dateline < %d ORDER BY id DESC LIMIT %d', // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
time() - $_instance->_conf_cache_ttl,
(int) apply_filters( 'litespeed_avatar_limit', 30 )
)
);
self::debug( '[Avatar] cron job [count] ' . ( $list ? count( $list ) : 0 ) );
if ( $list ) {
foreach ( $list as $v ) {
self::debug( '[Avatar] cron job [url] ' . $v->url );
$_instance->_generate( $v->url );
}
}
}
/**
* Download and store the avatar locally, then update DB row.
*
* @since 3.0
* @access private
* @param string $url Original avatar URL.
* @return string Rewritten local URL (fallback to original on failure).
*/
private function _generate( $url ) {
global $wpdb;
$file = $this->_realpath( $url );
// Mark request start
self::save_summary(
[
'curr_request' => time(),
]
);
$temp = File::download( $url, $file, 180 );
self::debug( '[Avatar] _generate [url] ' . $url );
if ( is_wp_error( $temp ) ) {
self::debug( '[Avatar] failed to get: ' . $temp->get_error_code() );
return $url;
}
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
if ( false === @getimagesize( $temp ) || ! File::publish_temp_file( $temp, $file ) ) {
wp_delete_file( $temp );
self::debug( '[Avatar] failed to validate or save the image.' );
return $url;
}
// Save summary data
self::save_summary(
[
'last_spent' => time() - (int) $this->_summary['curr_request'],
'last_request' => $this->_summary['curr_request'],
'curr_request' => 0,
]
);
// Update/insert DB record
$md5 = md5( $url );
$existed = $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
'UPDATE `' . $this->_tb . '` SET dateline = %d WHERE md5 = %s', // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
time(),
$md5
)
);
if ( ! $existed ) {
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->prepare(
'INSERT INTO `' . $this->_tb . '` (url, md5, dateline) VALUES (%s, %s, %d)', // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$url,
$md5,
time()
)
);
}
self::debug( '[Avatar] saved avatar ' . $file );
return $this->_rewrite( $url );
}
/**
* Handle all request actions from main cls.
*
* @since 3.0
* @access public
* @return void
*/
public function handler() {
$type = Router::verify_type();
switch ( $type ) {
case self::TYPE_GENERATE:
self::cron( true );
break;
default:
break;
}
Admin::redirect();
}
}