HTML
1 year ago
views
5 months ago
Apply.php
6 months ago
Cron.php
1 year ago
CronJob.php
7 months ago
CronJobs.php
2 months ago
Crypt.php
1 month ago
DownloadStats.php
5 months ago
Email.php
5 days ago
EmailCron.php
1 year ago
FileSystem.php
1 year ago
Installer.php
14 hours ago
Messages.php
1 year ago
Query.php
4 months ago
Session.php
14 hours ago
Settings.php
4 years ago
SimpleMath.php
4 years ago
TempStorage.php
14 hours ago
Template.php
5 months ago
UI.php
6 months ago
Updater.php
4 years ago
UserAgent.php
2 years ago
__.php
1 month ago
__MailUI.php
3 years ago
Session.php
300 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Session Management Class |
| 4 | * |
| 5 | * Handles user session data with database or file-based storage. |
| 6 | * Uses cookie-based device ID for session tracking. |
| 7 | * |
| 8 | * @package WPDM |
| 9 | * @subpackage Core |
| 10 | * @author WPDM Team |
| 11 | * @since 4.7.9 |
| 12 | * @version 3.3.39 |
| 13 | * |
| 14 | * @updated 2024-12-23 |
| 15 | * @changelog Added function_exists() checks for WordPress functions |
| 16 | * Added fallbacks for early initialization scenarios |
| 17 | * Fixed namespace prefix for global PHP functions |
| 18 | * Improved compatibility with various server configurations |
| 19 | */ |
| 20 | |
| 21 | namespace WPDM\__; |
| 22 | |
| 23 | class Session |
| 24 | { |
| 25 | private static $data = []; // In-memory cache |
| 26 | public static $deviceID = null; |
| 27 | private static $store; |
| 28 | private static $initialized = false; |
| 29 | |
| 30 | /** |
| 31 | * Initialize session - call once per request |
| 32 | */ |
| 33 | static function init() |
| 34 | { |
| 35 | if (self::$initialized) return; |
| 36 | self::$initialized = true; |
| 37 | |
| 38 | // get_option should be available, but fallback to 'db' if not |
| 39 | self::$store = \function_exists('get_option') ? \get_option('__wpdm_tmp_storage', 'db') : 'db'; |
| 40 | self::initDeviceID(); |
| 41 | |
| 42 | if (self::$store === 'file') { |
| 43 | self::loadFileSession(); |
| 44 | \register_shutdown_function([__CLASS__, 'saveSession']); |
| 45 | } |
| 46 | //wp_die(self::deviceID()); |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Constructor for backward compatibility |
| 51 | */ |
| 52 | function __construct() |
| 53 | { |
| 54 | self::init(); |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Get or generate device ID - cookie-first approach |
| 59 | */ |
| 60 | private static function initDeviceID() |
| 61 | { |
| 62 | // Check cached value |
| 63 | if (self::$deviceID) return self::$deviceID; |
| 64 | |
| 65 | // Check existing cookie |
| 66 | if (!empty($_COOKIE['__wpdm_client'])) { |
| 67 | self::$deviceID = __::sanitize_var($_COOKIE['__wpdm_client'], 'alphanum'); |
| 68 | return self::$deviceID; |
| 69 | } |
| 70 | |
| 71 | // Generate new ID (random is more reliable than IP+UA) |
| 72 | // Use wp_generate_password if available, otherwise fallback to PHP random |
| 73 | if (\function_exists('wp_generate_password')) { |
| 74 | $deviceID = \wp_generate_password(32, false); |
| 75 | } else { |
| 76 | // Fallback for early initialization before WordPress is fully loaded |
| 77 | $deviceID = \bin2hex(\random_bytes(16)); |
| 78 | } |
| 79 | self::$deviceID = $deviceID; |
| 80 | self::setDeviceCookie($deviceID); |
| 81 | |
| 82 | return self::$deviceID; |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Set device cookie with proper domain and security flags |
| 87 | */ |
| 88 | private static function setDeviceCookie($deviceID) |
| 89 | { |
| 90 | if (\defined('WPDM_ACCEPT_COOKIE') && WPDM_ACCEPT_COOKIE === false) return; |
| 91 | |
| 92 | // Check if apply_filters is available (WordPress fully loaded) |
| 93 | if (\function_exists('apply_filters') && !\apply_filters('wpdm_user_accept_cookies', true)) return; |
| 94 | |
| 95 | // Get domain - with fallback for early initialization |
| 96 | if (\function_exists('home_url')) { |
| 97 | $domain = \wp_parse_url(\home_url(), PHP_URL_HOST); |
| 98 | } else { |
| 99 | // Fallback: parse from server variables |
| 100 | $domain = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''; |
| 101 | $domain = \preg_replace('/:\d+$/', '', $domain); // Remove port if present |
| 102 | } |
| 103 | |
| 104 | $secure = \function_exists('is_ssl') ? \is_ssl() : (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'); |
| 105 | @\setcookie('__wpdm_client', $deviceID, 0, "/", $domain, $secure, true); |
| 106 | $_COOKIE['__wpdm_client'] = $deviceID; |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * Get or set device ID |
| 111 | * |
| 112 | * @param string|null $deviceID Optional device ID to set |
| 113 | * @return string Current device ID |
| 114 | */ |
| 115 | static function deviceID($deviceID = null) |
| 116 | { |
| 117 | if ($deviceID) { |
| 118 | self::$deviceID = __::sanitize_var($deviceID, 'alphanum'); |
| 119 | self::setDeviceCookie(self::$deviceID); |
| 120 | } elseif (!self::$deviceID) { |
| 121 | self::init(); |
| 122 | } |
| 123 | return self::$deviceID; |
| 124 | } |
| 125 | |
| 126 | /** |
| 127 | * Set session value - with in-memory caching |
| 128 | * |
| 129 | * @param string $name Session key |
| 130 | * @param mixed $value Session value |
| 131 | * @param int $expire Expiration time in seconds (default 30 minutes) |
| 132 | */ |
| 133 | static function set($name, $value, $expire = 1800) |
| 134 | { |
| 135 | if (!$name) return; |
| 136 | if (!self::$initialized) self::init(); |
| 137 | |
| 138 | $expireTime = \time() + $expire; |
| 139 | |
| 140 | // Always cache in memory |
| 141 | self::$data[$name] = ['value' => $value, 'expire' => $expireTime]; |
| 142 | |
| 143 | if (self::$store === 'file') { |
| 144 | // File storage saves on shutdown |
| 145 | return; |
| 146 | } |
| 147 | |
| 148 | // DB storage. REPLACE INTO only de-duplicates on a PRIMARY/UNIQUE |
| 149 | // collision; (deviceID, name) is not unique here, so REPLACE would keep |
| 150 | // inserting duplicate rows on every set(). Delete-then-insert (both |
| 151 | // index-backed by `name_device`) guarantees a single row per key. |
| 152 | global $wpdb; |
| 153 | if ($value) { |
| 154 | $wpdb->delete("{$wpdb->prefix}ahm_sessions", ['deviceID' => self::$deviceID, 'name' => $name]); |
| 155 | $wpdb->insert("{$wpdb->prefix}ahm_sessions", [ |
| 156 | 'deviceID' => self::$deviceID, |
| 157 | 'name' => $name, |
| 158 | 'value' => \maybe_serialize($value), |
| 159 | 'lastAccess' => \time(), |
| 160 | 'expire' => $expireTime, |
| 161 | ]); |
| 162 | } else { |
| 163 | self::clear($name); |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | /** |
| 168 | * Get session value - with in-memory caching |
| 169 | * |
| 170 | * @param string $name Session key |
| 171 | * @return mixed|null Session value or null if not found/expired |
| 172 | */ |
| 173 | static function get($name) |
| 174 | { |
| 175 | if (!self::$initialized) self::init(); |
| 176 | |
| 177 | // Check in-memory cache first |
| 178 | if (isset(self::$data[$name])) { |
| 179 | $cached = self::$data[$name]; |
| 180 | if ($cached['expire'] > \time()) { |
| 181 | return $cached['value']; |
| 182 | } |
| 183 | // Expired - remove from cache |
| 184 | unset(self::$data[$name]); |
| 185 | return null; |
| 186 | } |
| 187 | |
| 188 | if (self::$store === 'file') { |
| 189 | return null; // File storage loads everything upfront |
| 190 | } |
| 191 | |
| 192 | // DB storage - use prepared statement |
| 193 | global $wpdb; |
| 194 | $value = $wpdb->get_var($wpdb->prepare( |
| 195 | "SELECT value FROM {$wpdb->prefix}ahm_sessions |
| 196 | WHERE deviceID = %s AND name = %s AND expire > %d", |
| 197 | self::$deviceID, $name, \time() |
| 198 | )); |
| 199 | |
| 200 | if ($value !== null) { |
| 201 | $unserialized = \maybe_unserialize($value); |
| 202 | // Cache for subsequent calls in same request |
| 203 | self::$data[$name] = ['value' => $unserialized, 'expire' => \time() + 300]; |
| 204 | return $unserialized; |
| 205 | } |
| 206 | |
| 207 | return null; |
| 208 | } |
| 209 | |
| 210 | /** |
| 211 | * Clear session data |
| 212 | * |
| 213 | * @param string $name Optional key to clear. Empty clears all. |
| 214 | */ |
| 215 | static function clear($name = '') |
| 216 | { |
| 217 | if (!self::$initialized) self::init(); |
| 218 | |
| 219 | global $wpdb; |
| 220 | |
| 221 | if ($name === '') { |
| 222 | self::$data = []; |
| 223 | if (self::$store !== 'file') { |
| 224 | $wpdb->delete("{$wpdb->prefix}ahm_sessions", ['deviceID' => self::$deviceID]); |
| 225 | } |
| 226 | } else { |
| 227 | unset(self::$data[$name]); |
| 228 | if (self::$store !== 'file') { |
| 229 | $wpdb->delete("{$wpdb->prefix}ahm_sessions", ['deviceID' => self::$deviceID, 'name' => $name]); |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | /** |
| 235 | * Cleanup expired sessions - call via cron |
| 236 | */ |
| 237 | static function cleanup() |
| 238 | { |
| 239 | global $wpdb; |
| 240 | $wpdb->query($wpdb->prepare( |
| 241 | "DELETE FROM {$wpdb->prefix}ahm_sessions WHERE expire < %d AND deviceID != 'alldevice'", |
| 242 | \time() |
| 243 | )); |
| 244 | } |
| 245 | |
| 246 | /** |
| 247 | * Reset all sessions except 'alldevice' temp rows and durable download-key rows |
| 248 | */ |
| 249 | static function reset() |
| 250 | { |
| 251 | global $wpdb; |
| 252 | $wpdb->query("DELETE FROM {$wpdb->prefix}ahm_sessions WHERE deviceID NOT IN ('alldevice', '" . TempStorage::DURABLE_SCOPE . "')"); |
| 253 | } |
| 254 | |
| 255 | /** |
| 256 | * Debug: Show session data |
| 257 | */ |
| 258 | static function show() |
| 259 | { |
| 260 | wpdmprecho(self::$data); |
| 261 | } |
| 262 | |
| 263 | /** |
| 264 | * Load session data from file storage |
| 265 | */ |
| 266 | private static function loadFileSession() |
| 267 | { |
| 268 | $file = WPDM_CACHE_DIR . "/session-" . self::$deviceID . ".txt"; |
| 269 | $realpath = \realpath($file); |
| 270 | if ($realpath && \file_exists($realpath) && \substr_count($realpath, WPDM_CACHE_DIR)) { |
| 271 | $data = \file_get_contents($realpath); |
| 272 | $data = Crypt::decrypt($data, true); |
| 273 | self::$data = \is_array($data) ? $data : []; |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | /** |
| 278 | * Save session data to file storage (called on shutdown) |
| 279 | */ |
| 280 | static function saveSession() |
| 281 | { |
| 282 | if (self::$store !== 'file' || empty(self::$data)) return; |
| 283 | |
| 284 | // Filter out expired entries before saving |
| 285 | $now = \time(); |
| 286 | self::$data = \array_filter(self::$data, function($v) use ($now) { |
| 287 | return $v['expire'] > $now; |
| 288 | }); |
| 289 | |
| 290 | if (empty(self::$data)) return; |
| 291 | |
| 292 | if (!\file_exists(WPDM_CACHE_DIR)) { |
| 293 | @\mkdir(WPDM_CACHE_DIR, 0755, true); |
| 294 | } |
| 295 | |
| 296 | $data = Crypt::encrypt(self::$data); |
| 297 | \file_put_contents(WPDM_CACHE_DIR . 'session-' . self::$deviceID . '.txt', $data); |
| 298 | } |
| 299 | } |
| 300 |