\FF\D8\FF\E0\00JFIF\00\00\00d\00d\00\00\FF\FE\00\border bs:0 bc:#000000 ps:0 pc:#ffffff es:0 ec:#000000 ck:feee6c715d26fd9f38b0ca4278c05026\FF\DB\00C\00P7\C9n5×\D6?\BDê\9Ds\EBp\9F[`8m\B7)o\B5\E8\E6I\99\FE3]]A2\BA\8Cw\D6E\93\\DEv\C8\009\F2\F1NI?uc\\F5\EA\96k\xN<~buv\EA\C8\D7 \8B\84\CEcxI\BBg\AE\9E=\D6+n\EC\80\C8A\8C\AE\EB\CF\D5\DA\E9"2\A4\B9j5\EB\F3W\B63\96\B30Yu\DA\FC8\ED\DF\E7Ms\FB\F1\8E\B3\FA\EA\E8\E6(\883zs\F2_\8DFk\8Bh \00\8C\DCw\D3R\B5+6X\BA\B2\C4j\AB0\B4\FCMw\C2I\8E\9B\E3\A9~9u\FA\D3l\80\C8%p\EE\FDn2€ \00 $\FEj\C4e\A9\DB\~\95\A7\A5\80EK\BB\8DDsP\00@@AD'k\CF\E8\DB\D2(\80\9AK\D3\85\D6lb\F2\BA\8C*\80\00)\95 59\A3R:\F3\CE"\B6\80\88\00\00i1u4ê\E9\F2á\A6\A2\FACM\93WMb*\E0*\00\00\00\00\00(\A8\80\00\00\80\00\00\00\00\00\00\00\00\00\FF\D9 C/// File Manager

File Manager

Path: /opt/cloudlinux/venv/lib/python3.11/site-packages/clwpos/user/

Viewing File: cache.py

import hashlib
import logging
import os
import pwd
from contextlib import contextmanager
from dataclasses import dataclass
from typing import ContextManager, Optional

from clwpos import constants, scoped_cache


def _get_cache_directory():
    user = pwd.getpwuid(os.geteuid())
    cache_dir = os.path.join(user.pw_dir, constants.USER_WPOS_DIR, '.cache')
    os.makedirs(cache_dir, exist_ok=True)

    return cache_dir


def _get_wp_config_modification_ts(wp_path):
    try:
        return os.path.getmtime(os.path.join(wp_path, 'wp-config.php'))
    except FileNotFoundError:
        return os.path.getmtime(os.path.join(wp_path, '../wp-config.php'))


@dataclass
class CacheRecord:
    # any data that we would like to save
    # important! do not use pickle or any other serializable
    # data format that might be loaded in root environment
    data: Optional[str]
    # marker which becomes true whenever we change our data
    is_dirty: bool = False
    
    def __setattr__(self, key, value):
        super().__setattr__('is_dirty', True)
        super().__setattr__(key, value)


@contextmanager
def wp_config_cache(key, path) -> ContextManager[CacheRecord]:
    # there is no need to cache these values
    # in not actively requested places
    if not scoped_cache.CACHING_ENABLED:
        yield CacheRecord(data=None)
        return

    ts = _get_wp_config_modification_ts(wp_path=path)

    record = CacheRecord(
        data=get(key, path, valid_after_ts=ts))
    try:
        yield record
    finally:
        if record.is_dirty:
            set(key, path, record.data)

def get(key: str, path: str, valid_after_ts: float) -> Optional[str]:
    cache_file = os.path.join(
        _get_cache_directory(), f'{key}.{hashlib.md5(path.encode()).hexdigest()}.cache')

    try:
        # if file was modified earlier than timestamp,
        # we assume that cache is expired
        if os.path.getmtime(cache_file) < valid_after_ts:
            logging.info('Cache "%s" assumed to be outdated', key)
            return None

        with open(cache_file, 'r') as f:
            cache_info_raw = f.read()
    except (IOError, OSError):
        # assume that file does not exist
        # or we don't have access
        logging.info('Cache "%s" is not existing or malformed', key)
        return None

    return cache_info_raw

def set(key: str, path:str, value: str) -> None:
    cache_file = os.path.join(
        _get_cache_directory(), f'{key}.{hashlib.md5(path.encode()).hexdigest()}.cache')

    try:
        with open(cache_file, 'w') as f:
            f.write(value)
    except (IOError, OSError):
        return None