| Current File : /home/mmdealscpanel/yummmdeals.com/add-ons.tar |
ispmanager/httpd_config.xml 0000644 00000013727 15055136437 0012107 0 ustar 00 <?xml version="1.0" encoding="UTF-8"?>
<httpServerConfig>
<serverName>$HOSTNAME</serverName>
<user>apache</user>
<group>apache</group>
<priority>0</priority>
<chrootPath>/</chrootPath>
<enableChroot>0</enableChroot>
<inMemBufSize>60M</inMemBufSize>
<swappingDir>/tmp/lshttpd/swap</swappingDir>
<autoRestart>1</autoRestart>
<autoFix503>0</autoFix503>
<loadApacheConf>1</loadApacheConf>
<autoReloadApacheConf>1</autoReloadApacheConf>
<apacheBinPath>/usr/sbin/httpd</apacheBinPath>
<apacheConfFile>/etc/httpd/conf/httpd.conf</apacheConfFile>
<apachePortOffset>%AP_PORT_OFFSET%</apachePortOffset>
<apacheIpOffset></apacheIpOffset>
<apacheHandledContent>/manager/,/mancgi/</apacheHandledContent>
<phpSuExec>%PHP_SUEXEC%</phpSuExec>
<phpSuExecMaxConn>10</phpSuExecMaxConn>
<mime>$SERVER_ROOT/conf/mime.properties</mime>
<disableInitLogRotation></disableInitLogRotation>
<showVersionNumber>0</showVersionNumber>
<enableIpGeo></enableIpGeo>
<useIpInProxyHeader>2</useIpInProxyHeader>
<autoUpdateInterval>86400</autoUpdateInterval>
<autoUpdateDownloadPkg>1</autoUpdateDownloadPkg>
<adminEmails>%ADMIN_EMAIL%</adminEmails>
<adminRoot>$SERVER_ROOT/admin/</adminRoot>
<logging>
<log>
<fileName>$SERVER_ROOT/logs/error.log</fileName>
<logLevel>DEBUG</logLevel>
<debugLevel>0</debugLevel>
<rollingSize>2000M</rollingSize>
<enableStderrLog>1</enableStderrLog>
</log>
<accessLog>
<fileName>$SERVER_ROOT/logs/access.log</fileName>
<rollingSize>10M</rollingSize>
<keepDays>30</keepDays>
<compressArchive>0</compressArchive>
</accessLog>
</logging>
<indexFiles>index.html, index.php, index.htm</indexFiles>
<autoIndex></autoIndex>
<autoIndexURI></autoIndexURI>
<htAccess>
<allowOverride>31</allowOverride>
<accessFileName>.htaccess</accessFileName>
</htAccess>
<expires>
<enableExpires>1</enableExpires>
<expiresByType>image/*=A604800, text/css=A604800, application/x-javascript=A604800, application/javascript=A604800</expiresByType>
</expires>
<tuning>
<maxConnections>10000</maxConnections>
<maxSSLConnections>10000</maxSSLConnections>
<connTimeout>120</connTimeout>
<maxKeepAliveReq>10000</maxKeepAliveReq>
<smartKeepAlive>0</smartKeepAlive>
<keepAliveTimeout>10</keepAliveTimeout>
<sndBufSize>0</sndBufSize>
<rcvBufSize>0</rcvBufSize>
<eventDispatcher>best</eventDispatcher>
<maxCachedFileSize>4096</maxCachedFileSize>
<totalInMemCacheSize>20M</totalInMemCacheSize>
<maxMMapFileSize>256K</maxMMapFileSize>
<totalMMapCacheSize>40M</totalMMapCacheSize>
<useSendfile>1</useSendfile>
<useAIO>1</useAIO>
<AIOBlockSize>4</AIOBlockSize>
<etagNoInode>1</etagNoInode>
<SSLCryptoDevice>null</SSLCryptoDevice>
<maxReqURLLen>8192</maxReqURLLen>
<maxReqHeaderSize>16380</maxReqHeaderSize>
<maxReqBodySize>500M</maxReqBodySize>
<maxDynRespHeaderSize>4K</maxDynRespHeaderSize>
<maxDynRespSize>500M</maxDynRespSize>
<enableGzipCompress>1</enableGzipCompress>
<enableDynGzipCompress>1</enableDynGzipCompress>
<compressibleTypes>default</compressibleTypes>
<gzipAutoUpdateStatic>1</gzipAutoUpdateStatic>
<gzipCacheDir></gzipCacheDir>
</tuning>
<security>
<fileAccessControl>
<followSymbolLink>1</followSymbolLink>
<checkSymbolLink>0</checkSymbolLink>
<forceStrictOwnership>1</forceStrictOwnership>
<requiredPermissionMask>000</requiredPermissionMask>
<restrictedPermissionMask>000</restrictedPermissionMask>
<restrictedScriptPermissionMask>002</restrictedScriptPermissionMask>
<restrictedDirPermissionMask>002</restrictedDirPermissionMask>
</fileAccessControl>
<perClientConnLimit>
<staticReqPerSec>0</staticReqPerSec>
<dynReqPerSec>0</dynReqPerSec>
<outBandwidth>0</outBandwidth>
<inBandwidth>0</inBandwidth>
<softLimit>10000</softLimit>
<hardLimit>10000</hardLimit>
<gracePeriod>15</gracePeriod>
<banPeriod>300</banPeriod>
</perClientConnLimit>
<CGIRLimit>
<maxCGIInstances>20</maxCGIInstances>
<minUID>11</minUID>
<minGID>10</minGID>
<priority>0</priority>
<CPUSoftLimit>60</CPUSoftLimit>
<CPUHardLimit>120</CPUHardLimit>
<memSoftLimit>1250M</memSoftLimit>
<memHardLimit>1300M</memHardLimit>
<procSoftLimit>400</procSoftLimit>
<procHardLimit>450</procHardLimit>
</CGIRLimit>
<censorshipControl>
<enableCensorship>0</enableCensorship>
<logLevel>0</logLevel>
<defaultAction>deny,log,status:403</defaultAction>
<scanPOST>1</scanPOST>
</censorshipControl>
<accessDenyDir>
<dir>/</dir>
<dir>/etc/*</dir>
<dir>/dev/*</dir>
<dir>$SERVER_ROOT/conf/*</dir>
<dir>$SERVER_ROOT/admin/conf/*</dir>
</accessDenyDir>
<accessControl>
<allow>ALL</allow>
<deny></deny>
</accessControl>
</security>
<extProcessorList>
</extProcessorList>
<scriptHandlerList>
</scriptHandlerList>
<phpConfig>
<maxConns>35</maxConns>
<env>PHP_LSAPI_CHILDREN=35</env>
<initTimeout>60</initTimeout>
<retryTimeout>0</retryTimeout>
<pcKeepAliveTimeout>1</pcKeepAliveTimeout>
<respBuffer>0</respBuffer>
<extMaxIdleTime>60</extMaxIdleTime>
<memSoftLimit></memSoftLimit>
<memHardLimit></memHardLimit>
<procSoftLimit>1400</procSoftLimit>
<procHardLimit>1500</procHardLimit>
</phpConfig>
<railsDefaults>
<rubyBin></rubyBin>
<railsEnv>1</railsEnv>
<maxConns>5</maxConns>
<env>LSAPI_MAX_IDLE=60</env>
<initTimeout>60</initTimeout>
<retryTimeout>0</retryTimeout>
<pcKeepAliveTimeout>60</pcKeepAliveTimeout>
<respBuffer>0</respBuffer>
<backlog>50</backlog>
<runOnStartUp>1</runOnStartUp>
<extMaxIdleTime>300</extMaxIdleTime>
<priority>3</priority>
<memSoftLimit></memSoftLimit>
<memHardLimit></memHardLimit>
<procSoftLimit>400</procSoftLimit>
<procHardLimit>500</procHardLimit>
</railsDefaults>
</httpServerConfig>
frontpage/conf/srm.conf 0000644 00000000000 15055136437 0011125 0 ustar 00 frontpage/conf/access.conf 0000644 00000000000 15055136437 0011565 0 ustar 00 frontpage/conf/httpd.conf 0000644 00000000000 15055136437 0011447 0 ustar 00 hsphere/httpd_config.xml 0000644 00000013250 15055136437 0011406 0 ustar 00 <?xml version="1.0" encoding="UTF-8"?>
<httpServerConfig>
<serverName>$HOSTNAME</serverName>
<user>httpd</user>
<group>httpd</group>
<priority>0</priority>
<chrootPath>/</chrootPath>
<enableChroot>0</enableChroot>
<inMemBufSize>60M</inMemBufSize>
<swappingDir>/tmp/lshttpd/swap</swappingDir>
<autoRestart>1</autoRestart>
<autoFix503>0</autoFix503>
<loadApacheConf>1</loadApacheConf>
<autoReloadApacheConf>1</autoReloadApacheConf>
<apacheConfFile>/hsphere/local/config/httpd/httpd.conf</apacheConfFile>
<apachePortOffset>%AP_PORT_OFFSET%</apachePortOffset>
<apacheIpOffset>0</apacheIpOffset>
<phpSuExec>%PHP_SUEXEC%</phpSuExec>
<phpSuExecMaxConn>10</phpSuExecMaxConn>
<mime>$SERVER_ROOT/conf/mime.properties</mime>
<disableInitLogRotation></disableInitLogRotation>
<showVersionNumber>0</showVersionNumber>
<enableIpGeo></enableIpGeo>
<useIpInProxyHeader>2</useIpInProxyHeader>
<autoUpdateInterval>86400</autoUpdateInterval>
<autoUpdateDownloadPkg>1</autoUpdateDownloadPkg>
<adminEmails>%ADMIN_EMAIL%</adminEmails>
<adminRoot>$SERVER_ROOT/admin/</adminRoot>
<logging>
<log>
<fileName>$SERVER_ROOT/logs/error.log</fileName>
<logLevel>DEBUG</logLevel>
<debugLevel>0</debugLevel>
<rollingSize>10M</rollingSize>
<enableStderrLog>1</enableStderrLog>
</log>
<accessLog>
<fileName>$SERVER_ROOT/logs/access.log</fileName>
<rollingSize>10M</rollingSize>
<keepDays>30</keepDays>
<compressArchive>0</compressArchive>
</accessLog>
</logging>
<indexFiles>index.html, index.php, index.htm</indexFiles>
<autoIndex></autoIndex>
<autoIndexURI></autoIndexURI>
<htAccess>
<allowOverride>31</allowOverride>
<accessFileName>.htaccess</accessFileName>
</htAccess>
<expires>
<enableExpires>1</enableExpires>
<expiresByType>image/*=A604800, text/css=A604800, application/x-javascript=A604800, application/javascript=A604800</expiresByType>
</expires>
<tuning>
<maxConnections>10000</maxConnections>
<maxSSLConnections>10000</maxSSLConnections>
<connTimeout>120</connTimeout>
<maxKeepAliveReq>10000</maxKeepAliveReq>
<smartKeepAlive>0</smartKeepAlive>
<keepAliveTimeout>10</keepAliveTimeout>
<sndBufSize>0</sndBufSize>
<rcvBufSize>0</rcvBufSize>
<eventDispatcher>best</eventDispatcher>
<maxCachedFileSize>4096</maxCachedFileSize>
<totalInMemCacheSize>20M</totalInMemCacheSize>
<maxMMapFileSize>256K</maxMMapFileSize>
<totalMMapCacheSize>40M</totalMMapCacheSize>
<useSendfile>1</useSendfile>
<useAIO>1</useAIO>
<AIOBlockSize>4</AIOBlockSize>
<etagNoInode>1</etagNoInode>
<SSLCryptoDevice>null</SSLCryptoDevice>
<maxReqURLLen>8192</maxReqURLLen>
<maxReqHeaderSize>16380</maxReqHeaderSize>
<maxReqBodySize>500M</maxReqBodySize>
<maxDynRespHeaderSize>4K</maxDynRespHeaderSize>
<maxDynRespSize>500M</maxDynRespSize>
<enableGzipCompress>1</enableGzipCompress>
<enableDynGzipCompress>1</enableDynGzipCompress>
<compressibleTypes>default</compressibleTypes>
<gzipAutoUpdateStatic>1</gzipAutoUpdateStatic>
<gzipCacheDir></gzipCacheDir>
</tuning>
<security>
<fileAccessControl>
<followSymbolLink>1</followSymbolLink>
<checkSymbolLink>0</checkSymbolLink>
<requiredPermissionMask>000</requiredPermissionMask>
<restrictedPermissionMask>000</restrictedPermissionMask>
</fileAccessControl>
<perClientConnLimit>
<staticReqPerSec>0</staticReqPerSec>
<dynReqPerSec>0</dynReqPerSec>
<outBandwidth>0</outBandwidth>
<inBandwidth>0</inBandwidth>
<softLimit>10000</softLimit>
<hardLimit>10000</hardLimit>
<gracePeriod>15</gracePeriod>
<banPeriod>300</banPeriod>
</perClientConnLimit>
<CGIRLimit>
<maxCGIInstances>20</maxCGIInstances>
<minUID>11</minUID>
<minGID>10</minGID>
<priority>0</priority>
<CPUSoftLimit>60</CPUSoftLimit>
<CPUHardLimit>120</CPUHardLimit>
<memSoftLimit>1250M</memSoftLimit>
<memHardLimit>1300M</memHardLimit>
<procSoftLimit>400</procSoftLimit>
<procHardLimit>450</procHardLimit>
</CGIRLimit>
<censorshipControl>
<enableCensorship>0</enableCensorship>
<logLevel>0</logLevel>
<defaultAction>deny,log,status:403</defaultAction>
<scanPOST>1</scanPOST>
</censorshipControl>
<accessDenyDir>
<dir>/</dir>
<dir>/etc/*</dir>
<dir>/dev/*</dir>
<dir>$SERVER_ROOT/conf/*</dir>
<dir>$SERVER_ROOT/admin/conf/*</dir>
</accessDenyDir>
<accessControl>
<allow>ALL</allow>
<deny></deny>
</accessControl>
</security>
<extProcessorList>
</extProcessorList>
<scriptHandlerList>
</scriptHandlerList>
<phpConfig>
<maxConns>35</maxConns>
<env>PHP_LSAPI_CHILDREN=35</env>
<initTimeout>60</initTimeout>
<retryTimeout>0</retryTimeout>
<pcKeepAliveTimeout>1</pcKeepAliveTimeout>
<respBuffer>0</respBuffer>
<extMaxIdleTime>60</extMaxIdleTime>
<memSoftLimit></memSoftLimit>
<memHardLimit></memHardLimit>
<procSoftLimit>1400</procSoftLimit>
<procHardLimit>1500</procHardLimit>
</phpConfig>
<railsDefaults>
<rubyBin></rubyBin>
<railsEnv>1</railsEnv>
<maxConns>5</maxConns>
<env>LSAPI_MAX_IDLE=60</env>
<initTimeout>60</initTimeout>
<retryTimeout>0</retryTimeout>
<pcKeepAliveTimeout>60</pcKeepAliveTimeout>
<respBuffer>0</respBuffer>
<backlog>50</backlog>
<runOnStartUp>1</runOnStartUp>
<extMaxIdleTime>300</extMaxIdleTime>
<priority>3</priority>
<memSoftLimit></memSoftLimit>
<memHardLimit></memHardLimit>
<procSoftLimit>200</procSoftLimit>
<procHardLimit>300</procHardLimit>
</railsDefaults>
</httpServerConfig>
cwp/httpd_config.xml 0000644 00000013573 15055136437 0010551 0 ustar 00 <?xml version="1.0" encoding="UTF-8"?>
<httpServerConfig>
<serverName>$HOSTNAME</serverName>
<user>nobody</user>
<group>nobody</group>
<priority>0</priority>
<chrootPath>/</chrootPath>
<enableChroot>0</enableChroot>
<inMemBufSize>60M</inMemBufSize>
<swappingDir>/tmp/lshttpd/swap</swappingDir>
<autoRestart>1</autoRestart>
<autoFix503>0</autoFix503>
<loadApacheConf>1</loadApacheConf>
<autoReloadApacheConf>2</autoReloadApacheConf>
<apacheBinPath>/usr/local/apache/bin/httpd</apacheBinPath>
<apacheConfFile>/usr/local/apache/conf/httpd.conf</apacheConfFile>
<apachePortOffset>0</apachePortOffset>
<apacheIpOffset>0</apacheIpOffset>
<apacheIgnoredModules></apacheIgnoredModules>
<phpSuExec>%PHP_SUEXEC%</phpSuExec>
<phpSuExecMaxConn>10</phpSuExecMaxConn>
<mime>$SERVER_ROOT/conf/mime.properties</mime>
<disableInitLogRotation>1</disableInitLogRotation>
<showVersionNumber>0</showVersionNumber>
<enableIpGeo></enableIpGeo>
<useIpInProxyHeader>2</useIpInProxyHeader>
<autoUpdateInterval>86400</autoUpdateInterval>
<autoUpdateDownloadPkg>1</autoUpdateDownloadPkg>
<adminEmails>%ADMIN_EMAIL%</adminEmails>
<adminRoot>$SERVER_ROOT/admin/</adminRoot>
<logging>
<log>
<fileName>/usr/local/apache/logs/error_log</fileName>
<logLevel>DEBUG</logLevel>
<debugLevel>0</debugLevel>
<rollingSize>2000M</rollingSize>
<enableStderrLog>1</enableStderrLog>
</log>
<accessLog>
<fileName>$SERVER_ROOT/logs/access.log</fileName>
<rollingSize>2000M</rollingSize>
<keepDays>30</keepDays>
<compressArchive>0</compressArchive>
</accessLog>
</logging>
<indexFiles>index.html, index.php, index.htm</indexFiles>
<autoIndex></autoIndex>
<autoIndexURI></autoIndexURI>
<htAccess>
<allowOverride>31</allowOverride>
<accessFileName>.htaccess</accessFileName>
</htAccess>
<expires>
<enableExpires>1</enableExpires>
<expiresByType>image/*=A604800, text/css=A604800, application/x-javascript=A604800, application/javascript=A604800</expiresByType>
</expires>
<tuning>
<maxConnections>10000</maxConnections>
<maxSSLConnections>10000</maxSSLConnections>
<connTimeout>120</connTimeout>
<maxKeepAliveReq>10000</maxKeepAliveReq>
<smartKeepAlive>0</smartKeepAlive>
<keepAliveTimeout>10</keepAliveTimeout>
<sndBufSize>0</sndBufSize>
<rcvBufSize>0</rcvBufSize>
<eventDispatcher>best</eventDispatcher>
<maxCachedFileSize>4096</maxCachedFileSize>
<totalInMemCacheSize>20M</totalInMemCacheSize>
<maxMMapFileSize>256K</maxMMapFileSize>
<totalMMapCacheSize>40M</totalMMapCacheSize>
<useSendfile>1</useSendfile>
<useAIO>1</useAIO>
<AIOBlockSize>4</AIOBlockSize>
<etagNoInode>1</etagNoInode>
<SSLCryptoDevice>null</SSLCryptoDevice>
<maxReqURLLen>8192</maxReqURLLen>
<maxReqHeaderSize>16380</maxReqHeaderSize>
<maxReqBodySize>500M</maxReqBodySize>
<maxDynRespHeaderSize>8K</maxDynRespHeaderSize>
<maxDynRespSize>500M</maxDynRespSize>
<enableGzipCompress>1</enableGzipCompress>
<enableDynGzipCompress>1</enableDynGzipCompress>
<compressibleTypes>default</compressibleTypes>
<gzipAutoUpdateStatic>1</gzipAutoUpdateStatic>
<gzipCacheDir></gzipCacheDir>
</tuning>
<security>
<fileAccessControl>
<followSymbolLink>1</followSymbolLink>
<checkSymbolLink>0</checkSymbolLink>
<forceStrictOwnership>1</forceStrictOwnership>
<requiredPermissionMask>000</requiredPermissionMask>
<restrictedPermissionMask>000</restrictedPermissionMask>
<restrictedScriptPermissionMask>000</restrictedScriptPermissionMask>
<restrictedDirPermissionMask>000</restrictedDirPermissionMask>
</fileAccessControl>
<perClientConnLimit>
<staticReqPerSec>0</staticReqPerSec>
<dynReqPerSec>0</dynReqPerSec>
<outBandwidth>0</outBandwidth>
<inBandwidth>0</inBandwidth>
<softLimit>10000</softLimit>
<hardLimit>10000</hardLimit>
<gracePeriod>15</gracePeriod>
<banPeriod>300</banPeriod>
</perClientConnLimit>
<CGIRLimit>
<maxCGIInstances>200</maxCGIInstances>
<minUID>11</minUID>
<minGID>10</minGID>
<priority>0</priority>
<CPUSoftLimit>60</CPUSoftLimit>
<CPUHardLimit>120</CPUHardLimit>
<memSoftLimit>1450M</memSoftLimit>
<memHardLimit>1500M</memHardLimit>
<procSoftLimit>400</procSoftLimit>
<procHardLimit>450</procHardLimit>
</CGIRLimit>
<censorshipControl>
<enableCensorship>0</enableCensorship>
<logLevel>0</logLevel>
<defaultAction>deny,log,status:403</defaultAction>
<scanPOST>1</scanPOST>
</censorshipControl>
<accessDenyDir>
<dir>/</dir>
<dir>/etc/*</dir>
<dir>/dev/*</dir>
<dir>$SERVER_ROOT/conf/*</dir>
<dir>$SERVER_ROOT/admin/conf/*</dir>
</accessDenyDir>
<accessControl>
<allow>ALL</allow>
<deny></deny>
</accessControl>
</security>
<phpConfig>
<maxConns>35</maxConns>
<env>PHP_LSAPI_CHILDREN=35</env>
<initTimeout>60</initTimeout>
<retryTimeout>0</retryTimeout>
<pcKeepAliveTimeout>1</pcKeepAliveTimeout>
<respBuffer>0</respBuffer>
<extMaxIdleTime>60</extMaxIdleTime>
<memSoftLimit></memSoftLimit>
<memHardLimit></memHardLimit>
<procSoftLimit>1400</procSoftLimit>
<procHardLimit>1500</procHardLimit>
</phpConfig>
<railsDefaults>
<rubyBin></rubyBin>
<railsEnv>1</railsEnv>
<maxConns>5</maxConns>
<env>LSAPI_MAX_IDLE=60</env>
<initTimeout>60</initTimeout>
<retryTimeout>0</retryTimeout>
<pcKeepAliveTimeout>60</pcKeepAliveTimeout>
<respBuffer>0</respBuffer>
<backlog>50</backlog>
<runOnStartUp>1</runOnStartUp>
<extMaxIdleTime>300</extMaxIdleTime>
<priority>3</priority>
<memSoftLimit></memSoftLimit>
<memHardLimit></memHardLimit>
<procSoftLimit>400</procSoftLimit>
<procHardLimit>500</procHardLimit>
</railsDefaults>
</httpServerConfig>
modsec/inspectmulti.sh 0000555 00000000232 15055136437 0011101 0 ustar 00 #!/bin/sh
if [ $# -lt 2 ] ; then
echo "miss parameter."
else
RUNAVCMD=$1
shift
for var in "$@"
do
$RUNAVCMD $var
done
fi
webcachemgr/MIN_VER 0000644 00000000007 15055136437 0010103 0 ustar 00 1.17.3
webcachemgr/autoloader.php 0000664 00000001565 15055136437 0011705 0 ustar 00 <?php
/* * *********************************************
* LiteSpeed Web Server Cache Manager
* @Author: LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @Copyright: (c) 2018
* *******************************************
*/
spl_autoload_register(function($class) {
/**
* project-specific namespace prefix
*/
$prefix = 'Lsc\\Wp\\';
/**
* base directory for the namespace prefix
*/
$base_dir = __DIR__ . '/src/';
$len = strlen($prefix);
if ( strncmp($prefix, $class, $len) !== 0 ) {
/**
* Class use the namespace prefix,
* move to the next registered autoloader.
*/
return;
}
$relative_class_name = substr($class, $len);
$file = $base_dir . str_replace('\\', '/', $relative_class_name) . '.php';
if ( file_exists($file) ) {
require $file;
}
});
webcachemgr/src/LogEntry.php 0000664 00000003342 15055136437 0012073 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright (c) 2018-2019
* *******************************************
*/
namespace Lsc\Wp;
class LogEntry
{
/**
* @var int
*/
protected $lvl;
/**
* @var string
*/
protected $msg;
/**
*
* @var null|string
*/
protected $prefix;
/**
*
* @var int[]
*/
protected $timestamp;
/**
*
* @param string $msg
* @param int $lvl
*/
public function __construct( $msg, $lvl )
{
$this->msg = $msg;
$this->lvl = $lvl;
$this->timestamp = time();
}
/**
*
* @param string $msg
*/
public function append( $msg )
{
$this->msg .= $msg;
}
/**
*
* @return int
*/
public function getLvl()
{
return $this->lvl;
}
/**
*
* @return string
*/
public function getMsg()
{
$msg = ($this->prefix == null) ? '' : "{$this->prefix} ";
if ( $this->msg ) {
$msg .= $this->msg;
}
return $msg;
}
/**
*
* @param int $logLvl
* @return string
* @throws LSCMException Thrown indirectly.
*/
public function getOutput( $logLvl )
{
if ( $this->lvl > $logLvl ) {
return '';
}
$timestamp = date('Y-m-d H:i:s', $this->timestamp);
$addTagInfo = Logger::getAdditionalTagInfo();
$lvl = '[' . Logger::getLvlDescr($this->lvl) . ']';
$msg = $this->getMsg();
return "{$timestamp} {$addTagInfo} {$lvl} {$msg}\n";
}
}
webcachemgr/src/Panel/ControlPanel.php 0000664 00000074633 15055136437 0014002 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2017-2024 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\Panel;
use DirectoryIterator;
use Exception;
use Lsc\Wp\Logger;
use Lsc\Wp\LSCMException;
use Lsc\Wp\Util;
use Lsc\Wp\WPInstall;
abstract class ControlPanel
{
/**
* @deprecated
*
* @var string
*/
const PANEL_CPANEL = 'whm';
/**
* @deprecated
*
* @var string
*/
const PANEL_PLESK = 'plesk';
/**
* @var string
*/
const PANEL_API_VERSION = '1.17.4.2';
/**
* @since 1.9
* @var int
*/
const PANEL_API_VERSION_SUPPORTED = 0;
/**
* @since 1.9
* @var int
*/
const PANEL_API_VERSION_TOO_LOW = 1;
/**
* @since 1.9
* @var int
*/
const PANEL_API_VERSION_TOO_HIGH = 2;
/**
* @since 1.9
* @var int
*/
const PANEL_API_VERSION_UNKNOWN = 3;
/**
* @var int
*/
const PHP_TIMEOUT = 30;
/**
* @var string
*/
const NOT_SET = '__LSC_NOTSET__';
/**
* @var string
*/
protected $panelName = '';
/**
* @var string
*/
protected $phpOptions;
/**
* @var null|string
*/
protected $serverCacheRoot;
/**
* @var null|string
*/
protected $vhCacheRoot;
/**
* @var string
*/
protected $defaultSvrCacheRoot;
/**
* @var string
*/
protected $apacheConf;
/**
* @var string
*/
protected $apacheVHConf;
/**
* @var null|array[] 'docroots' => (index => docroots),
* 'names' => (servername => index)
*/
protected $docRootMap = null;
/**
* @since 1.9.7
* @var string
*/
protected static $minAPIFilePath = '';
/**
* @var null|ControlPanel Object that extends ControlPanel abstract class.
*/
protected static $instance;
/**
*
* @throws LSCMException Thrown indirectly by $this->init2() call.
*/
protected function __construct()
{
$this->init2();
}
/**
* Temporary function name until existing deprecated public static init()
* function is removed.
*
* @since 1.13.2
*
* @throws LSCMException Thrown indirectly by $this->initConfPaths() call.
*/
protected function init2()
{
/**
* output_handler value cleared to avoid compressed output through
* 'ob_gzhandler' etc.
*/
$this->phpOptions = '-d disable_functions=ini_set -d opcache.enable=0 '
. '-d max_execution_time=' . static::PHP_TIMEOUT
. ' -d memory_limit=512M -d register_argc_argv=1 '
. '-d zlib.output_compression=0 -d output_handler= '
. '-d safe_mode=0 -d open_basedir=';
$this->initConfPaths();
}
/**
* Deprecated 02/04/19 as this function will be made private.
* Use getClassInstance() with a fully qualified class name as a parameter
* instead.
*
* Sets static::$instance with a new $className instance if it has not been
* set already. An exception will be thrown if static::$instance has already
* been set to a different class name than the one provided.
*
* @deprecated
*
* @param string $className A fully qualified control panel class name.
*
* @return ControlPanel|null Object that extends ControlPanel abstract
* class.
*
* @throws LSCMException Thrown when unable to include custom panel file.
* @throws LSCMException Thrown when class 'CustomPanel' does not extend
* class '\Lsc\Wp\Panel\CustomPanelBase'.
* @throws LSCMException Re-thrown when "new $className()" call throws an
* exception.
* @throws LSCMException Thrown when an instance of a different
* ControlPanel/CustomPanel extending class has already been created.
*/
public static function initByClassName( $className )
{
if ( static::$instance == null ) {
if ( $className == 'custom' ) {
$lsws_home = realpath(__DIR__ . '/../../../../');
$customPanelFile =
"$lsws_home/admin/lscdata/custom/CustomPanel.php";
if ( ! file_exists($customPanelFile)
|| ! include_once $customPanelFile ) {
throw new LSCMException(
"Unable to include file $customPanelFile"
);
}
$className = '\Lsc\Wp\Panel\CustomPanel';
$isSubClass = is_subclass_of(
$className,
'\Lsc\Wp\Panel\CustomPanelBase'
);
if ( ! $isSubClass ) {
throw new LSCMException(
'Class CustomPanel must extend class '
. '\Lsc\Wp\Panel\CustomPanelBase'
);
}
}
try{
static::$instance = new $className();
}
catch ( Exception $e ){
throw new LSCMException(
"Could not create object with class name $className. "
. "Error: {$e->getMessage()}"
);
}
}
else {
$instanceClassName = '\\' . get_class(static::$instance);
if ( $instanceClassName != $className ) {
throw new LSCMException(
"Could not initialize $className instance as an instance "
. "of another class ($instanceClassName) has already "
. 'been created.'
);
}
}
return static::$instance;
}
/**
* Deprecated 01/14/19. Use initByClassName() instead.
*
* @deprecated
*
* @param string $name
*
* @return ControlPanel Object that extends ControlPanel abstract class.
*
* @throws LSCMException Thrown when static::$instance is not null.
* @throws LSCMException Thrown when provided $name is not recognized.
* @throws LSCMException Thrown indirectly by static::initByClassName()
* call.
*/
public static function init( $name )
{
if ( static::$instance != null ) {
throw new LSCMException(
'ControlPanel cannot be initialized twice.'
);
}
switch ($name) {
case static::PANEL_CPANEL:
$className = 'CPanel';
break;
case static::PANEL_PLESK:
$className = 'Plesk';
break;
default:
throw new LSCMException(
"Control panel '$name' is not supported."
);
}
return static::initByClassName("\Lsc\Wp\Panel\\$className");
}
/**
* Returns current ControlPanel instance when no $className is given. When
* $className is provided, an instance of $className will also be
* initialized if it has not yet been initialized already.
*
* @param string $className Fully qualified class name.
*
* @return ControlPanel Object that extends ControlPanel abstract class.
*
* @throws LSCMException Thrown when static::$instance is null.
* @throws LSCMException Thrown indirectly by static::initByClassName()
* call.
*/
public static function getClassInstance( $className = '' )
{
if ( $className != '' ) {
static::initByClassName($className);
}
elseif ( static::$instance == null ) {
throw new LSCMException(
'Could not get instance, ControlPanel not initialized. '
);
}
return static::$instance;
}
/**
* Deprecated on 02/06/19. Use getClassInstance() instead.
*
* @deprecated
*
* @return ControlPanel Object that extends ControlPanel abstract class.
*
* @throws LSCMException Thrown indirectly by static::getClassInstance()
* call.
*/
public static function getInstance()
{
return static::getClassInstance();
}
/**
*
* @param string $serverName
*
* @return string|null
*
* @throws LSCMException Thrown indirectly by $this->prepareDocrootMap()
* call.
*/
public function mapDocRoot( $serverName )
{
if ( $this->docRootMap == null ) {
$this->prepareDocrootMap();
}
if ( isset($this->docRootMap['names'][$serverName]) ) {
$index = $this->docRootMap['names'][$serverName];
return $this->docRootMap['docroots'][$index];
}
// error out
return null;
}
/**
*
* @return bool
*
* @throws LSCMException Thrown indirectly by $this->getServerCacheRoot()
* call.
* @throws LSCMException Thrown indirectly by $this->getVHCacheRoot() call.
*/
public function areCacheRootsSet()
{
$ret = true;
if ( static::NOT_SET == $this->getServerCacheRoot() ) {
$ret = false;
}
if ( static::NOT_SET == $this->getVHCacheRoot() ) {
$ret = false;
}
return $ret;
}
/**
*
* @throws LSCMException Thrown when cache is not enabled for the current
* LiteSpeed license.
* @throws LSCMException Thrown indirectly by $this->getServerCacheRoot()
* call.
* @throws LSCMException Thrown indirectly by $this->setServerCacheRoot()
* call.
* @throws LSCMException Thrown indirectly by $this->getVHCacheRoot() call.
* @throws LSCMException Thrown indirectly by $this->setVHCacheRoot() call.
*/
public function verifyCacheSetup()
{
if ( !$this->isCacheEnabled() ) {
throw new LSCMException(
'LSCache is not included in the current LiteSpeed license. '
. 'Please purchase the LSCache add-on or upgrade to a '
. 'license type that includes LSCache and try again.',
LSCMException::E_PERMISSION
);
}
$restartRequired = false;
if ( static::NOT_SET == $this->getServerCacheRoot() ) {
$this->setServerCacheRoot();
$restartRequired = true;
}
if ( static::NOT_SET == $this->getVHCacheRoot() ) {
$this->setVHCacheRoot();
$restartRequired = true;
}
if ( $restartRequired ) {
Util::restartLsws();
}
}
/**
*
* @param string $vhCacheRoot
*
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->writeVHCacheRoot()
* call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->applyVHConfChanges()
* call.
*/
public function setVHCacheRoot( $vhCacheRoot = 'lscache' )
{
$this->log('Attempting to set VH cache root...', Logger::L_VERBOSE);
if ( !file_exists($this->apacheVHConf) ) {
$this->createVHConfAndSetCacheRoot(
$this->apacheVHConf,
$vhCacheRoot
);
}
else {
$this->writeVHCacheRoot($this->apacheVHConf, $vhCacheRoot);
}
$this->vhCacheRoot = $vhCacheRoot;
$this->log(
"Virtual Host cache root set to $vhCacheRoot",
Logger::L_INFO
);
if ( $this->vhCacheRoot[0] == '/'
&& !file_exists($this->vhCacheRoot) ) {
/**
* 01/29/19: Temporarily create top virtual host cache root
* directory to avoid LSWS setting incorrect owner/group and
* permissions for the directory outside the cage.
*/
mkdir(str_replace('/$vh_user', '', $vhCacheRoot), 0755, true);
}
$this->applyVHConfChanges();
}
/**
*
* @return bool
*
* @throws LSCMException Thrown when status file is not found.
* @throws LSCMException Thrown when status file cannot be read.
*
*/
public function isCacheEnabled()
{
$statusFile = '/tmp/lshttpd/.status';
if ( !file_exists($statusFile) ) {
throw new LSCMException(
'Cannot determine LSCache availability. Please start/switch to '
. 'LiteSpeed Web Server before trying again.',
LSCMException::E_PERMISSION
);
}
if ( ($f = fopen($statusFile, 'r')) === false ) {
throw new LSCMException(
'Cannot determine LSCache availability.',
LSCMException::E_PERMISSION
);
}
fseek($f, -128, SEEK_END);
$line = fread($f, 128);
fclose($f);
if ( preg_match('/FEATURES: ([0-9.]+)/', $line, $m)
&& ($m[1] & 1) == 1 ) {
return true;
}
return false;
}
/**
* return array of docroots, can set index from and batch
*
* @param int $offset
* @param null|int $length
*
* @return string[]
*
* @throws LSCMException Thrown indirectly by $this->prepareDocrootMap()
* call.
*/
public function getDocRoots( $offset = 0, $length = null )
{
if ( $this->docRootMap == null ) {
$this->prepareDocrootMap();
}
return array_slice($this->docRootMap['docroots'], $offset, $length);
}
/**
* Used in PleskEscalate.
*
* @return array[]
*
* @noinspection PhpUnused
* @noinspection PhpDocMissingThrowsInspection
*/
public function getDocrootMap()
{
if ( $this->docRootMap == null ) {
/**
* LSCMException not thrown in Plesk implementation.
* @noinspection PhpUnhandledExceptionInspection
*/
$this->prepareDocrootMap();
}
return $this->docRootMap;
}
/**
*
* @return string
*/
public function getDefaultSvrCacheRoot()
{
return $this->defaultSvrCacheRoot;
}
/**
*
* @return string
*
* @throws LSCMException Thrown indirectly by $this->initCacheRoots() call.
*/
public function getServerCacheRoot()
{
if ( $this->serverCacheRoot == null ) {
$this->initCacheRoots();
}
return $this->serverCacheRoot;
}
/**
*
* @return string
*
* @throws LSCMException Thrown indirectly by $this->initCacheRoots() call.
*/
public function getVHCacheRoot()
{
if ( $this->vhCacheRoot == null ) {
$this->initCacheRoots();
}
return $this->vhCacheRoot;
}
/**
*
* @return void
*
* @throws LSCMException Thrown in some existing implementations.
*/
abstract protected function initConfPaths();
/**
*
* @throws LSCMException Thrown in some existing implementations.
*/
abstract protected function prepareDocrootMap();
/**
*
* @param WPInstall $wpInstall
*
* @return string
*
* @throws LSCMException Thrown in some existing implementations.
*/
abstract public function getPhpBinary( WPInstall $wpInstall );
/**
* Searches the given directories '.conf' files for CacheRoot setting.
*
* Note: Visibility is public to better accommodate escalation functions.
*
* @param string $confDir Directory to be searched.
*
* @return string
*/
public function cacheRootSearch( $confDir )
{
$files = new DirectoryIterator($confDir);
foreach ( $files as $file ) {
$filename = $file->getFilename();
if ( strlen($filename) > 5
&& substr_compare($filename, '.conf', -5) === 0 ) {
$cacheRoot = $this->getCacheRootSetting($file->getPathname());
if ( $cacheRoot != '' ) {
return $cacheRoot;
}
}
}
return '';
}
/**
* Note: Visibility is public to better accommodate escalation functions.
*
* @param string $file
*
* @return string
*/
public function getCacheRootSetting( $file )
{
if ( file_exists($file) ) {
$matchFound = preg_match(
'/^\s*CacheRoot (.+)/im',
file_get_contents($file),
$matches
);
if ( $matchFound ) {
return trim($matches[1]);
}
}
return '';
}
/**
* Note: Visibility is public to better accommodate escalation functions.
*
* @return string
*/
public function getLSWSCacheRootSetting()
{
$serverConf = __DIR__ . '/../../../../conf/httpd_config.xml';
if ( file_exists($serverConf) ) {
$matchFound = preg_match(
'!<cacheStorePath>(.+)</cacheStorePath>!i',
file_get_contents($serverConf),
$matches
);
if ( $matchFound ) {
return trim($matches[1]);
}
}
return '';
}
abstract protected function serverCacheRootSearch();
abstract protected function vhCacheRootSearch();
/**
* Checks server and VH conf files for cacheroot settings and populates in
* object if found.
*
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
*/
protected function initCacheRoots()
{
$svrCacheRoot = $this->serverCacheRootSearch();
if ( $svrCacheRoot == '' ) {
$svrCacheRoot = $this->getLSWSCacheRootSetting();
}
$vhCacheRoot = $this->vhCacheRootSearch();
if ( $svrCacheRoot ) {
$this->serverCacheRoot = $svrCacheRoot;
$this->log(
"Server level cache root is $svrCacheRoot.",
Logger::L_DEBUG
);
}
else {
$this->serverCacheRoot = static::NOT_SET;
$this->log('Server level cache root is not set.', Logger::L_NOTICE);
}
if ( $vhCacheRoot ) {
$this->vhCacheRoot = $vhCacheRoot;
$this->log(
"Virtual Host level cache root is $vhCacheRoot.",
Logger::L_DEBUG
);
}
else {
$this->vhCacheRoot = static::NOT_SET;
$this->log(
'Virtual Host level cache root is not set.',
Logger::L_INFO
);
}
}
/**
*
* @param string $msg
* @param int $level
*
* @throws LSCMException Thrown indirectly by Logger::error() call.
* @throws LSCMException Thrown indirectly by Logger::warn() call.
* @throws LSCMException Thrown indirectly by Logger::notice() call.
* @throws LSCMException Thrown indirectly by Logger::info() call.
* @throws LSCMException Thrown indirectly by Logger::verbose() call.
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function log( $msg, $level )
{
$msg = "$this->panelName - $msg";
switch ($level) {
case Logger::L_ERROR:
Logger::error($msg);
break;
case Logger::L_WARN:
Logger::warn($msg);
break;
case Logger::L_NOTICE:
Logger::notice($msg);
break;
case Logger::L_INFO:
Logger::info($msg);
break;
case Logger::L_VERBOSE:
Logger::verbose($msg);
break;
case Logger::L_DEBUG:
Logger::debug($msg);
break;
//no default
}
}
/**
*
* @param string $svrCacheRoot
*
* @throws LSCMException Thrown directly and indirectly.
*/
public function setServerCacheRoot( $svrCacheRoot = '' )
{
$this->log('Attempting to set server cache root...', Logger::L_VERBOSE);
if ( $svrCacheRoot != '' ) {
$cacheroot = $svrCacheRoot;
}
else {
$cacheroot = $this->defaultSvrCacheRoot;
}
$cacheRootLine =
"<IfModule LiteSpeed>\nCacheRoot $cacheroot\n</IfModule>\n\n";
if ( !file_exists($this->apacheConf) ) {
file_put_contents($this->apacheConf, $cacheRootLine);
chmod($this->apacheConf, 0644);
$this->log("Created file $this->apacheConf", Logger::L_VERBOSE);
}
else {
if ( !is_writable($this->apacheConf) ) {
throw new LSCMException(
'Apache Config is not writeable. No changes made.'
);
}
if ( !Util::createBackup($this->apacheConf) ) {
throw new LSCMException(
'Could not backup Apache config. No changes made.'
);
}
else {
$file_contents = file($this->apacheConf);
$pattern = '/^\s*<IfModule +LiteSpeed *>/im';
if ( preg_grep($pattern, $file_contents) ) {
if ( preg_grep('/^\s*CacheRoot +/im', $file_contents) ) {
$file_contents = preg_replace(
'/^\s*CacheRoot +.+/im',
"CacheRoot $cacheroot",
$file_contents
);
}
else {
$file_contents = preg_replace(
'/^\s*<IfModule +LiteSpeed *>/im',
"<IfModule LiteSpeed>\nCacheRoot $cacheroot",
$file_contents
);
}
}
else {
array_unshift($file_contents, $cacheRootLine);
}
file_put_contents($this->apacheConf, $file_contents);
}
}
$this->serverCacheRoot = $cacheroot;
$this->log("Server level cache root set to $cacheroot", Logger::L_INFO);
if ( file_exists($cacheroot) ) {
exec("/bin/rm -rf $cacheroot");
$this->log(
'Server level cache root directory removed for proper '
. 'permission.',
Logger::L_DEBUG
);
}
}
/**
*
* @param array $file_contents
* @param string $vhCacheRoot
*
* @return array
*/
abstract protected function addVHCacheRootSection(
array $file_contents,
$vhCacheRoot = 'lscache'
);
/**
*
* @param string $vhConf
*
* @throws LSCMException Thrown when virtual host conf file is not
* writeable.
* @throws LSCMException Thrown when a backup of the virtual host conf file
* could not be made.
* @throws LSCMException Thrown when "write to virtual host conf file" call
* fails.
* @throws LSCMException Thrown indirectly by $this->log() call.
*/
public function writeVHCacheRoot( $vhConf, $vhCacheRoot = 'lscache' )
{
if ( !is_writable($vhConf) ) {
throw new LSCMException(
"Could not write to VH config $vhConf. No changes made.",
LSCMException::E_PERMISSION
);
}
if ( !Util::createBackup($vhConf) ) {
throw new LSCMException(
"Could not backup Virtual Host config file $vhConf. No "
. 'changes made.',
LSCMException::E_PERMISSION
);
}
$file_contents = file($vhConf);
if ( preg_grep('/^\s*<IfModule +LiteSpeed *>/im', $file_contents) ) {
if ( preg_grep('/^\s*CacheRoot +/im', $file_contents) ) {
$modified_contents = preg_replace(
'/^\s*CacheRoot +.+/im',
"CacheRoot $vhCacheRoot",
$file_contents
);
}
else {
$modified_contents = preg_replace(
'/^\s*<IfModule +LiteSpeed *>/im',
"<IfModule LiteSpeed>\nCacheRoot $vhCacheRoot",
$file_contents
);
}
}
else {
$modified_contents =
$this->addVHCacheRootSection($file_contents, $vhCacheRoot);
}
if ( file_put_contents($vhConf, $modified_contents) === false ) {
throw new LSCMException(
"Failed to write to file $vhConf.",
LSCMException::E_PERMISSION
);
}
$this->log("Updated file $vhConf.", Logger::L_DEBUG);
}
/**
* Note: Visibility is public to better accommodate escalation functions.
*
* @param string $vhConf
* @param string $vhCacheRoot
*/
abstract public function createVHConfAndSetCacheRoot(
$vhConf,
$vhCacheRoot = 'lscache'
);
/**
* Note: Visibility is public to better accommodate escalation functions.
*
* @throws LSCMException Thrown by some implementations.
*/
abstract public function applyVHConfChanges();
/**
*
* @since 1.9.7
*/
protected static function setMinAPIFilePath()
{
static::$minAPIFilePath = realpath(__DIR__ . '/../..') . '/MIN_VER';
}
/**
*
* @since 1.9.7
*
* @return string
*/
protected static function getMinAPIFilePath()
{
if ( static::$minAPIFilePath == '' ) {
static::setMinAPIFilePath();
}
return static::$minAPIFilePath;
}
/**
*
* @since 1.9.7
* @since 1.12 Changed visibility from protected to public.
*/
public static function populateMinAPIVerFile()
{
$minVerFile = static::getMinAPIFilePath();
$content = Util::get_url_contents(
'https://www.litespeed.sh/sub/shared/MIN_VER'
);
if ( !empty($content) ) {
file_put_contents($minVerFile, $content);
}
else {
touch($minVerFile);
}
}
/**
*
* @since 1.9.7
*
* @return string
*/
protected static function getMinAPIVer()
{
$minVerFile = static::getMinAPIFilePath();
clearstatcache();
if ( !file_exists($minVerFile)
|| (time() - filemtime($minVerFile)) > 86400 ) {
static::populateMinAPIVerFile();
}
if ( ($content = file_get_contents($minVerFile)) !== false ) {
return trim($content);
}
return '';
}
/**
*
* @since 1.9.7
*
* @return bool
*/
public static function meetsMinAPIVerRequirement()
{
$minAPIVer = static::getMinAPIVer();
if ( $minAPIVer == ''
|| Util::betterVersionCompare(static::PANEL_API_VERSION, $minAPIVer, '<') ) {
return false;
}
return true;
}
/**
*
* @since 1.9
*
* @param string $panelAPIVer Shared code API version used by the panel
* plugin.
*
* @return int
*/
public static function checkPanelAPICompatibility( $panelAPIVer )
{
$supportedAPIVers = array(
'1.17.4.2',
'1.17.4.1',
'1.17.4',
'1.17.3',
'1.17.2',
'1.17.1.1',
'1.17.1',
'1.17.0.5',
'1.17.0.4',
'1.17.0.3',
'1.17.0.2',
'1.17.0.1',
'1.17',
'1.16.1',
'1.16.0.2',
'1.16.0.1',
'1.16',
'1.15.0.1',
'1.15',
'1.14.5',
'1.14.4.1',
'1.14.4',
'1.14.3.2',
'1.14.3.1',
'1.14.3',
'1.14.2',
'1.14.1.2',
'1.14.1.1',
'1.14.1',
'1.14.0.3',
'1.14.0.2',
'1.14.0.1',
'1.14',
'1.13.13.1',
'1.13.13',
'1.13.12',
'1.13.11.1',
'1.13.11',
'1.13.10.2',
'1.13.10.1',
'1.13.10',
'1.13.9',
'1.13.8',
'1.13.7.1',
'1.13.7',
'1.13.6',
'1.13.5.2',
'1.13.5.1',
'1.13.5',
'1.13.4.4',
'1.13.4.3',
'1.13.4.2',
'1.13.4.1',
'1.13.4',
'1.13.3.1',
'1.13.3',
'1.13.2.2',
'1.13.2.1',
'1.13.2',
'1.13.1',
'1.13.0.3',
'1.13.0.2',
'1.13.0.1',
'1.13',
'1.12',
'1.11',
'1.10',
'1.9.8',
'1.9.7',
'1.9.6.1',
'1.9.6',
'1.9.5',
'1.9.4',
'1.9.3',
'1.9.2',
'1.9.1',
'1.9',
'1.8',
'1.7',
'1.6.1',
'1.6',
'1.5',
'1.4',
'1.3',
'1.2',
'1.1',
'1.0'
);
if ( Util::betterVersionCompare($panelAPIVer, $supportedAPIVers[0], '>') ) {
return static::PANEL_API_VERSION_TOO_HIGH;
}
elseif ( Util::betterVersionCompare($panelAPIVer, end($supportedAPIVers), '<') ) {
return static::PANEL_API_VERSION_TOO_LOW;
}
elseif ( ! in_array($panelAPIVer, $supportedAPIVers) ) {
return static::PANEL_API_VERSION_UNKNOWN;
}
else {
return static::PANEL_API_VERSION_SUPPORTED;
}
}
/**
*
* @deprecated 1.9 Use checkPanelAPICompatibility() instead.
*
* @param string $panelAPIVer Shared code API version used by the panel
* plugin.
*
* @return bool
*/
public static function isPanelAPICompatible( $panelAPIVer )
{
$apiCompatStatus = static::checkPanelAPICompatibility($panelAPIVer);
if ( $apiCompatStatus != static::PANEL_API_VERSION_SUPPORTED ) {
return false;
}
return true;
}
}
webcachemgr/src/Panel/Plesk.php 0000664 00000030124 15055136440 0012435 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright (c) 2018-2023
* ******************************************* */
namespace Lsc\Wp\Panel;
use Lsc\Wp\Logger;
use Lsc\Wp\LSCMException;
use Lsc\Wp\Util;
use Lsc\Wp\WPInstall;
class Plesk extends ControlPanel
{
/**
*
* @throws LSCMException Thrown indirectly by parent::__construct() call.
*/
public function __construct()
{
parent::__construct();
}
/**
*
* @since 1.13.2
*
* @throws LSCMException Thrown indirectly by parent::init2() call.
*/
protected function init2()
{
$this->panelName = 'Plesk';
$this->defaultSvrCacheRoot = '/var/www/vhosts/lscache/';
parent::init2();
}
/**
* More reliable than php_uname('s')
*
* @return string
*
* @throws LSCMException Thrown when supported Plesk OS detection command
* fails.
* @throws LSCMException Thrown when supported OS is not detected.
*/
public function getPleskOS()
{
$supportedOsList = array(
'centos',
'virtuozzo',
'cloudlinux',
'redhat',
'rhel',
'ubuntu',
'debian',
'almalinux',
'rocky'
);
$cmds = array();
if ( file_exists('/etc/debian_version') ) {
return 'debian';
}
if ( is_readable('/etc/os-release') ) {
$cmds[] = 'grep ^ID= /etc/os-release | cut -d "=" -f2 | xargs';
}
if ( is_readable('/etc/lsb-release') ) {
$cmds[] =
'grep ^DISTRIB_ID= /etc/lsb-release | cut -d "=" -f2 | xargs';
}
if ( is_readable('/etc/redhat-release') ) {
$cmds[] = 'cat /etc/redhat-release | awk \'{print $1}\'';
}
foreach ( $cmds as $cmd ) {
if ( !($output = shell_exec($cmd)) ) {
throw new LSCMException(
'Supported Plesk OS detection command failed.',
LSCMException::E_UNSUPPORTED
);
}
$OS = trim($output);
foreach ( $supportedOsList as $supportedOs ) {
if ( stripos($OS, $supportedOs) !== false ) {
return $supportedOs;
}
}
}
throw new LSCMException(
'Plesk detected with unsupported OS. '
. '(Not CentOS/Virtuozzo/Cloudlinux/RedHat/Ubuntu/Debian/'
. 'AlmaLinux/Rocky)',
LSCMException::E_UNSUPPORTED
);
}
/**
*
* @since 1.13.3
*
* @return string
*/
protected function getVhDir()
{
$vhDir = '/var/www/vhosts';
$psaConfFile = '/etc/psa/psa.conf';
if ( file_exists($psaConfFile) ) {
$ret = preg_match(
'/HTTPD_VHOSTS_D\s+(\S+)/',
file_get_contents($psaConfFile),
$m
);
if ( $ret == 1 ) {
$vhDir = $m[1];
}
}
return $vhDir;
}
/**
*
* @throws LSCMException Thrown indirectly by $this->getPleskOS() call.
*/
protected function initConfPaths()
{
$OS = $this->getPleskOS();
switch ( $OS ) {
case 'centos':
case 'virtuozzo':
case 'cloudlinux':
case 'redhat':
case 'rhel':
case 'almalinux':
case 'rocky':
$this->apacheConf = '/etc/httpd/conf.d/lscache.conf';
break;
case 'ubuntu':
$this->apacheConf = '/etc/apache2/conf-enabled/lscache.conf';
break;
case 'debian':
if ( is_dir('/etc/apache2/conf-enabled') ) {
$this->apacheConf =
'/etc/apache2/conf-enabled/lscache.conf';
}
else {
/**
* Old location.
*/
$this->apacheConf = '/etc/apache2/conf.d/lscache.conf';
}
break;
//no default case
}
$this->apacheVHConf = '/usr/local/psa/admin/conf/templates'
. '/custom/domain/domainVirtualHost.php';
}
/**
*
* @return string
*/
protected function serverCacheRootSearch()
{
$apacheConfDir = dirname($this->apacheConf);
if ( file_exists($apacheConfDir) ) {
return $this->cacheRootSearch($apacheConfDir);
}
return '';
}
/**
*
* @return string
*/
protected function vhCacheRootSearch()
{
if ( file_exists($this->apacheVHConf) ) {
return $this->getCacheRootSetting($this->apacheVHConf);
}
return '';
}
/**
*
* @param array $file_contents
* @param string $vhCacheRoot
*
* @return array
*/
protected function addVHCacheRootSection(
array $file_contents,
$vhCacheRoot = 'lscache' )
{
return preg_replace(
'!^\s*</VirtualHost>!im',
"<IfModule Litespeed>\nCacheRoot $vhCacheRoot\n</IfModule>\n"
. '</VirtualHost>',
$file_contents
);
}
/**
*
* @param string $vhConf
* @param string $vhCacheRoot
*
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
*/
public function createVHConfAndSetCacheRoot(
$vhConf,
$vhCacheRoot = 'lscache' )
{
$vhConfTmpl = '/usr/local/psa/admin/conf/templates/default/domain/'
. 'domainVirtualHost.php';
$vhConfDir = dirname($vhConf);
if ( !file_exists($vhConfDir) ) {
mkdir($vhConfDir, 0755, true);
$this->log("Created directory $vhConfDir", Logger::L_DEBUG);
}
copy($vhConfTmpl, $vhConf);
Util::matchPermissions($vhConfTmpl, $vhConf);
$this->log(
"Copied Virtual Host conf template file $vhConfTmpl to $vhConf",
Logger::L_DEBUG
);
file_put_contents(
$vhConf,
preg_replace(
'!^\s*</VirtualHost>!im',
"<IfModule Litespeed>\nCacheRoot $vhCacheRoot\n</IfModule>"
. "\n</VirtualHost>",
file($vhConf)
)
);
$this->log(
"Virtual Host cache root set to $vhCacheRoot",
Logger::L_INFO
);
}
public function applyVHConfChanges()
{
exec('/usr/local/psa/admin/bin/httpdmng --reconfigure-all');
}
/**
* Gets a list of found docroots and associated server names.
*
* Note: This function is repeated in Plesk plugin files to avoid extra
* serialize ops etc. This copy is for cli only.
*/
protected function prepareDocrootMap()
{
exec(
'grep -hro --exclude="stat_ttl.conf" --exclude="*.bak" '
. '--exclude="last_httpd.conf" '
. '"DocumentRoot.*\|ServerName.*\|ServerAlias.*" '
. "{$this->getVhDir()}/system/*/conf/*",
$lines
);
/**
* [0]=servername, [1]=serveralias, [2]=serveralias, [3]=docroot, etc.
* Not unique & not sorted.
*
* Example:
* ServerName "pltest1.com:443"
* ServerAlias "www.pltest1.com"
* ServerAlias "ipv4.pltest1.com"
* DocumentRoot "/var/www/vhosts/pltest1.com/httpdocs"
* ServerName "pltest1.com:80"
* ServerAlias "www.pltest1.com"
* ServerAlias "ipv4.pltest1.com"
* DocumentRoot "/var/www/vhosts/pltest1.com/httpdocs"
* ServerName "pltest2.com:443"
* ServerAlias "www.pltest2.com"
* ServerAlias "ipv4.pltest2.com"
* DocumentRoot "/var/www/vhosts/pltest2.com/httpdocs"
* ServerName "pltest2.com:80"
* ServerAlias "www.pltest2.com"
* ServerAlias "ipv4.pltest2.com"
* DocumentRoot "/var/www/vhosts/pltest2.com/httpdocs"
*
* @noinspection SpellCheckingInspection
*/
$x = 0;
$names = $tmpDocrootMap = array();
$lineCount = count($lines);
while ( $x < $lineCount ) {
$matchFound =
preg_match('/ServerName\s+"([^"]+)"/', $lines[$x], $m1);
if ( !$matchFound ) {
/**
* Invalid start of group, skip.
*/
$x++;
continue;
}
$UrlInfo = parse_url(
(preg_match('#^https?://#', $m1[1])) ? $m1[1] : "http://$m1[1]"
);
$names[] = $UrlInfo['host'];
$x++;
$pattern = '/ServerAlias\s+"([^"]+)"/';
while ( isset($lines[$x])
&& preg_match($pattern, $lines[$x], $m2) ) {
$names[] = $m2[1];
$x++;
}
$pattern = '/DocumentRoot\s+"([^"]+)"/';
if ( isset($lines[$x])
&& preg_match($pattern, $lines[$x], $m3) == 1
&& is_dir($m3[1]) ) {
$docroot = $m3[1];
if ( !isset($tmpDocrootMap[$docroot]) ) {
$tmpDocrootMap[$docroot] = $names;
}
else {
$tmpDocrootMap[$docroot] =
array_merge($tmpDocrootMap[$docroot], $names);
}
$x++;
}
$names = array();
}
$index = 0;
$roots = $serverNames = array();
foreach ( $tmpDocrootMap as $docroot => $names ) {
$roots[$index] = $docroot;
$names = array_unique($names);
foreach ( $names as $n ) {
$serverNames[$n] = $index;
}
$index++;
}
$this->docRootMap =
array( 'docroots' => $roots, 'names' => $serverNames );
}
/**
* Check for known Plesk PHP binaries and return the newest available
* version among them.
*
* @since 1.9.6
*
* @return string
*/
protected function getDefaultPhpBinary()
{
$binaryList = array (
'/opt/plesk/php/8.2/bin/php',
'/opt/plesk/php/8.1/bin/php',
'/opt/plesk/php/8.0/bin/php',
'/opt/plesk/php/7.4/bin/php',
'/opt/plesk/php/7.3/bin/php',
'/opt/plesk/php/7.2/bin/php',
'/opt/plesk/php/7.1/bin/php',
'/opt/plesk/php/7.0/bin/php',
'/opt/plesk/php/5.6/bin/php',
);
foreach ( $binaryList as $binary ) {
if ( file_exists($binary)) {
return $binary;
}
}
return '';
}
/**
*
* @param WPInstall $wpInstall
*
* @return string
*/
public function getPhpBinary( WPInstall $wpInstall )
{
$serverName = $wpInstall->getData(WPInstall::FLD_SERVERNAME);
if ( $serverName != null ) {
$output = shell_exec(
'plesk db -Ne "SELECT s.value '
. 'FROM ((domains d INNER JOIN hosting h ON h.dom_id=d.id) '
. 'INNER JOIN ServiceNodeEnvironment s '
. 'ON h.php_handler_id=s.name) '
. 'WHERE d.name=' . escapeshellarg($serverName)
. ' AND s.section=\'phphandlers\'" '
. '| sed -n \'s:.*<clipath>\(.*\)</clipath>.*:\1:p\''
);
if ( $output ) {
$binPath = trim($output);
}
}
if ( !empty($binPath) ) {
$phpBin = $binPath;
}
elseif ( ($defaultBinary = $this->getDefaultPHPBinary()) != '' ) {
$phpBin = $defaultBinary;
}
else {
$phpBin = 'php';
}
return "$phpBin $this->phpOptions";
}
}
webcachemgr/src/Panel/DirectAdmin.php 0000664 00000036237 15055136440 0013555 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2019-2024 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\Panel;
use DirectoryIterator;
use Lsc\Wp\Logger;
use Lsc\Wp\LSCMException;
use Lsc\Wp\WPInstall;
class DirectAdmin extends ControlPanel
{
protected function __construct()
{
/** @noinspection PhpUnhandledExceptionInspection */
parent::__construct();
}
/**
*
* @since 1.13.2
*/
protected function init2()
{
$this->panelName = 'DirectAdmin';
$this->defaultSvrCacheRoot = '/home/lscache/';
/** @noinspection PhpUnhandledExceptionInspection */
parent::init2();
}
protected function initConfPaths()
{
$this->apacheConf = '/etc/httpd/conf/extra/httpd-includes.conf';
$this->apacheVHConf = '/usr/local/directadmin/data/templates/custom/'
. 'cust_httpd.CUSTOM.2.pre';
}
/**
*
* @return string
*/
protected function serverCacheRootSearch()
{
if ( !file_exists($this->apacheConf) ) {
return '';
}
return $this->getCacheRootSetting($this->apacheConf);
}
/**
*
* @return string
*/
protected function vhCacheRootSearch()
{
$apacheUserdataDir = dirname($this->apacheVHConf);
if ( !file_exists($apacheUserdataDir) ) {
return '';
}
return $this->daVhCacheRootSearch($apacheUserdataDir);
}
/**
* Searches the given directories '.pre' and '.post' files for CacheRoot
* setting.
*
* @param string $confDir Directory to be searched.
*
* @return string
*/
public function daVhCacheRootSearch( $confDir )
{
if ( !is_dir($confDir) ) {
return '';
}
$files = new DirectoryIterator($confDir);
foreach ( $files as $file ) {
$filename = $file->getFilename();
$isPreOrPostFile = (
strlen($filename) > 4
&&
(
substr_compare($filename, '.pre', -4) === 0
||
substr_compare($filename, '.post', -5) === 0
)
);
if ( $isPreOrPostFile ) {
$cacheRoot = $this->getCacheRootSetting($file->getPathname());
if ( $cacheRoot != '' ) {
return $cacheRoot;
}
}
}
return '';
}
/**
*
* @param array $file_contents
* @param string $vhCacheRoot
*
* @return array
*/
protected function addVHCacheRootSection(
array $file_contents,
$vhCacheRoot = 'lscache' )
{
array_unshift(
$file_contents,
"<IfModule LiteSpeed>\nCacheRoot $vhCacheRoot\n</IfModule>\n\n"
);
return $file_contents;
}
/**
*
* @param string $vhConf
* @param string $vhCacheRoot
*
* @throws LSCMException Thrown when mkdir() call fails to create virtual
* host conf directory.
* @throws LSCMException Thrown when file_put_contents() call fails to
* create virtual host conf file.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
*/
public function createVHConfAndSetCacheRoot(
$vhConf,
$vhCacheRoot = 'lscache' )
{
$vhConfDir = dirname($vhConf);
if ( !file_exists($vhConfDir) ) {
if ( !mkdir($vhConfDir, 0755) ) {
throw new LSCMException(
"Failed to create directory $vhConfDir."
);
}
$this->log("Created directory $vhConfDir", Logger::L_DEBUG);
}
$bytesWrittenToFile = file_put_contents(
$vhConf,
"<IfModule Litespeed>\nCacheRoot $vhCacheRoot\n</IfModule>"
);
if ( false === $bytesWrittenToFile ) {
throw new LSCMException("Failed to create file $vhConf.");
}
$this->log("Created file $vhConf.", Logger::L_DEBUG);
}
public function applyVHConfChanges()
{
exec('/usr/local/directadmin/custombuild/build rewrite_confs');
}
/**
*
* @since 1.13.7
*
* @return array[]
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
private function getHttpdConfDocrootMapInfo()
{
exec(
'grep -hros "DocumentRoot.*\|ServerAlias.*\|ServerName.*" '
. '/usr/local/directadmin/data/users/*/httpd.conf',
$lines
);
/**
* [0]=servername, [1]=serveraliases, [2]=docroot, [3]=servername, etc.
* Not unique & not sorted.
*
* Example:
* ServerName www.daruby1.com
* ServerAlias www.daruby1.com daruby1.com
* DocumentRoot /home/daruby1/domains/daruby1.com/public_html
* ServerName www.daruby1.com
* ServerAlias www.daruby1.com daruby1.com
* DocumentRoot /home/daruby1/domains/daruby1.com/private_html
* ServerName www.dauser1.com
* ServerAlias www.dauser1.com dauser1.com
* DocumentRoot /home/dauser1/domains/dauser1.com/public_html
* ServerName www.dauser1.com
* ServerAlias www.dauser1.com dauser1.com
* DocumentRoot /home/dauser1/domains/dauser1.com/private_html
*
* @noinspection SpellCheckingInspection
*/
$docRoots = array();
$curServerName = $curServerAliases = '';
foreach ( $lines as $line ) {
if ( $curServerName == '' ) {
if ( strpos($line, 'ServerName') === 0 ) {
/**
* 10 is strlen('ServerName')
*/
$curServerName = trim(substr($line, 10));
}
}
elseif ( strpos($line, 'ServerAlias') === 0 ) {
/**
* 11 is strlen('ServerAlias')
*/
$curServerAliases = trim(substr($line, 11));
}
elseif ( strpos($line, 'DocumentRoot') === 0 ) {
/**
* 12 is strlen('DocumentRoot')
*/
$curDocRoot = trim(substr($line, 12), " \n\r\t\v\x00\"");
/**
* Avoid possible duplicate detections due to
* public_html/private_html symlinks.
*/
if ( !isset($docRoots[$curDocRoot])
&& is_dir($curDocRoot)
&& !is_link($curDocRoot) ) {
$docRoots[$curDocRoot] = explode(' ', $curServerAliases);
$docRoots[$curDocRoot][] = $curServerName;
}
/**
* Looking for the next data set
*/
$curServerName = $curServerAliases = '';
}
else {
Logger::debug("Unused line when preparing docroot map: $line.");
}
}
return $docRoots;
}
/**
*
* @since 1.13.7
*
* @return array[]
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
private function getOpenlitespeedConfDocrootMapInfo()
{
exec(
'grep -hros "docRoot.*\|vhDomain.*\|vhAliases.*" '
. '/usr/local/directadmin/data/users/*/openlitespeed.conf',
$lines
);
/**
* [0]=docroot, [1]=servername, [2]=serveraliases, [3]=docroot, etc.
* Not unique & not sorted.
*
* Example:
* docRoot /home/test/domains/test.com/public_html
* vhDomain test.com
* vhAliases www.test.com
* docRoot /home/test/domains/test.com/public_html
* vhDomain testalias.com
* vhAliases www.testalias.com
* docRoot /home/test/domains/test.com/private_html
* vhDomain test.com
* vhAliases www.test.com
* docRoot /home/test/domains/test.com/private_html
* vhDomain testalias.com
* vhAliases www.testalias.com
* docRoot /home/test_2/domains/test2.com/public_html
* vhDomain test2.com
* vhAliases www.test2.com
* docRoot /home/test_2/domains/test2.com/private_html
* vhDomain test2.com
* vhAliases www.test2.com
*
* @noinspection SpellCheckingInspection
*/
$docRoots = array();
$curServerName = $curDocRoot = '';
foreach ( $lines as $line ) {
if ( $curDocRoot == '' ) {
if ( strpos($line, 'docRoot') === 0 ) {
/**
* 7 is strlen('docRoot')
*/
$curDocRoot = trim(substr($line, 7));
}
}
elseif ( strpos($line, 'vhDomain') === 0 ) {
/**
* 8 is strlen('vhDomain')
*/
$curServerName = trim(substr($line, 8));
}
elseif ( strpos($line, 'vhAliases') === 0 ) {
/**
* 9 is strlen('vhAliases')
*/
$curServerAlias = trim(substr($line, 9));
/**
* Avoid possible duplicate detections due to
* public_html/private_html symlinks.
*/
if ( is_dir($curDocRoot) && !is_link($curDocRoot) ) {
if ( !isset($docRoots[$curDocRoot]) ) {
$docRoots[$curDocRoot] =
array( $curServerName, $curServerAlias );
}
else {
if ( !in_array($curServerName, $docRoots[$curDocRoot]) ) {
$docRoots[$curDocRoot][] = $curServerName;
}
if ( !in_array($curServerAlias, $docRoots[$curDocRoot]) ) {
$docRoots[$curDocRoot][] = $curServerAlias;
}
}
}
/**
* Looking for the next data set
*/
$curDocRoot = $curServerName = '';
}
else {
Logger::debug("Unused line when preparing docroot map: $line.");
}
}
return $docRoots;
}
/**
* Gets a list of found docroots and associated server names.
* Only needed for scan operation.
*
* @throws LSCMException Thrown indirectly by
* $this->getHttpdConfDocrootMapInfo() call.
* @throws LSCMException Thrown indirectly by
* $this->getOpenlitespeedConfDocrootMapInfo() call.
*/
protected function prepareDocrootMap()
{
$docRootMapInfo = $this->getHttpdConfDocrootMapInfo();
$openlitespeedConfDocrootMapInfo =
$this->getOpenlitespeedConfDocrootMapInfo();
foreach ( $openlitespeedConfDocrootMapInfo as $oDocRoot => $oDomains ) {
if ( !isset($docRootMapInfo[$oDocRoot]) ) {
$docRootMapInfo[$oDocRoot] = $oDomains;
}
else {
foreach ( $oDomains as $oDomain ) {
if ( !in_array($oDomain, $docRootMapInfo[$oDocRoot]) ) {
$docRootMapInfo[$oDocRoot][] = $oDomain;
}
}
}
}
$roots = array();
$servernames = array();
$index = 0;
foreach ( $docRootMapInfo as $docRoot => $domains ) {
$domains = array_unique($domains);
$roots[$index] = $docRoot;
foreach ( $domains as $domain ) {
$servernames[$domain] = $index;
}
$index++;
}
$this->docRootMap =
array( 'docroots' => $roots, 'names' => $servernames );
}
/**
* Check the user's httpd.conf file for a VirtualHost entry containing a
* given servername/docroot combination and return the PHP handler version
* if set.
*
* @param WPInstall $wpInstall
*
* @return string
*
* @throws LSCMException Thrown when a valid user data conf file could not
* be found.
*/
protected function getCustomPhpHandlerVer( WPInstall $wpInstall )
{
if ( ($serverName = $wpInstall->getServerName()) == null
|| ($docroot = $wpInstall->getDocRoot()) == null ) {
return '';
}
$escServerName = str_replace('.', '\.', $serverName);
$escDocRoot =
str_replace(array('.', '/'), array('\.', '\/'), $docroot);
$user = $wpInstall->getOwnerInfo('user_name');
$httpdConfFile = "/usr/local/directadmin/data/users/$user/httpd.conf";
$olsConfFile =
"/usr/local/directadmin/data/users/$user/openlitespeed.conf";
if ( file_exists($httpdConfFile) ) {
$confFile = $httpdConfFile;
$pattern = '/VirtualHost'
. '(?:(?!<\/VirtualHost).)*'
. "ServerName $escServerName"
. '(?:(?!<\/VirtualHost).)*'
. "DocumentRoot $escDocRoot"
. '(?:(?!<\/VirtualHost).)*'
. 'AddHandler.* \.php(\d\d)/sU';
}
elseif ( file_exists($olsConfFile) ) {
$confFile = $olsConfFile;
$pattern = '/virtualHost\s'
. '(?:(?!}\s*\n*virtualHost).)*?'
. '{'
. '(?:(?!}\s*\n*virtualHost).)*?'
. "(?:\s|\n)docRoot\s+$escDocRoot(?:\s|\n)"
. '(?:(?!}\s*\n*virtualHost).)*?'
. "(?:\s|\n)vhDomain\s+$escServerName(?:\s|\n)"
. '(?:(?!}\s*\n*virtualHost).)*?'
. '(?:\s|\n)scripthandler(?:\s|\n)*{'
. '(?:(?!}\s*\n*virtualHost).)*?'
. '\sphp(\d\d)(?=\s|\n)/s';
}
else {
throw new LSCMException('Could not find valid user data conf file');
}
if ( preg_match($pattern, file_get_contents($confFile), $m) ) {
return $m[1];
}
return '';
}
/**
*
* @param WPInstall $wpInstall
*
* @return string
*
* @throws LSCMException Thrown indirectly by
* $this->getCustomPhpHandlerVer() call.
*/
public function getPhpBinary( WPInstall $wpInstall )
{
$phpBin = '/usr/local/bin/php';
if ( ($ver = $this->getCustomPhpHandlerVer($wpInstall)) != '' ) {
$customBin = "/usr/local/php$ver/bin/php";
if ( file_exists($customBin) && is_executable($customBin) ) {
$phpBin = $customBin;
}
}
return "$phpBin $this->phpOptions";
}
}
webcachemgr/src/Panel/CPanel.php 0000664 00000057704 15055136440 0012536 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2017-2023 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\Panel;
use Lsc\Wp\Logger;
use Lsc\Wp\LSCMException;
use Lsc\Wp\Util;
use Lsc\Wp\WPInstall;
class CPanel extends ControlPanel
{
/**
* @var string
*/
const USER_PLUGIN_INSTALL_SCRIPT = '/usr/local/cpanel/whostmgr/docroot/cgi/lsws/res/ls_web_cache_mgr/install.sh';
/**
* @deprecated 1.13.11 Split into paper_lantern and jupiter theme specific
* constants.
* @since 1.13.2
* @var string
*/
const USER_PLUGIN_DIR = '/usr/local/cpanel/base/frontend/paper_lantern/ls_web_cache_manager';
/**
* @since 1.13.11
* @var string
*/
const THEME_JUPITER_USER_PLUGIN_DIR = '/usr/local/cpanel/base/frontend/jupiter/ls_web_cache_manager';
/**
* @since 1.13.11
* @var string
*/
const THEME_PAPER_LANTERN_USER_PLUGIN_DIR = '/usr/local/cpanel/base/frontend/paper_lantern/ls_web_cache_manager';
/**
* @deprecated 1.13.11 No longer used.
* @var string
*/
const USER_PLUGIN_UNINSTALL_SCRIPT = self::USER_PLUGIN_DIR . '/uninstall.sh';
/**
* @since 1.13.11
* @var string
*/
const USER_PLUGIN_RELATIVE_UNINSTALL_SCRIPT = 'uninstall.sh';
/**
* @since 1.13.2
* @var string
*/
const USER_PLUGIN_BACKUP_DIR = '/tmp/lscp-plugin-tmp';
/**
* @since 1.13.11
* @var string
*/
const USER_PLUGIN_RELATIVE_DATA_DIR = 'data';
/**
* @deprecated 1.13.11
* @since 1.13.2
* @var string An old location for cPanel user-end plugin conf file.
*/
const USER_PLUGIN_CONF_OLD = self::USER_PLUGIN_DIR . '/lswcm.conf';
/**
* @since 1.13.11
* @var string
*/
const USER_PLUGIN_RELATIVE_CONF_OLD = '/lswcm.conf';
/**
* @since 1.13.11
* @var string
*/
const USER_PLUGIN_RELATIVE_CONF_OLD_2 = self::USER_PLUGIN_RELATIVE_DATA_DIR . '/lswcm.conf';
/**
* @var string
*/
const USER_PLUGIN_CONF = '/usr/local/cpanel/3rdparty/ls_webcache_mgr/lswcm.conf';
/**
* @var string
*/
const CPANEL_AUTOINSTALL_DISABLE_FLAG = '/usr/local/cpanel/whostmgr/docroot/cgi/lsws/cpanel_autoinstall_off';
/**
* @var string
*/
const USER_PLUGIN_SETTING_VHOST_CACHE_ROOT = 'vhost_cache_root';
/**
* @var string
*/
const USER_PLUGIN_SETTING_LSWS_DIR = 'lsws_dir';
/**
* @deprecated 1.13.11 Never used.
* @since 1.13.2
* @var string
*/
protected $cpanelPluginDataDir;
/**
* @deprecated 1.13.11 Never used.
* @since 1.13.2
* @var string
*/
protected $cpanelPluginTplDir;
/**
* @deprecated 1.13.11 Never used.
* @since 1.13.2
* @var string
*/
protected $cpanelPluginCustTransDir;
/**
* @deprecated 1.13.11 Never used.
* @since 1.13.2
* @var string
*/
protected $tmpCpanelPluginDataDir;
/**
* @since 1.13.2
* @var string
*/
protected $tmpCpanelPluginTplDir;
/**
* @since 1.13.2
* @var string
*/
protected $tmpCpanelPluginCustTransDir;
protected function __construct()
{
/** @noinspection PhpUnhandledExceptionInspection */
parent::__construct();
}
/**
*
* @since 1.13.2
*/
protected function init2()
{
$this->panelName = 'cPanel/WHM';
$this->defaultSvrCacheRoot = '/home/lscache/';
$this->tmpCpanelPluginTplDir =
self::USER_PLUGIN_BACKUP_DIR . '/landing';
$this->tmpCpanelPluginCustTransDir =
self::USER_PLUGIN_BACKUP_DIR . '/cust';
/** @noinspection PhpUnhandledExceptionInspection */
parent::init2();
}
protected function initConfPaths()
{
$this->apacheConf =
'/etc/apache2/conf.d/includes/pre_main_global.conf';
$this->apacheVHConf =
'/etc/apache2/conf.d/userdata/lscache_vhosts.conf';
}
/**
*
* @return string
*/
protected function serverCacheRootSearch()
{
if ( file_exists($this->apacheConf) ) {
return $this->getCacheRootSetting($this->apacheConf);
}
return '';
}
/**
*
* @return string
*/
protected function vhCacheRootSearch()
{
$apacheUserdataDir = dirname($this->apacheVHConf);
if ( file_exists($apacheUserdataDir) ) {
return $this->cacheRootSearch($apacheUserdataDir);
}
return '';
}
/**
*
* @param array $file_contents
* @param string $vhCacheRoot
*
* @return array
*/
protected function addVHCacheRootSection(
array $file_contents,
$vhCacheRoot = 'lscache' )
{
array_unshift(
$file_contents,
"<IfModule LiteSpeed>\nCacheRoot $vhCacheRoot\n</IfModule>\n\n"
);
return $file_contents;
}
/**
*
* @param string $vhConf
* @param string $vhCacheRoot
*
* @throws LSCMException Thrown when virtual host conf directory cannot be
* created.
* @throws LSCMException Thrown when virtual host conf file cannot be
* created.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
*/
public function createVHConfAndSetCacheRoot(
$vhConf,
$vhCacheRoot = 'lscache' )
{
$vhConfDir = dirname($vhConf);
if ( !file_exists($vhConfDir) ) {
if ( !mkdir($vhConfDir, 0755) ) {
throw new LSCMException(
"Failed to create directory $vhConfDir."
);
}
$this->log("Created directory $vhConfDir", Logger::L_DEBUG);
}
$vhConfFileCreated = (
file_put_contents(
$vhConf,
"<IfModule Litespeed>\nCacheRoot $vhCacheRoot\n</IfModule>"
)
!==
false
);
if ( !$vhConfFileCreated ) {
throw new LSCMException("Failed to create file $vhConf.");
}
$this->log("Created file $vhConf.", Logger::L_DEBUG);
}
/**
*
* @throws LSCMException Thrown indirectly by
* self::UpdateCpanelPluginConf() call.
*/
public function applyVHConfChanges()
{
exec('/scripts/ensure_vhost_includes --all-users');
if ( file_exists(self::THEME_JUPITER_USER_PLUGIN_DIR)
|| file_exists(self::THEME_PAPER_LANTERN_USER_PLUGIN_DIR) ) {
self::UpdateCpanelPluginConf(
self::USER_PLUGIN_SETTING_VHOST_CACHE_ROOT,
$this->vhCacheRoot
);
}
}
/**
* Gets a list of found docroots and associated server names.
* Only needed for scan logic.
*
* @throws LSCMException Thrown when an error is encountered by
* preg_split() call on trimmed $line value.
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*
* @noinspection SpellCheckingInspection
*/
protected function prepareDocrootMap()
{
exec(
'grep -hro '
. '--exclude="cache" --exclude="main" --exclude="*.cache" '
. '"documentroot.*\|serveralias.*\|servername.*" '
. '/var/cpanel/userdata/*',
$lines
);
/**
* [0]=docroot, [1]=serveraliases, [2]=servername, [3]=docroot, etc.
* Not unique & not sorted.
*
* Example:
* documentroot: /home/user1/finches
* serveralias: finches.com mail.finches.com www.finches.com www.finches.user1.com cpanel.finches.com autodiscover.finches.com whm.finches.com webmail.finches.com webdisk.finches.com
* servername: finches.user1.com
* documentroot: /home/user1/public_html/dookoo
* serveralias: www.dookoo.user1.com
* servername: dookoo.user1.com
* documentroot: /home/user1/public_html/doo/doo2
* serveralias: www.doo2.user1.com
* servername: doo2.user1.com
* documentroot: /home/user1/finches
* serveralias: finches.com mail.finches.com www.finches.com www.finches.user1.com
* servername: finches.user1.com
*/
$cur = '';
$docroots = array();
foreach ( $lines as $line ) {
if ( $cur == '' ) {
if ( strpos($line, 'documentroot:') === 0 ) {
/**
* 13 is strlen('documentroot:')
*/
$cur = trim(substr($line, 13));
if ( !isset($docroots[$cur]) ) {
if ( is_dir($cur) ) {
$docroots[$cur] = '';
}
else {
/**
* bad entry ignore
*/
$cur = '';
}
}
}
}
elseif ( strpos($line, 'serveralias:') === 0 ) {
/**
* 12 is strlen('serveralias:')
*/
$docroots[$cur] .= substr($line, 12);
}
elseif ( strpos($line, 'servername:') === 0 ) {
/**
* 11 is strlen('servername:')
*/
$docroots[$cur] .= substr($line, 11);
/**
* looking for the next docroot
*/
$cur = '';
}
else {
Logger::debug("Unused line when preparing docroot map: $line.");
}
}
$roots = array();
$servernames = array();
$index = 0;
foreach ( $docroots as $docroot => $line ) {
$names = preg_split('/\s+/', trim($line), -1, PREG_SPLIT_NO_EMPTY);
if ( $names === false ) {
throw new LSCMException(
'prepareDocrootMap(): Error encountered when calling '
. 'preg_split() on trimmed $line.'
);
}
$names = array_unique($names);
$roots[$index] = $docroot;
foreach ( $names as $n ) {
$servernames[$n] = $index;
}
$index++;
}
$this->docRootMap =
array( 'docroots' => $roots, 'names' => $servernames );
}
/**
*
* @param WPInstall $wpInstall
*
* @return string
*/
public function getPhpBinary( WPInstall $wpInstall )
{
/**
* cPanel php wrapper should accurately detect the correct binary in
* EA4 when EA4 only directive '--ea-reference-dir' is provided.
*/
return '/usr/local/bin/php '
. "--ea-reference-dir={$wpInstall->getPath()}/wp-admin "
. $this->phpOptions;
}
/**
*
* @return bool
*/
public static function isCpanelPluginAutoInstallOn()
{
if ( file_exists(self::CPANEL_AUTOINSTALL_DISABLE_FLAG) ) {
return false;
}
return true;
}
/**
*
* @return bool
*/
public static function turnOnCpanelPluginAutoInstall()
{
if ( !file_exists(self::CPANEL_AUTOINSTALL_DISABLE_FLAG) ) {
return true;
}
return unlink(self::CPANEL_AUTOINSTALL_DISABLE_FLAG);
}
/**
*
* @return bool
*/
public static function turnOffCpanelPluginAutoInstall()
{
return touch(self::CPANEL_AUTOINSTALL_DISABLE_FLAG);
}
/**
*
* @return string
*
* @throws LSCMException Thrown when unable to find cPanel user-end plugin
* installation script.
* @throws LSCMException Thrown when failing to back up cPanel user-end
* plugin data files.
* @throws LSCMException Thrown indirectly by
* self::backupCpanelPluginDataFiles() call.
* @throws LSCMException Thrown indirectly by Logger::error() call.
*/
public function installCpanelPlugin()
{
if ( !file_exists(self::USER_PLUGIN_INSTALL_SCRIPT) ) {
throw new LSCMException(
'Unable to find cPanel user-end plugin installation script.'
. ' Please ensure that the LiteSpeed WHM plugin is already '
. 'installed.'
);
}
$existingInstall = (
file_exists(self::THEME_JUPITER_USER_PLUGIN_DIR)
|| file_exists(self::THEME_PAPER_LANTERN_USER_PLUGIN_DIR)
);
if ( $existingInstall ) {
if ( !self::backupCpanelPluginDataFiles() ) {
throw new LSCMException(
'Failed to backup cPanel user-end plugin data files. '
. 'Aborting install/update operation.'
);
}
exec(self::USER_PLUGIN_INSTALL_SCRIPT);
if ( !self::restoreCpanelPluginDataFiles() ) {
Logger::error(
'Failed to restore cPanel user-end plugin data files.'
);
}
}
else {
exec(self::USER_PLUGIN_INSTALL_SCRIPT);
self::turnOnCpanelPluginAutoInstall();
}
$this->updateCoreCpanelPluginConfSettings();
return ($existingInstall) ? 'update' : 'new';
}
/**
*
* @since 1.13.2
* @since 1.13.2.2 Made function static.
* @since 1.13.5.2 Removed optional param $oldLogic.
*
* @return bool
*
* @throws LSCMException Thrown when failing to create a temporary backup
* directory.
*/
protected static function backupCpanelPluginDataFiles()
{
if ( file_exists(self::THEME_JUPITER_USER_PLUGIN_DIR) ) {
$pluginDir = self::THEME_JUPITER_USER_PLUGIN_DIR;
}
elseif ( file_exists(self::THEME_PAPER_LANTERN_USER_PLUGIN_DIR) ) {
$pluginDir = self::THEME_PAPER_LANTERN_USER_PLUGIN_DIR;
}
else {
return false;
}
if ( file_exists(self::USER_PLUGIN_BACKUP_DIR) ) {
Util::rrmdir(self::USER_PLUGIN_BACKUP_DIR);
}
if ( !mkdir(self::USER_PLUGIN_BACKUP_DIR, 0755) ) {
throw new LSCMException(
'Failed to make temporary directory '
. self::USER_PLUGIN_BACKUP_DIR
);
}
/**
* Move existing conf file (if needed), templates, and custom
* translations to temp directory and remove default template dir to
* prevent overwriting when moving back.
*/
$activeConfFile =
self::getInstalledCpanelPluginActiveConfFileLocation($pluginDir);
if ( $activeConfFile == '' || !file_exists($activeConfFile) ) {
return false;
}
$backupCmds = '';
if ( $activeConfFile != self::USER_PLUGIN_CONF ) {
$backupCmds .= "/bin/mv $activeConfFile "
. self::USER_PLUGIN_BACKUP_DIR . '/;';
}
$tmpCpanelPluginCustTransDir = self::USER_PLUGIN_BACKUP_DIR . '/cust';
$backupCmds .= '/bin/mv '
. "$pluginDir/landing " . self::USER_PLUGIN_BACKUP_DIR . '/;'
. "/bin/rm -rf "
. self::USER_PLUGIN_BACKUP_DIR . '/landing/default;'
. '/bin/mv '
. "$pluginDir/lang/cust $tmpCpanelPluginCustTransDir;"
. "/bin/rm -rf $tmpCpanelPluginCustTransDir/README";
exec($backupCmds);
return true;
}
/**
*
* @since 1.13.2
* @since 1.13.2.2 Made function static.
* @since 1.13.5.2 Removed optional param $oldLogic.
*
* @return bool
*/
protected static function restoreCpanelPluginDataFiles()
{
$pluginInstalls = array();
if ( file_exists(self::THEME_JUPITER_USER_PLUGIN_DIR) ) {
$pluginInstalls[] = self::THEME_JUPITER_USER_PLUGIN_DIR;
}
if ( file_exists(self::THEME_PAPER_LANTERN_USER_PLUGIN_DIR) ) {
$pluginInstalls[] = self::THEME_PAPER_LANTERN_USER_PLUGIN_DIR;
}
if ( !file_exists(self::USER_PLUGIN_BACKUP_DIR)
|| empty($pluginInstalls) ) {
return false;
}
$tmpCpanelPluginConfFile = self::USER_PLUGIN_BACKUP_DIR . '/lswcm.conf';
foreach ( $pluginInstalls as $pluginInstall ) {
$cpanelPluginLangDir = "$pluginInstall/lang";
if (!file_exists($cpanelPluginLangDir)) {
mkdir($cpanelPluginLangDir, 0755);
}
if ( file_exists($tmpCpanelPluginConfFile) ) {
$activeConfFile = self::getInstalledCpanelPluginActiveConfFileLocation(
$pluginInstall
);
if ($activeConfFile == '') {
return false;
}
copy($tmpCpanelPluginConfFile, $activeConfFile);
chmod($activeConfFile, 0644);
}
/**
* Replace cPanel plugin templates, custom translations.
*/
exec(
'/bin/cp -prf '
. self::USER_PLUGIN_BACKUP_DIR . "/landing $pluginInstall/;"
. '/bin/cp -prf '
. self::USER_PLUGIN_BACKUP_DIR
. "/cust $cpanelPluginLangDir/"
);
}
exec('/bin/rm -rf ' . self::USER_PLUGIN_BACKUP_DIR);
return true;
}
/**
*
* @since 1.13.2.2 Made function static.
*
* @throws LSCMException Thrown when unable to find the uninstallation
* script.
*/
public static function uninstallCpanelPlugin()
{
$jupiterUninstallFile = self::THEME_JUPITER_USER_PLUGIN_DIR . '/'
. self::USER_PLUGIN_RELATIVE_UNINSTALL_SCRIPT;
$paperLanternUninstallFile = self::THEME_PAPER_LANTERN_USER_PLUGIN_DIR
. '/' . self::USER_PLUGIN_RELATIVE_UNINSTALL_SCRIPT;
if ( file_exists($jupiterUninstallFile) ) {
$uninstallFile = $jupiterUninstallFile;
}
elseif ( file_exists($paperLanternUninstallFile) ) {
$uninstallFile = $paperLanternUninstallFile;
}
else {
throw new LSCMException(
'Unable to find cPanel user-end plugin uninstallation script. '
. 'Plugin may already be uninstalled.'
);
}
exec($uninstallFile);
self::turnOffCpanelPluginAutoInstall();
}
/**
* Attempt to update core cPanel plugin settings used for basic plugin
* operation to the currently discovered values.
*
* @since 1.13.2.2
* @since 1.13.5 Changed function visibility to public.
*
* @throws LSCMException Thrown indirectly by
* self::UpdateCpanelPluginConf() call.
* @throws LSCMException Thrown indirectly by $this->getVHCacheRoot() call.
* @throws LSCMException Thrown indirectly by
* self::UpdateCpanelPluginConf() call.
*/
public function updateCoreCpanelPluginConfSettings()
{
self::UpdateCpanelPluginConf(
self::USER_PLUGIN_SETTING_LSWS_DIR,
realpath(__DIR__ . '/../../../..')
);
self::UpdateCpanelPluginConf(
self::USER_PLUGIN_SETTING_VHOST_CACHE_ROOT,
$this->getVHCacheRoot()
);
}
/**
*
* @since 1.13.2.2 Made function static.
*
* @param string $setting
* @param mixed $value
*
* @throws LSCMException Thrown when unable to determine active cPanel
* user-end plugin conf file location usually indicating that the
* cPanel user-end plugin is not currently installed.
* @throws LSCMException Thrown when unable to create cPanel user-end
* plugin "data" directory for older versions of the cPanel user-end
* plugin that require this directory.
*/
public static function UpdateCpanelPluginConf( $setting, $value )
{
$pluginInstalls = array();
if ( file_exists(self::THEME_JUPITER_USER_PLUGIN_DIR) ) {
$pluginInstalls[] = self::THEME_JUPITER_USER_PLUGIN_DIR;
}
else {
$pluginInstalls[] = self::THEME_PAPER_LANTERN_USER_PLUGIN_DIR;
}
foreach ( $pluginInstalls as $pluginInstall ) {
$activeConfFile = self::getInstalledCpanelPluginActiveConfFileLocation(
$pluginInstall
);
if ( $activeConfFile == '' ) {
throw new LSCMException(
'Unable to determine active conf file location for cPanel '
. 'user-end plugin. cPanel user-end plugin is likely '
. 'not installed.'
);
}
if ( !file_exists($activeConfFile) ) {
$oldConf = '';
if ( file_exists("$pluginInstall/" . self::USER_PLUGIN_RELATIVE_CONF_OLD_2) ) {
$oldConf = "$pluginInstall/" . self::USER_PLUGIN_RELATIVE_CONF_OLD_2;
}
elseif ( file_exists("$pluginInstall/" . self::USER_PLUGIN_RELATIVE_CONF_OLD) ) {
$oldConf = "$pluginInstall/" . self::USER_PLUGIN_RELATIVE_CONF_OLD;
}
if ( $oldConf != '' ) {
$dataDir =
"$pluginInstall/" . self::USER_PLUGIN_RELATIVE_DATA_DIR;
if ( $activeConfFile == "$pluginInstall/" . self::USER_PLUGIN_RELATIVE_CONF_OLD_2
&& !file_exists($dataDir)
&& !mkdir($dataDir) ) {
throw new LSCMException(
"Failed to create directory $dataDir."
);
}
copy($oldConf, $activeConfFile);
}
}
if ( file_exists($activeConfFile) ) {
chmod($activeConfFile, 0644);
switch ( $setting ) {
case self::USER_PLUGIN_SETTING_LSWS_DIR:
$pattern = '/LSWS_HOME_DIR = ".*"/';
$replacement = "LSWS_HOME_DIR = \"$value\"";
break;
case self::USER_PLUGIN_SETTING_VHOST_CACHE_ROOT:
$pattern = '/VHOST_CACHE_ROOT = ".*"/';
$replacement = "VHOST_CACHE_ROOT = \"$value\"";
break;
default:
return;
}
$content = file_get_contents($activeConfFile);
if ( preg_match($pattern, $content) ) {
file_put_contents(
$activeConfFile,
preg_replace($pattern, $replacement, $content)
);
}
else {
file_put_contents(
$activeConfFile,
$replacement,
FILE_APPEND
);
}
}
}
}
/**
*
* @since 1.13.11
*
* @param string $pluginDir
*
* @return string
*/
protected static function getInstalledCpanelPluginActiveConfFileLocation(
$pluginDir )
{
$versionFile = "$pluginDir/VERSION";
if ( file_exists($versionFile) ) {
$verGreaterThan2_1_2_2 = Util::betterVersionCompare(
file_get_contents($versionFile),
'2.1.2.2',
'>'
);
if ( $verGreaterThan2_1_2_2 ) {
return self::USER_PLUGIN_CONF;
}
}
if ( file_exists("$pluginDir/" . self::USER_PLUGIN_RELATIVE_DATA_DIR) ) {
return "$pluginDir/" . self::USER_PLUGIN_RELATIVE_CONF_OLD_2;
}
if ( file_exists($pluginDir) ) {
return "$pluginDir/" . self::USER_PLUGIN_RELATIVE_CONF_OLD;
}
return '';
}
}
webcachemgr/src/Panel/CustomPanel.php 0000664 00000004767 15055136440 0013627 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright (c) 2020
* ******************************************* */
namespace Lsc\Wp\Panel;
use Lsc\Wp\WPInstall;
class CustomPanel
extends CustomPanelBase
{
protected function __construct()
{
/**
* Panel name can be set to whatever you'd like.
*/
$this->panelName = 'customPanel';
/** @noinspection PhpUnhandledExceptionInspection */
parent::__construct();
}
/**
*
* @since 1.13.2
*/
protected function init2()
{
$this->panelName = 'customPanel';
/** @noinspection PhpUnhandledExceptionInspection */
parent::init2();
}
/**
* Gets a list of found docroots and associated server names.
* Only needed for lscmctl 'scan' command.
*/
protected function prepareDocrootMap()
{
/**
* This function can be left as is if you do not intend to use
* the lscmctl 'scan' command. In this case lscmctl command
* 'addinstalls' can be used to add WordPress installations to the
* custom data file instead.
*
* If you would like to add support for the lscmctl 'scan' command,
* implement this function so that it searches for all document root,
* server name, and server alias groups and uses this information to
* populate $this->docRootMap as follows:
*
* array(
* 'docroots' => array(index => docroot),
* 'names' => array("server name/alias" => index)
* );
*
* Where the value of each discovered servername/alias in the 'names'
* array matches the index of the related document root in the
* 'docroots' array.
*/
$this->docRootMap = array('docroots' => array(), 'names' => array());
}
/**
* This function returns the PHP binary to be used when performing
* WordPress related actions for the WordPress installation associated with
* the passed in WPInstall object.
*
* @param WPInstall $wpInstall
* @return string
*/
public function getPhpBinary( WPInstall $wpInstall )
{
/**
* If PHP binary $phpBin can be more accurately detected for the given
* installation, do so here.
*/
$phpBin = 'php';
return "{$phpBin} {$this->phpOptions}";
}
}
webcachemgr/src/Panel/CustomPanelBase.php 0000664 00000002130 15055136440 0014400 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright (c) 2020-2023
* @since 1.10
* ******************************************* */
namespace Lsc\Wp\Panel;
abstract class CustomPanelBase
extends ControlPanel
{
/**
* The following functions deal with apache configuration files and
* server/virtual host cache roots and will never be called in the
* CustomPanel context. They are included here to meet abstract function
* requirements in parent class ControlPanel.
*
*/
protected function initConfPaths()
{}
protected function serverCacheRootSearch()
{}
protected function vhCacheRootSearch()
{}
protected function addVHCacheRootSection(
array $file_contents,
$vhCacheRoot = 'lscache' )
{}
public function verifyCacheSetup()
{}
public function createVHConfAndSetCacheRoot(
$vhConf,
$vhCacheRoot = 'lscache' )
{}
public function applyVHConfChanges()
{}
}
webcachemgr/src/WPInstallStorage.php 0000664 00000102362 15055136440 0013526 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2018-2025 LiteSpeed Technologies, Inc.
* *******************************************
*/
namespace Lsc\Wp;
use Lsc\Wp\Context\Context;
use Lsc\Wp\Panel\ControlPanel;
use Lsc\Wp\ThirdParty\Polyfill\Utf8;
/**
* map to data file
*/
class WPInstallStorage
{
/**
* @var string
*/
const CMD_ADD_CUST_WPINSTALLS = 'addCustWPInstalls';
/**
* @since 1.13.3
* @var string
*/
const CMD_ADD_NEW_WPINSTALL = 'addNewWPInstall';
/**
* @deprecated 1.13.3 Use CMD_DISCOVER_NEW2 instead.
* @var string
*/
const CMD_DISCOVER_NEW = 'discoverNew';
/**
* @since 1.14
* @var string
*/
const CMD_DISCOVER_NEW_AND_ENABLE = 'discoverNewAndEnable';
/**
* @since 1.13.3
* @var string
*/
const CMD_DISCOVER_NEW2 = 'discoverNew2';
/**
* @var string
*/
const CMD_FLAG = 'flag';
/**
* @var string
*/
const CMD_MASS_FLAG = 'mass_flag';
/**
* @var string
*/
const CMD_MASS_UNFLAG = 'mass_unflag';
/**
* @deprecated 1.13.3 Use CMD_SCAN2 instead for now.
* @var string
*/
const CMD_SCAN = 'scan';
/**
* @since 1.13.3
* @var string
*/
const CMD_SCAN2 = 'scan2';
/**
* @var string
*/
const CMD_UNFLAG = 'unflag';
/**
* @var string
*/
const DATA_VERSION = '1.5';
/**
* @var int
*/
const ERR_NOT_EXIST = 1;
/**
* @var int
*/
const ERR_CORRUPTED = 2;
/**
* @var int
*/
const ERR_VERSION_HIGH = 3;
/**
* @var int
*/
const ERR_VERSION_LOW = 4;
/**
* @var string
*/
protected $dataFile;
/**
* @var string
*/
protected $customDataFile;
/**
* @var null|WPInstall[] Key is the path to a WordPress installation.
*/
protected $wpInstalls = null;
/**
* @var null|WPInstall[] Key is the path to a WordPress installation.
*/
protected $custWpInstalls = null;
/**
* @var int
*/
protected $error;
/**
* @var WPInstall[]
*/
protected $workingQueue = [];
/**
*
* @param string $dataFile
* @param string $custDataFile
*
* @throws LSCMException Thrown indirectly by $this->init() call.
*/
public function __construct( $dataFile, $custDataFile = '' )
{
$this->dataFile = $dataFile;
$this->customDataFile = $custDataFile;
$this->error = $this->init();
}
/**
*
* @return int
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function init()
{
$dataExists = false;
try {
if ( file_exists($this->dataFile) ) {
$dataExists = true;
$this->wpInstalls = $this->getDataFileData($this->dataFile);
}
if (
$this->customDataFile != ''
&&
file_exists($this->customDataFile)
) {
$dataExists = true;
$this->custWpInstalls =
$this->getDataFileData($this->customDataFile);
}
}
catch ( LSCMException $e ) {
Logger::debug($e->getMessage());
return $e->getCode();
}
if ( !$dataExists ) {
return self::ERR_NOT_EXIST;
}
return 0;
}
/**
*
* @since 1.15
*
* @param string $dataFile
*
* @return false|string
*/
protected static function getDataFileContents( $dataFile )
{
return file_get_contents($dataFile);
}
/**
*
* @param string $dataFile
*
* @return WPInstall[]
*
* @throws LSCMException Thrown when data file is corrupt.
* @throws LSCMException Thrown when there is a data file version issue.
* @throws LSCMException Thrown indirectly by $this->verifyDataFileVer()
* call.
*/
protected function getDataFileData( $dataFile )
{
$content = static::getDataFileContents($dataFile);
if ( ($data = json_decode($content, true)) === null ) {
/**
* Data file may be in old serialized format. Try unserializing.
*/
$data = unserialize($content);
}
if ( $data === false || !is_array($data) || !isset($data['__VER__']) ) {
throw new LSCMException(
"$dataFile - Data is corrupt.",
self::ERR_CORRUPTED
);
}
if ( ($err = $this->verifyDataFileVer($dataFile, $data['__VER__'])) ) {
throw new LSCMException(
"$dataFile - Data file version issue.",
$err
);
}
unset($data['__VER__']);
$wpInstalls = [];
foreach ( $data as $utf8Path => $idata ) {
$path = Utf8::decode($utf8Path);
$i = new WPInstall($path);
$idata[WPInstall::FLD_SITEURL] =
urldecode((string)$idata[WPInstall::FLD_SITEURL]);
$idata[WPInstall::FLD_SERVERNAME] =
urldecode((string)$idata[WPInstall::FLD_SERVERNAME]);
$i->initData($idata);
$wpInstalls[$path] = $i;
}
return $wpInstalls;
}
/**
*
* @return int
*/
public function getError()
{
return $this->error;
}
/**
*
* @param bool $nonFatalOnly
*
* @return int
*/
public function getCount( $nonFatalOnly = false )
{
$count = 0;
if ( $this->wpInstalls != null ) {
if ( $nonFatalOnly ) {
foreach ( $this->wpInstalls as $install ) {
if ( !$install->hasFatalError() ) {
$count++;
}
}
}
else {
$count += count($this->wpInstalls);
}
}
if ( $this->custWpInstalls != null ) {
if ( $nonFatalOnly ) {
foreach ( $this->custWpInstalls as $custInstall ) {
if ( !$custInstall->hasFatalError() ) {
$count++;
}
}
}
else {
$count += count($this->custWpInstalls);
}
}
return $count;
}
/**
*
* @return null|WPInstall[]
*
* @noinspection PhpUnused
*/
public function getWPInstalls()
{
return $this->wpInstalls;
}
/**
*
* @return null|WPInstall[]
*
* @noinspection PhpUnused
*/
public function getCustWPInstalls()
{
return $this->custWpInstalls;
}
/**
*
* @return null|WPInstall[]
*/
public function getAllWPInstalls()
{
if ( $this->wpInstalls != null ) {
if ( $this->custWpInstalls != null ) {
return array_merge($this->wpInstalls, $this->custWpInstalls);
}
else {
return $this->wpInstalls;
}
}
elseif ( $this->custWpInstalls != null ) {
return $this->custWpInstalls;
}
else {
return null;
}
}
/**
* Get all known WPInstall paths.
*
* @return string[]
*/
public function getPaths()
{
$paths = [];
if ( $this->wpInstalls != null ) {
$paths = array_keys($this->wpInstalls);
}
if ( $this->custWpInstalls != null ) {
$paths = array_merge($paths, array_keys($this->custWpInstalls));
}
return $paths;
}
/**
*
* @param string $path
*
* @return WPInstall|null
*/
public function getWPInstall( $path )
{
if ( ($realPath = realpath($path)) === false ) {
$index = $path;
}
else {
$index = $realPath;
}
if ( isset($this->wpInstalls[$index]) ) {
return $this->wpInstalls[$index];
}
elseif ( isset($this->custWpInstalls[$index]) ) {
return $this->custWpInstalls[$index];
}
return null;
}
/**
*
* @return WPInstall[]
*/
public function getWorkingQueue()
{
return $this->workingQueue;
}
/**
*
* @param WPInstall $wpInstall
*/
public function addWPInstall( WPInstall $wpInstall )
{
$this->wpInstalls[$wpInstall->getPath()] = $wpInstall;
}
/**
*
* @throws LSCMException Thrown indirectly by $this->saveDataFile() call.
* @throws LSCMException Thrown indirectly by $this->saveDataFile() call.
*/
public function syncToDisk()
{
$this->saveDataFile($this->dataFile, $this->wpInstalls);
if ( $this->customDataFile != '' ) {
$this->saveDataFile($this->customDataFile, $this->custWpInstalls);
}
}
/**
*
* @param string $dataFile
* @param WPInstall[]|null $wpInstalls
*
* @throws LSCMException Thrown indirectly by $this->log() call.
*/
protected function saveDataFile( $dataFile, $wpInstalls )
{
$data = [ '__VER__' => self::DATA_VERSION ];
if ( !empty($wpInstalls) ) {
foreach ( $wpInstalls as $path => $install ) {
if ( !$install->shouldRemove() ) {
$utf8Path = Utf8::encode($path);
$data[$utf8Path] = $install->getData();
$siteUrl = &$data[$utf8Path][WPInstall::FLD_SITEURL];
if ( $siteUrl != null ) {
$siteUrl = urlencode($siteUrl);
}
$serverName = &$data[$utf8Path][WPInstall::FLD_SERVERNAME];
if ( $serverName != null ) {
$serverName = urlencode($serverName);
}
}
}
ksort($data);
}
file_put_contents($dataFile, json_encode($data), LOCK_EX);
chmod($dataFile, 0600);
$this->log("Data file saved $dataFile", Logger::L_DEBUG);
}
/**
*
* @param string $dataFile
* @param string $dataFileVer
*
* @return int
*
* @throws LSCMException Thrown indirectly by Logger::info() call.
* @throws LSCMException Thrown indirectly by $this->updateDataFile() call.
*/
protected function verifyDataFileVer( $dataFile, $dataFileVer )
{
$res = Util::betterVersionCompare($dataFileVer, self::DATA_VERSION);
if ( $res == 1 ) {
Logger::info(
'Data file version is higher than expected and cannot be used.'
);
return self::ERR_VERSION_HIGH;
}
if ( $res == -1 && !$this->updateDataFile($dataFile, $dataFileVer) ) {
return self::ERR_VERSION_LOW;
}
return 0;
}
/**
*
* @param string $dataFile
* @param string $dataFileVer
*
* @return bool
*
* @throws LSCMException Thrown indirectly by Logger::info() call.
* @throws LSCMException Thrown indirectly by Util::createBackup() call.
* @throws LSCMException Thrown indirectly by Logger::error() call.
*/
public static function updateDataFile( $dataFile, $dataFileVer )
{
Logger::info(
"$dataFile - Old data file version detected. Attempting to "
. 'update...'
);
/**
* Currently no versions are upgradeable to 1.5
*/
$updatableVersions = [];
if (
!in_array($dataFileVer, $updatableVersions)
||
! Util::createBackup($dataFile)
) {
Logger::error(
"$dataFile - Data file could not be updated to version "
. self::DATA_VERSION
);
return false;
}
/**
* Upgrade funcs will be called here.
*/
return true;
}
/**
*
* @param string $action
*
* @return string[]
*
* @throws LSCMException Thrown when "get docroots" command fails.
* @throws LSCMException Thrown when $action value is unsupported.
*/
protected function prepareActionItems( $action )
{
switch ( $action ) {
case self::CMD_SCAN:
case self::CMD_SCAN2:
case self::CMD_DISCOVER_NEW:
case self::CMD_DISCOVER_NEW2:
try
{
return ControlPanel::getClassInstance()->getDocRoots();
}
catch ( LSCMException $e )
{
throw new LSCMException(
$e->getMessage()
. " Could not prepare $action action items."
);
}
case UserCommand::CMD_MASS_ENABLE:
case UserCommand::CMD_MASS_DISABLE:
case UserCommand::CMD_MASS_UPGRADE:
case UserCommand::CMD_MASS_DASH_NOTIFY:
case UserCommand::CMD_MASS_DASH_DISABLE:
case self::CMD_MASS_UNFLAG:
return $this->getPaths();
default:
throw new LSCMException('Missing parameter(s).');
}
}
/**
*
* @param string $action
* @param string $path
* @param string[] $extraArgs
*
* @throws LSCMException Thrown when an invalid LSCWP version is selected
* in action UserCommand::CMD_MASS_UPGRADE.
* @throws LSCMException Thrown when LSCWP version fails to download in
* action UserCommand::CMD_MASS_UPGRADE.
* @throws LSCMException Thrown when LSCWP source package is not available
* in action UserCommand::CMD_MASS_UPGRADE.
* @throws LSCMException Thrown indirectly by $wpInstall->hasValidPath()
* call.
* @throws LSCMException Thrown indirectly by $wpInstall->addUserFlagFile()
* call.
* @throws LSCMException Thrown indirectly by $wpInstall->hasValidPath()
* call.
* @throws LSCMException Thrown indirectly by $wpInstall->refreshStatus()
* call.
* @throws LSCMException Thrown indirectly by $wpInstall->addUserFlagFile()
* call.
* @throws LSCMException Thrown indirectly by PluginVersion::getInstance()
* call.
* @throws LSCMException Thrown indirectly by
* PluginVersion::getInstance()->getAllowedVersions() call.
* @throws LSCMException Thrown indirectly by UserCommand::issue() call.
* @throws LSCMException Thrown indirectly by $this->syncToDisk() call.
* @throws LSCMException Thrown indirectly by $this->syncToDisk() call.
*/
protected function doWPInstallAction( $action, $path, array $extraArgs )
{
if ( ($wpInstall = $this->getWPInstall($path)) == null ) {
$wpInstall = new WPInstall($path);
$this->addWPInstall($wpInstall);
}
switch ( $action ) {
case self::CMD_FLAG:
case self::CMD_MASS_FLAG:
if ( !$wpInstall->hasValidPath() ) {
return;
}
if ( $wpInstall->addUserFlagFile(false) ) {
$wpInstall->setCmdStatusAndMsg(
UserCommand::EXIT_SUCC,
'Flag file set'
);
}
else {
$wpInstall->setCmdStatusAndMsg(
UserCommand::EXIT_FAIL,
'Could not create flag file'
);
}
$this->workingQueue[$path] = $wpInstall;
return;
case self::CMD_UNFLAG:
case self::CMD_MASS_UNFLAG:
if ( !$wpInstall->hasValidPath() ) {
return;
}
$wpInstall->removeFlagFile();
$wpInstall->setCmdStatusAndMsg(
UserCommand::EXIT_SUCC,
'Flag file unset'
);
$this->workingQueue[$path] = $wpInstall;
return;
case UserCommand::CMD_ENABLE:
case UserCommand::CMD_DISABLE:
case UserCommand::CMD_DASH_NOTIFY:
case UserCommand::CMD_DASH_DISABLE:
if ( $wpInstall->hasFatalError() ) {
$wpInstall->refreshStatus();
if ( $wpInstall->hasFatalError() ) {
$wpInstall->addUserFlagFile(false);
$wpInstall->setCmdStatusAndMsg(
UserCommand::EXIT_FAIL,
'Install skipped and flagged due to Error status.'
);
$this->workingQueue[$path] = $wpInstall;
return;
}
}
break;
case UserCommand::CMD_MASS_UPGRADE:
$lscwpVer = $extraArgs[1];
$isAllowedVer = in_array(
$lscwpVer,
PluginVersion::getInstance()->getAllowedVersions()
);
if ( !$isAllowedVer ) {
throw new LSCMException(
'Selected LSCWP version ('
. htmlspecialchars($lscwpVer)
. ') is invalid.'
);
}
break;
//no default
}
if ( UserCommand::issue($action, $wpInstall, $extraArgs) ) {
if (
$action == UserCommand::CMD_MASS_UPGRADE
&&
($wpInstall->getCmdStatus() & UserCommand::EXIT_FAIL)
&&
preg_match(
'/Download failed. Not Found/',
$wpInstall->getCmdMsg()
)
) {
$this->syncToDisk();
throw new LSCMException(
'Could not download version '
. htmlspecialchars($extraArgs[1])
. '.'
);
}
if (
$action == UserCommand::CMD_MASS_ENABLE
&&
($wpInstall->getCmdStatus() & UserCommand::EXIT_FAIL)
&&
preg_match(
'/Source Package not available/',
$wpInstall->getCmdMsg()
)
) {
$this->syncToDisk();
throw new LSCMException($wpInstall->getCmdMsg());
}
$this->workingQueue[$path] = $wpInstall;
}
}
/**
*
* @param string $action
* @param null|string[] $list
* @param string[]|string[][] $extraArgs
*
* @return string[]
*
* @throws LSCMException Thrown indirectly by $this->prepareActionItems()
* call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by Context::getActionTimeout()
* call.
* @throws LSCMException Thrown indirectly by $this->scan() call.
* @throws LSCMException Thrown indirectly by $this->addNewWPInstall()
* call.
* @throws LSCMException Thrown indirectly by
* $this->addCustomInstallations() call.
* @throws LSCMException Thrown indirectly by
* PluginVersion::getCurrentVersion() call.
* @throws LSCMException Thrown indirectly by PluginVersion::getInstance()
* call.
* @throws LSCMException Thrown indirectly by
* PluginVersion::getInstance()->setActiveVersion() call.
* @throws LSCMException Thrown indirectly by $this->doWPInstallAction()
* call.
* @throws LSCMException Thrown indirectly by $this->syncToDisk() call.
*/
public function doAction( $action, $list, array $extraArgs = [] )
{
if ( $list === null ) {
$list = $this->prepareActionItems($action);
}
$count = count($list);
$this->log("doAction $action for $count items", Logger::L_VERBOSE);
$endTime = ($count > 1) ? Context::getActionTimeout() : 0;
$finishedList = [];
switch ( $action ) {
case self::CMD_SCAN:
case self::CMD_DISCOVER_NEW:
foreach ( $list as $path ) {
$this->scan($path, ($action == self::CMD_SCAN));
$finishedList[] = $path;
if ( $endTime && time() >= $endTime ) {
break;
}
}
break;
case self::CMD_ADD_NEW_WPINSTALL:
foreach ( $list as $path) {
$this->addNewWPInstall($path);
$finishedList[] = $path;
if ( $endTime && time() >= $endTime ) {
break;
}
}
break;
case self::CMD_ADD_CUST_WPINSTALLS:
$this->addCustomInstallations($extraArgs[0]);
break;
default:
if (
$action == UserCommand::CMD_ENABLE
||
$action == UserCommand::CMD_MASS_ENABLE
) {
/**
* Ensure that the current version is locally downloaded.
*/
PluginVersion::getInstance()
->setActiveVersion(PluginVersion::getCurrentVersion())
;
}
foreach ( $list as $path ) {
$this->doWPInstallAction($action, $path, $extraArgs);
$finishedList[] = $path;
if ( $endTime && time() >= $endTime ) {
break;
}
}
}
$this->syncToDisk();
if ( $action == self::CMD_SCAN || $action == self::CMD_SCAN2 ) {
/**
* Explicitly clear any data file errors after scanning in case of
* multiple actions performed in the same process (cli).
*/
$this->error = 0;
}
return $finishedList;
}
/**
*
* @deprecated 1.13.3 Use $this->scan2() instead.
*
* @param string $docroot
* @param bool $forceRefresh
*
* @return void
*
* @throws LSCMException Thrown indirectly by Context::getScanDepth() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by
* $this->wpInstalls[$wp_path]->refreshStatus() call.
*/
protected function scan( $docroot, $forceRefresh = false )
{
$directories = shell_exec(
"find -L $docroot -maxdepth "
. Context::getScanDepth()
. ' -name wp-admin -print'
);
$hasMatches = false;
if ( $directories ) {
/**
* Example:
* /home/user/public_html/wordpress/wp-admin
* /home/user/public_html/blog/wp-admin
* /home/user/public_html/wp/wp-admin
*/
$hasMatches = preg_match_all(
"|$docroot(.*)(?=/wp-admin)|",
$directories,
$matches
);
}
if ( ! $hasMatches ) {
/**
* Nothing found.
*/
return;
}
/** @noinspection PhpUndefinedVariableInspection */
foreach ( $matches[1] as $path ) {
$wp_path = realpath($docroot . $path);
$refresh = $forceRefresh;
if ( !isset($this->wpInstalls[$wp_path]) ) {
$this->wpInstalls[$wp_path] = new WPInstall($wp_path);
$refresh = true;
$this->log(
"New installation found: $wp_path",
Logger::L_INFO
);
if (
$this->custWpInstalls != null
&&
isset($this->custWpInstalls[$wp_path])
) {
unset($this->custWpInstalls[$wp_path]);
$this->log(
"Installation removed from custom data file: $wp_path",
Logger::L_INFO
);
}
}
else {
$this->log(
"Installation already found: $wp_path",
Logger::L_DEBUG
);
}
if ( $refresh ) {
$this->wpInstalls[$wp_path]->refreshStatus();
$this->workingQueue[$wp_path] = $this->wpInstalls[$wp_path];
}
}
}
/**
*
* @since 1.13.3
* @since 1.15 Changed function visibility from 'public' to
* 'public static'.
*
* @param string $docroot
*
* @return string[]
*
* @throws LSCMException Thrown indirectly by Context::getScanDepth() call.
*/
public static function scan2( $docroot )
{
$directories = shell_exec(
"find -L $docroot -maxdepth "
. Context::getScanDepth()
.' -name wp-admin -print'
);
$hasMatches = false;
if ( $directories ) {
/**
* Example:
* /home/user/public_html/wordpress/wp-admin
* /home/user/public_html/blog/wp-admin
* /home/user/public_html/wp/wp-admin
*/
$hasMatches = preg_match_all(
"|$docroot(.*)(?=/wp-admin)|",
$directories,
$matches
);
}
if ( ! $hasMatches ) {
/**
* Nothing found.
*/
return [];
}
$wpPaths = [];
/** @noinspection PhpUndefinedVariableInspection */
foreach ( $matches[1] as $path ) {
$wpPaths[] = realpath($docroot . $path);
}
return $wpPaths;
}
/**
* Add a new WPInstall object to WPInstallStorage's $wpInstalls[] given a
* path to a WordPress installation and refresh its status. If a WPInstall
* object already exists for the given path, refresh its status.
*
* @since 1.13.3
*
* @param string $wpPath
*
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by
* $this->wpInstalls[$wpPath]->refreshStatus() call.
*/
protected function addNewWPInstall( $wpPath )
{
if ( ($realPath = realpath($wpPath)) !== false ) {
$wpPath = $realPath;
}
if ( !isset($this->wpInstalls[$wpPath]) ) {
$this->wpInstalls[$wpPath] = new WPInstall($wpPath);
$this->log("New installation found: $wpPath", Logger::L_INFO);
if (
$this->custWpInstalls != null
&&
isset($this->custWpInstalls[$wpPath])
) {
unset($this->custWpInstalls[$wpPath]);
$this->log(
"Installation removed from custom data file: $wpPath",
Logger::L_INFO
);
}
}
else {
$this->log(
"Installation already found: $wpPath",
Logger::L_DEBUG
);
}
$this->wpInstalls[$wpPath]->refreshStatus();
$this->workingQueue[$wpPath] = $this->wpInstalls[$wpPath];
}
/**
*
* @param string[] $wpInstallsInfo
*
* @return void
*
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by
* $this->custWpInstalls[$wpPath]->refreshStatus() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
* @throws LSCMException Thrown indirectly by $this->log() call.
*/
protected function addCustomInstallations( array $wpInstallsInfo )
{
if ( $this->customDataFile == '' ) {
$this->log(
'No custom data file set, could not add custom Installation.',
Logger::L_INFO
);
return;
}
if ( $this->custWpInstalls == null ) {
$this->custWpInstalls = [];
}
for ( $i = 0; $i < count($wpInstallsInfo); $i++ ) {
$info = preg_split('/\s+/', trim($wpInstallsInfo[$i]));
$line = $i + 1;
if ( count($info) != 4 ) {
$this->log(
'Incorrect number of values for custom installation input '
. "string on line $line. Skipping.",
Logger::L_INFO
);
continue;
}
$wpPath = $info[0];
if ( !file_exists("$wpPath/wp-admin") ) {
$this->log(
"No 'wp-admin' directory found for $wpPath on line "
. "$line. Skipping.",
Logger::L_INFO
);
continue;
}
$docroot = $info[1];
if ( !(substr($wpPath, 0, strlen($docroot)) === $docroot) ) {
$this->log(
"docroot not contained in $wpPath on line $line. "
. 'Skipping.',
Logger::L_INFO
);
continue;
}
if ( !isset($this->wpInstalls[$wpPath]) ) {
$this->custWpInstalls[$wpPath] = new WPInstall($wpPath);
$this->custWpInstalls[$wpPath]->setDocRoot($docroot);
$this->custWpInstalls[$wpPath]->setServerName($info[2]);
$this->custWpInstalls[$wpPath]->setSiteUrlDirect($info[3]);
$this->custWpInstalls[$wpPath]->refreshStatus();
$this->log(
"New installation added to custom data file: $wpPath",
Logger::L_INFO
);
}
else {
$this->log(
"Installation already found during scan: $wpPath. "
. 'Skipping.',
Logger::L_INFO
);
}
}
}
/**
* Get all WPInstall command messages as a key=>value array.
*
* @return string[][]
*/
public function getAllCmdMsgs()
{
$succ = $fail = $err = [];
foreach ( $this->workingQueue as $wpInstall ) {
if ( ($msg = $wpInstall->getCmdMsg()) ) {
$cmdStatus = $wpInstall->getCmdStatus();
switch( true ) {
case $cmdStatus & UserCommand::EXIT_SUCC:
$msgType = &$succ;
break;
case $cmdStatus & UserCommand::EXIT_FAIL:
$msgType = &$fail;
break;
case $cmdStatus & UserCommand::EXIT_ERROR:
$msgType = &$err;
break;
default:
continue 2;
}
$msgType[] = "{$wpInstall->getPath()} - $msg";
}
}
return [ 'succ' => $succ, 'fail' => $fail, 'err' => $err ];
}
/**
*
* @param string $msg
* @param int $level
*
* @throws LSCMException Thrown indirectly by Logger::error() call.
* @throws LSCMException Thrown indirectly by Logger::warn() call.
* @throws LSCMException Thrown indirectly by Logger::notice() call.
* @throws LSCMException Thrown indirectly by Logger::info() call.
* @throws LSCMException Thrown indirectly by Logger::verbose() call.
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function log( $msg, $level )
{
$msg = "WPInstallStorage - $msg";
switch ( $level ) {
case Logger::L_ERROR:
Logger::error($msg);
break;
case Logger::L_WARN:
Logger::warn($msg);
break;
case Logger::L_NOTICE:
Logger::notice($msg);
break;
case Logger::L_INFO:
Logger::info($msg);
break;
case Logger::L_VERBOSE:
Logger::verbose($msg);
break;
case Logger::L_DEBUG:
Logger::debug($msg);
break;
//no default
}
}
}
webcachemgr/src/CliController.php 0000664 00000121421 15055136440 0013074 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright (c) 2018-2023 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp;
use Exception;
use Lsc\Wp\Context\Context;
use Lsc\Wp\Panel\ControlPanel;
use Lsc\Wp\Panel\CPanel;
class CliController
{
/**
* @since 1.13.5
* @var string
*/
const SPECIAL_CMD_CPANEL_PLUGIN_AUTOINSTALL_OFF = 'cpanelPluginAutoInstallOff';
/**
* @since 1.13.5
* @var string
*/
const SPECIAL_CMD_CPANEL_PLUGIN_AUTOINSTALL_ON = 'cpanelPluginAutoInstallOn';
/**
* @since 1.13.5
* @var string
*/
const SPECIAL_CMD_CPANEL_PLUGIN_AUTOINSTALL_STATUS = 'cpanelPluginAutoInstallStatus';
/**
* @since 1.13.5
* @var string
*/
const SPECIAL_CMD_CPANEL_PLUGIN_FIX_CONF = 'cpanelPluginFixConf';
/**
* @since 1.13.5
* @var string
*/
const SPECIAL_CMD_CPANEL_PLUGIN_INSTALL = 'cpanelPluginInstall';
/**
* @since 1.13.5
* @var string
*/
const SPECIAL_CMD_CPANEL_PLUGIN_UNINSTALL = 'cpanelPluginUninstall';
/**
* @var string[]
*/
private $cacheRootCmds = array();
/**
* @var string[]
*/
private $commands = array();
/**
* @var string
*/
private $svrCacheRootParam = '';
/**
* @var string
*/
private $vhCacheRootParam = '';
/**
* @var bool
*/
private $displayCacheRoots = false;
/**
* @var null|string
*/
private $currWpPath;
/**
* @var null|string
*/
private $versionCmd;
/**
* @var null|string
*/
private $specialCmd;
/**
* Holds any additional command input for use after parseCommands().
*
* @var null|array
*/
private $input;
/**
*
* @throws LSCMException Thrown when script argument count is less than
* expected.
*/
public function __construct()
{
if ( empty($_SERVER['argv']) || $_SERVER['argc'] < 3 ) {
throw new LSCMException('Cli Illegal entrance!');
}
$args = $_SERVER['argv'];
/**
* shift out script name
*/
array_shift($args);
$this->parseCommands($args);
}
/**
* Checks if current $wpInstallStorage object is capable of having the
* given non-scan action performed.
*
* @param string $action
* @param WPInstallStorage $wpInstallStorage
*
* @return void
*
* @throws LSCMException Thrown when scan data cannot be read.
* @throws LSCMException Thrown when expected scan data format has changed.
* @throws LSCMException Thrown when attempting to execute a "mass"
* operation without any discovered installations.
*/
private function checkDataFile(
$action,
WPInstallStorage $wpInstallStorage )
{
if ( $action == WPInstallStorage::CMD_SCAN2 ) {
/**
* Always allowed.
*/
return;
}
if ( ($err = $wpInstallStorage->getError()) ) {
switch ($err) {
case WPInstallStorage::ERR_NOT_EXIST:
case WPInstallStorage::ERR_CORRUPTED:
case WPInstallStorage::ERR_VERSION_HIGH:
throw new LSCMException(
'Scan data could not be read! Please scan again '
. '(without the \'-n\' flag) before attempting any '
. "cache operations.\n"
);
case WPInstallStorage::ERR_VERSION_LOW:
throw new LSCMException(
'Scan data file format has been changed for this '
. 'version. Please scan again (without the \'-n\' '
. "flag) before attempting any cache operations.\n"
);
//no default
}
}
elseif ( strpos($action,'mass_') === 0
&& $wpInstallStorage->getCount() == 0 ) {
throw new LSCMException(
'No WordPress installations discovered in the previous scan. '
. 'If you have any newly installed WordPress '
. 'installations, please scan again or add them with '
. "command 'addinstalls'.\n"
);
}
}
/**
*
* @param WPInstall $wpInstall
*/
private function printStatusMsg( WPInstall $wpInstall )
{
$msg = "$this->currWpPath - Status: ";
$status = $wpInstall->getStatus();
if ( $status & WPInstall::ST_PLUGIN_ACTIVE ) {
$msg .= 'enabled';
if ( !$status & WPInstall::ST_LSC_ADVCACHE_DEFINED ) {
$msg .= ', not caching';
}
}
else {
$msg .= 'disabled';
}
$msg .= ' | Flagged: ';
$msg .= ($status & WPInstall::ST_FLAGGED) ? 'yes' : 'no';
$msg .= ' | Error: ';
if ( $status & WPInstall::ST_ERR_SITEURL ) {
$msg .= 'Could not retrieve WordPress siteURL.';
}
elseif ( $status & WPInstall::ST_ERR_DOCROOT ) {
$msg .= 'Could not match WordPress siteURL to a known control '
. 'panel docroot.';
}
elseif ( $status & WPInstall::ST_ERR_EXECMD ) {
$msg .= 'WordPress fatal error encountered during action '
. 'execution. This is most likely caused by custom code in '
. 'this WordPress installation.';
}
elseif ( $status & WPInstall::ST_ERR_EXECMD_DB ) {
$msg .= 'Error establishing WordPress database connection.';
}
elseif ( $status & WPInstall::ST_ERR_TIMEOUT ) {
$msg .= 'Timeout occurred during action execution.';
}
elseif ( $status & WPInstall::ST_ERR_WPCONFIG ) {
$msg .= 'Could not find a valid wp-config.php file.';
}
echo "$msg\n\n";
}
/**
*
* @param string[] $args
*
* @return void
*
* @throws LSCMException Thrown when -svr parameter is passed without a
* value.
* @throws LSCMException Thrown when -svr parameter value points to a
* non-empty directory.
* @throws LSCMException Thrown when -vh parameter is passed without a
* value.
* @throws LSCMException Thrown when -vh parameter value contains invalid
* character '$'.
* @throws LSCMException Thrown when -vh parameter value points to a
* non-empty directory.
* @throws LSCMException Thrown indirectly by
* ControlPanel::getClassInstance() call.
* @throws LSCMException Thrown indirectly by
* $controlPanel->getServerCacheRoot() call.
* @throws LSCMException Thrown indirectly by
* $controlPanel->getVHCacheRoot() call.
*/
private function handleSetCacheRootInput( array &$args )
{
if ( empty($args) ) {
$this->cacheRootCmds[] = 'listCacheRoots';
return;
}
$controlPanel = ControlPanel::getClassInstance();
if ( ($key = array_search('-svr', $args)) !== false ) {
if ( empty($args[$key + 1])
|| ($this->svrCacheRootParam = trim($args[$key + 1])) == '' ) {
throw new LSCMException(
'Invalid Command, missing server cache root value.'
);
}
$currSvrCacheRoot = $controlPanel->getServerCacheRoot();
if ( $this->svrCacheRootParam != $currSvrCacheRoot ) {
if ( !Util::is_dir_empty($this->svrCacheRootParam) ) {
throw new LSCMException(
'Provided server level cache root must be an empty '
. 'directory.'
);
}
$this->cacheRootCmds[] = 'setSvrCacheRoot';
}
unset($args[$key], $args[$key + 1]);
}
if ( ($key = array_search('-vh', $args)) !== false ) {
$setvhCacheRoot = false;
if ( empty($args[$key + 1])
|| ($this->vhCacheRootParam = trim($args[$key + 1])) == '' ) {
throw new LSCMException(
'Invalid Command, missing virtual host cache root value.'
);
}
if ( strpos($this->vhCacheRootParam, '$') !== false ) {
throw new LSCMException(
'Invalid Command, virtual host cache root value cannot '
. 'contain any \'$\' characters. \'$vh_user\' will be '
. 'automatically added to the end of virtual host '
. 'cache root values starting with a \'/\'.'
);
}
$currVHCacheRoot = $controlPanel->getVHCacheRoot();
if ( $this->vhCacheRootParam[0] == '/' ) {
$updatedVhCacheRoot =
rtrim($this->vhCacheRootParam, '/') . '/$vh_user';
if ( $updatedVhCacheRoot != $currVHCacheRoot
&& ! Util::is_dir_empty($this->vhCacheRootParam) ) {
throw new LSCMException(
'Provided absolute path for virtual host level cache '
. 'root must be an empty directory.'
);
}
$this->vhCacheRootParam = $updatedVhCacheRoot;
$setvhCacheRoot = true;
}
elseif ( $this->vhCacheRootParam != $currVHCacheRoot ) {
$setvhCacheRoot = true;
}
unset($args[$key], $args[$key + 1]);
if ( $setvhCacheRoot ) {
$this->cacheRootCmds[] = 'setVHCacheRoot';
}
}
}
/**
*
* @param string[] $args
*
* @return void
*
* @throws LSCMException Thrown when passed version set value is invalid.
*/
private function handleSetVersionInput( array &$args )
{
if ( ($key = array_search('--list', $args)) !== false ) {
unset($args[$key]);
$this->versionCmd = 'list';
return;
}
if ( ($key = array_search('--latest', $args)) !== false ) {
unset($args[$key]);
$this->versionCmd = 'latest';
return;
}
if ( empty($args) ) {
$this->versionCmd = 'active';
return;
}
$v = array_shift($args);
if ( preg_match('/[1-9]\.\d(?:\.\d)*(?:\.\d)*/', $v) !== 1 ) {
throw new LSCMException("Invalid version number ($v).");
}
$this->versionCmd = $v;
}
/**
*
* @param string[] $args
*/
private function handleScanInput( array &$args )
{
if ( ($key = array_search('-n', $args)) !== false ) {
unset($args[$key]);
$this->commands[] = WPInstallStorage::CMD_DISCOVER_NEW2;
}
else {
$this->commands[] = WPInstallStorage::CMD_SCAN2;
}
if ( ($key = array_search('-e', $args)) !== false ) {
unset($args[$key]);
$this->commands[] = UserCommand::CMD_MASS_ENABLE;
}
}
/**
*
* @param string[] $args
*/
private function handleScanNewInput( array &$args )
{
if ( ($key = array_search('-en', $args)) !== false ) {
unset($args[$key]);
$this->commands[] = WPInstallStorage::CMD_DISCOVER_NEW_AND_ENABLE;
}
else {
$this->commands[] = WPInstallStorage::CMD_DISCOVER_NEW2;
}
}
/**
*
* @param string[] $args
*
* @return bool
*/
private function isMassOperation( array &$args )
{
if ( ($key = array_search('-m', $args)) !== false ) {
unset($args[$key]);
return true;
}
return false;
}
/**
*
* @param string $cmd
* @param string[] $args
*
* @throws LSCMException Thrown when expected WP path value is not
* provided.
* @throws LSCMException Thrown when provided an invalid WP path value.
*/
private function handleSingleOperationInput( $cmd, array &$args )
{
$path = array_shift($args);
if ( $path == null ) {
throw new LSCMException('Invalid Command, missing WP path.');
}
$wpInstall = new WPInstall($path);
if ( !$wpInstall->hasValidPath() ) {
throw new LSCMException("Invalid WP Path: $path.");
}
$this->commands[] = $cmd;
$this->currWpPath = rtrim($path, '/');
}
/**
*
* @param string $cmdType
* @param string[] $args
*
* @throws LSCMException Thrown when neither -m nor -wppath parameters are
* provided in notify command.
* @throws LSCMException Thrown when -wppath parameter is passed without a
* value in notify command.
* @throws LSCMException Thrown when provided -wppath parameter value is
* invalid in notify command.
* @throws LSCMException Thrown when -msgfile parameter is passed without a
* value in notify command.
* @throws LSCMException Thrown when provided -msgfile parameter value
* points to a non-existent file in notify command.
* @throws LSCMException Thrown when unable to get file contents of the
* file pointed to by provided -msgfile value in notify command.
* @throws LSCMException Thrown when neither -msgfile nor -msg parameters
* are provided in notify command.
* @throws LSCMException Thrown when parameter -msg is passed without a
* value in notify command.
* @throws LSCMException Thrown when expected -plugin parameter is not
* provided in notify command.
* @throws LSCMException Thrown when provided -plugin parameter value does
* not a known plugin slug in notify command.
* @throws LSCMException Thrown when neither -m flag nor WP path value are
* provided in remove command.
* @throws LSCMException Thrown when provided WP path value is invalid in
* remove command.
*/
private function handleDashNotifyInput( $cmdType, array &$args )
{
if ( $cmdType == 'notify' ) {
if ( ($key = array_search('-m', $args)) !== false ) {
unset($args[$key]);
$this->commands[] = UserCommand::CMD_MASS_DASH_NOTIFY;
}
else {
if ( ($key = array_search('-wppath', $args)) === false ) {
throw new LSCMException(
'Invalid Command, missing required \'-m\' or '
. '\'-wppath\' parameter.'
);
}
if ( empty($args[$key + 1]) ) {
throw new LSCMException(
'Invalid Command, missing \'-wppath\' value.'
);
}
$path = $args[$key + 1];
$wpInstall = new WPInstall($path);
if ( !$wpInstall->hasValidPath() ) {
throw new LSCMException("Invalid WP Path: $path.");
}
$this->commands[] = UserCommand::CMD_DASH_NOTIFY;
$this->currWpPath = rtrim($path, '/');
unset($args[$key], $args[$key + 1]);
}
if ( ($key = array_search('-msgfile', $args)) !== false ) {
if ( empty($args[$key + 1]) ) {
throw new LSCMException(
'Invalid Command, missing \'-msgfile\' value.'
);
}
$msgFilePath = $args[$key + 1];
if ( !file_exists($msgFilePath) ) {
throw new LSCMException(
'Provided message file does not exist.'
);
}
if ( ($message = file_get_contents($msgFilePath)) === false ) {
throw new LSCMException(
'Unable to retrieve provided message file content.'
);
}
}
else {
if ( ($key = array_search('-msg', $args)) === false ) {
throw new LSCMException(
'Invalid Command, missing required \'-msgfile\' or '
. '\'-msg\' parameter.'
);
}
if ( empty($args[$key + 1]) ) {
throw new LSCMException(
'Invalid Command, missing \'-msg\' value.'
);
}
$message = $args[$key + 1];
}
$dashInput = array( 'msg' => $message );
unset($args[$key], $args[$key + 1]);
if ( ($key = array_search('-plugin', $args)) !== false ) {
if ( empty($args[$key + 1]) ) {
throw new LSCMException(
'Invalid Command, missing \'-plugin\' value.'
);
}
$slug = $args[$key + 1];
$pluginInfoJSON = Util::get_url_contents(
"https://api.wordpress.org/plugins/info/1.0/$slug.json"
);
$pluginInfo = json_decode($pluginInfoJSON, true);
if ( empty($pluginInfo['name']) ) {
throw new LSCMException(
'Could not find a plugin matching the provided plugin '
. 'slug.'
);
}
$dashInput['slug'] = $slug;
unset($args[$key], $args[$key + 1]);
}
$this->input = $dashInput;
}
elseif ( $cmdType == 'remove' ) {
$arg1 = array_shift($args);
if ( $arg1 == '-m' ) {
$this->commands[] = UserCommand::CMD_MASS_DASH_DISABLE;
}
else {
$path = $arg1;
if ( $path == null ) {
throw new LSCMException(
'Invalid Command, missing \'-m\' flag or WP path value.'
);
}
$wpInstall = new WPInstall($path);
if ( !$wpInstall->hasValidPath() ) {
throw new LSCMException("Invalid WP Path: $path.");
}
$this->commands[] = UserCommand::CMD_DASH_DISABLE;
$this->currWpPath = rtrim($path, '/');
}
}
}
/**
*
* @param string[] $args
*
* @throws LSCMException Thrown when command 'cpanelplugin' is used in a
* non-cPanel environment.
* @throws LSCMException Thrown indirectly by
* ControlPanel::getClassInstance() call.
*/
private function handleCpanelPluginInput( array &$args )
{
$controlPanel = ControlPanel::getClassInstance();
if ( !($controlPanel instanceof CPanel) ) {
throw new LSCMException(
'Command \'cpanelplugin\' cannot be used in a non-cPanel '
. 'environment.'
);
}
switch ($args[0]) {
case '--install':
$this->specialCmd = self::SPECIAL_CMD_CPANEL_PLUGIN_INSTALL;
unset($args[0]);
break;
case '--uninstall':
$this->specialCmd = self::SPECIAL_CMD_CPANEL_PLUGIN_UNINSTALL;
unset($args[0]);
break;
case '-autoinstall':
if ( !isset($args[1]) ) {
$this->specialCmd =
self::SPECIAL_CMD_CPANEL_PLUGIN_AUTOINSTALL_STATUS;
}
elseif ( "$args[1]" === '1' ) {
$this->specialCmd =
self::SPECIAL_CMD_CPANEL_PLUGIN_AUTOINSTALL_ON;
unset($args[1]);
}
elseif ( "$args[1]" === '0' ) {
$this->specialCmd =
self::SPECIAL_CMD_CPANEL_PLUGIN_AUTOINSTALL_OFF;
unset($args[1]);
}
unset($args[0]);
break;
case '--fixconf':
$this->specialCmd = self::SPECIAL_CMD_CPANEL_PLUGIN_FIX_CONF;
unset($args[0]);
break;
//no default
}
}
/**
*
* @param string[] $args
*
* @throws LSCMException Thrown when -wpinstall parameter is passed without
* a value.
* @throws LSCMException Thrown when expected 'docroot' value is not
* provided when using parameter -wpinstall.
* @throws LSCMException Thrown when expected 'server name' value is not
* provided when using parameter -wpinstall.
* @throws LSCMException Thrown when expected 'site url' value is not
* provided when using parameter -wpinstall.
* @throws LSCMException Thrown when -wpinstallsfile parameter is passed
* without a value.
* @throws LSCMException Thrown when provided -wpinstallsfile parameter
* value points to a non-existent file.
* @throws LSCMException Thrown when unable to get file contents of the
* file pointed to by provided -wpinstallsfile parameter value.
*/
private function handleAddInstallsInput( array &$args )
{
switch ($args[0]) {
case '-wpinstall':
if ( empty($args[1]) ) {
throw new LSCMException(
'Invalid Command, missing \'<wp path>\' value.'
);
}
$wpInstallsInfo = "$args[1]";
if ( empty($args[2]) ) {
throw new LSCMException(
'Invalid Command, missing \'<docroot>\' value.'
);
}
$wpInstallsInfo .= " $args[2]";
if ( empty($args[3]) ) {
throw new LSCMException(
'Invalid Command, missing \'<server name>\' value.'
);
}
$wpInstallsInfo .= " $args[3]";
if ( empty($args[4]) ) {
throw new LSCMException(
'Invalid Command, missing \'<site url>\' value.'
);
}
$wpInstallsInfo .= " $args[4]";
$this->commands[] = WPInstallStorage::CMD_ADD_CUST_WPINSTALLS;
$this->input =
array( 'addInstallsInfo' => array($wpInstallsInfo) );
unset($args[0], $args[1], $args[2], $args[3], $args[4]);
break;
case '-wpinstallsfile':
if ( empty($args[1]) ) {
throw new LSCMException(
'Invalid Command, missing \'-wpinstallsfile\' value.'
);
}
$wpInstallsFile = $args[1];
if ( !file_exists($wpInstallsFile) ) {
throw new LSCMException(
'Provided wpinstalls file does not exist.'
);
}
$fileContent = file_get_contents($wpInstallsFile);
if ( $fileContent === false ) {
throw new LSCMException(
'Could not read wpinstalls file content.'
);
}
$this->commands[] = WPInstallStorage::CMD_ADD_CUST_WPINSTALLS;
$this->input = array(
'addInstallsInfo' => explode("\n", trim($fileContent))
);
unset($args[0], $args[1]);
break;
// no default
}
}
/**
*
* @throws LSCMException Thrown indirectly by
* ControlPanel::getClassInstance() call.
* @throws LSCMException Thrown indirectly by
* $controlPanel->getServerCacheRoot() call.
* @throws LSCMException Thrown indirectly by
* $controlPanel->getVHCacheRoot() call.
*/
private function displayCacheRoots()
{
$controlPanel = ControlPanel::getClassInstance();
$svrCacheRoot = $controlPanel->getServerCacheRoot();
$vhCacheRoot = $controlPanel->getVHCacheRoot();
if ( $svrCacheRoot == ControlPanel::NOT_SET ) {
$svrCacheRoot = 'Not Set';
}
if ( $vhCacheRoot == ControlPanel::NOT_SET) {
$vhCacheRoot = 'Not Set';
}
echo <<<EOF
Server Cache Root: $svrCacheRoot
Virtual Host Cache Root: $vhCacheRoot
EOF;
}
/**
*
* @param string[] $args
*
* @throws LSCMException Thrown when command setcacheroot is used in the
* CustomPanel context.
* @throws LSCMException Thrown when an unrecognized command is provided.
* @throws LSCMException Thrown when not all provided command arguments are
* recognized or used when provided with a valid command.
* @throws LSCMException Thrown indirectly by
* ControlPanel::getClassInstance() call.
* @throws LSCMException Thrown indirectly by
* $this->handleSetCacheRootInput() call.
* @throws LSCMException Thrown indirectly by
* $this->handleSetVersionInput() call.
* @throws LSCMException Thrown indirectly by
* $this->handleSingleOperationInput() call.
* @throws LSCMException Thrown indirectly by
* $this->handleDashNotifyInput() call.
* @throws LSCMException Thrown indirectly by
* $this->handleDashNotifyInput() call.
* @throws LSCMException Thrown indirectly by
* $this->handleCpanelPluginInput() call.
* @throws LSCMException Thrown indirectly by
* $this->handleAddInstallsInput() call.
*/
private function parseCommands( array $args )
{
$panelClassName = array_shift($args);
/**
* Initialize ControlPanel instance.
*/
ControlPanel::getClassInstance($panelClassName);
$cmd = array_shift($args);
switch ( $cmd ) {
case 'setcacheroot':
if ( $panelClassName == 'custom' ) {
throw new LSCMException(
'Command \'setcacheroot\' cannot be used in the '
. 'CustomPanel context.'
);
}
$this->handleSetCacheRootInput($args);
break;
case 'setversion':
$this->handleSetVersionInput($args);
break;
case 'scan':
$this->handleScanInput($args);
break;
case 'scannew':
$this->handleScanNewInput($args);
break;
case 'enable':
case 'disable':
case 'upgrade':
/** @noinspection PhpMissingBreakStatementInspection */
case 'unflag':
if ( $this->isMassOperation($args) ) {
$this->commands[] = "mass_$cmd";
break;
}
//fall through
case 'flag':
case 'status':
$this->handleSingleOperationInput($cmd, $args);
break;
case 'dashnotify':
$this->handleDashNotifyInput('notify', $args);
break;
case 'dashnotifyremove':
$this->handleDashNotifyInput('remove', $args);
break;
case 'cpanelplugin':
$this->handleCpanelPluginInput($args);
break;
case 'addinstalls':
$this->handleAddInstallsInput($args);
break;
default:
throw new LSCMException('Invalid Command, Try --help.');
}
if ( !empty($args) ) {
throw new LSCMException('Invalid Command, Try --help.');
}
}
/**
*
* @param string $action
*
* @throws LSCMException Thrown indirectly by
* ControlPanel::getClassInstance() call.
* @throws LSCMException Thrown indirectly by
* $controlPanel->setServerCacheRoot() call.
* @throws LSCMException Thrown indirectly by
* $controlPanel->setVHCacheRoot() call.
* @throws LSCMException Thrown indirectly by Util::restartLsws() call.
* @throws LSCMException Thrown indirectly by
* $controlPanel->getVHCacheRoot() call.
*/
private function doCacheRootCommand( $action )
{
$restartRequired = false;
$controlPanel = ControlPanel::getClassInstance();
switch ( $action ) {
case 'setSvrCacheRoot':
$controlPanel->setServerCacheRoot($this->svrCacheRootParam);
$restartRequired = true;
break;
case 'setVHCacheRoot':
$controlPanel->setVHCacheRoot($this->vhCacheRootParam);
$restartRequired = true;
break;
case 'listCacheRoots':
/**
* Wait until after verifyCacheSetup() has been run.
*/
$this->displayCacheRoots = true;
break;
//no default
}
if ( $restartRequired ) {
Util::restartLsws();
}
Util::ensureVHCacheRootInCage($controlPanel->getVHCacheRoot());
}
/**
*
* @throws LSCMException Thrown indirectly by
* ControlPanel::getClassInstance() call.
* @throws LSCMException Thrown indirectly by
* $controlPanel->installCpanelPlugin() call.
* @throws LSCMException Thrown indirectly by
* CPanel::uninstallCpanelPlugin() call.
* @throws LSCMException Thrown indirectly by
* $controlPanel->updateCoreCpanelPluginConfSettings() call.
*/
private function doSpecialCommand()
{
$controlPanel = ControlPanel::getClassInstance();
switch($this->specialCmd) {
case self::SPECIAL_CMD_CPANEL_PLUGIN_INSTALL:
/* @var $controlPanel CPanel */
switch ( $controlPanel->installCpanelPlugin() ) {
case 'update':
echo 'Updated LiteSpeed cPanel plugin to current '
. "version\n\n";
break;
case 'new':
echo 'LiteSpeed cPanel plugin installed, auto install '
. "turned on.\n\n";
break;
//no default
}
break;
case self::SPECIAL_CMD_CPANEL_PLUGIN_UNINSTALL:
CPanel::uninstallCpanelPlugin();
echo 'LiteSpeed cPanel plugin uninstalled successfully, auto '
. "install turned off.\n\n";
break;
case self::SPECIAL_CMD_CPANEL_PLUGIN_AUTOINSTALL_STATUS:
$state = (CPanel::isCpanelPluginAutoInstallOn()) ? 'On' : 'Off';
echo "Auto install is currently $state for the LiteSpeed "
. "cPanel plugin.\n";
echo 'Use command \'cpanelplugin -autoinstall {0 | 1}\' to '
. "turn auto install off/on respectively.\n\n";
break;
case self::SPECIAL_CMD_CPANEL_PLUGIN_AUTOINSTALL_ON:
if ( CPanel::turnOnCpanelPluginAutoInstall() ) {
echo 'Auto install is now On for LiteSpeed cPanel plugin.'
. "\n\n";
}
else {
echo 'Failed to turn off auto install for LiteSpeed cPanel '
. "plugin.\n\n";
}
break;
case self::SPECIAL_CMD_CPANEL_PLUGIN_AUTOINSTALL_OFF:
if ( CPanel::turnOffCpanelPluginAutoInstall() ) {
echo 'Auto install is now Off for LiteSpeed cPanel plugin.'
. "\n\n";
}
else {
echo 'Failed to turn on auto install for LiteSpeed cPanel '
. "plugin.\n\n";
}
break;
case self::SPECIAL_CMD_CPANEL_PLUGIN_FIX_CONF:
/* @var $controlPanel CPanel */
$controlPanel->updateCoreCpanelPluginConfSettings();
echo "Attempted to fix user-end cPanel Plugin conf.\n\n";
break;
//no default
}
}
/**
*
* @throws LSCMException Thrown indirectly by PluginVersion::getInstance()
* call.
* @throws LSCMException Thrown indirectly by
* $pluginVerInstance->getAllowedVersions() call.
* @throws LSCMException Thrown indirectly by
* $pluginVerInstance->getLatestVersion() call.
* @throws LSCMException Thrown indirectly by
* $pluginVerInstance->setActiveVersion() call.
* @throws LSCMException Thrown indirectly by
* $pluginVerInstance->getCurrentVersion() call.
* @throws LSCMException Thrown indirectly by
* $pluginVerInstance->setActiveVersion() call.
*/
private function doVersionCommand()
{
$pluginVerInstance = PluginVersion::getInstance();
switch ( $this->versionCmd ) {
case 'list':
echo "Available versions are: \n"
. implode("\n",$pluginVerInstance->getAllowedVersions())
. "\n";
break;
case 'latest':
$latest = $pluginVerInstance->getLatestVersion();
try {
$currVer = $pluginVerInstance->getCurrentVersion();
}
catch ( LSCMException $e ) {
$currVer = '';
}
if ( $latest == $currVer ) {
echo "Current version, $latest, is already the latest "
. "version.\n";
}
else {
$pluginVerInstance->setActiveVersion($latest);
}
break;
case 'active':
echo "Current active version is "
. $pluginVerInstance->getCurrentVersion()
. ".\n";
break;
default:
$pluginVerInstance->setActiveVersion($this->versionCmd);
}
}
/**
*
* @throws LSCMException Thrown indirectly by Context::getLSCMDataFiles()
* call.
* @throws LSCMException Thrown indirectly by "new WPInstallStorage()"
* call.
* @throws LSCMException Thrown indirectly by $this->checkDataFile() call.
* @throws LSCMException Thrown indirectly by PluginVersion::getInstance()
* call.
* @throws LSCMException Thrown indirectly by
* $pluginVerInstance->getShortVersions() call.
* @throws LSCMException Thrown indirectly by
* $pluginVerInstance->getCurrentVersion() call.
* @throws LSCMException Thrown indirectly by
* DashNotifier::prepLocalDashPluginFiles() call.
* @throws LSCMException Thrown indirectly by
* ControlPanel::getClassInstance() call.
* @throws LSCMException Thrown indirectly by
* ControlPanel::getClassInstance()->getDocRoots() call.
* @throws LSCMException Thrown indirectly by $wpInstallStorage->scan2()
* call.
* @throws LSCMException Thrown indirectly by $wpInstallStorage->doAction()
* call.
*/
private function doWPInstallStorageAction()
{
$extraArgs = array();
$list = null;
$originalAction = null;
$lscmDataFiles = Context::getLSCMDataFiles();
$wpInstallStorage = new WPInstallStorage(
$lscmDataFiles['dataFile'],
$lscmDataFiles['custDataFile']
);
if ( $this->currWpPath ) {
$list = array( $this->currWpPath );
}
foreach ( $this->commands as $action ) {
$this->checkDataFile($action, $wpInstallStorage);
echo "\nPerforming $action operation. Please be patient...\n\n";
switch ( $action ) {
case UserCommand::CMD_UPGRADE:
case UserCommand::CMD_MASS_UPGRADE:
$pluginVerInstance = PluginVersion::getInstance();
$extraArgs[] = implode(
',',
$pluginVerInstance->getShortVersions()
);
$extraArgs[] = $pluginVerInstance->getCurrentVersion();
break;
case UserCommand::CMD_DASH_NOTIFY:
case UserCommand::CMD_MASS_DASH_NOTIFY:
DashNotifier::prepLocalDashPluginFiles();
$slug = '';
if ( isset($this->input['slug']) ) {
$slug = $this->input['slug'];
}
$msgInfoJSON = json_encode(
array(
'msg' => $this->input['msg'],
'plugin' => $slug,
'plugin_name' => ''
)
);
$extraArgs[] = base64_encode($msgInfoJSON);
break;
case WPInstallStorage::CMD_ADD_CUST_WPINSTALLS:
$list = array();
$extraArgs[] = $this->input['addInstallsInfo'];
break;
case WPInstallStorage::CMD_SCAN2:
case WPInstallStorage::CMD_DISCOVER_NEW2:
case WPInstallStorage::CMD_DISCOVER_NEW_AND_ENABLE:
$wpPaths = array();
$docroots = ControlPanel::getClassInstance()->getDocRoots();
foreach ( $docroots as $docroot ) {
$wpPaths = array_merge(
$wpPaths,
WPInstallStorage::scan2($docroot)
);
}
$list = array();
if ( $action == WPInstallStorage::CMD_DISCOVER_NEW2
|| $action == WPInstallStorage::CMD_DISCOVER_NEW_AND_ENABLE ) {
foreach( $wpPaths as $wpPath ) {
if ( $wpInstallStorage->getWPInstall($wpPath) == null ) {
$list[] = $wpPath;
}
}
}
else {
$list = array_merge($list, $wpPaths);
}
$originalAction = $action;
$action = WPInstallStorage::CMD_ADD_NEW_WPINSTALL;
break;
// no default case
}
$wpInstallStorage->doAction($action, $list, $extraArgs);
if ( $originalAction == WPInstallStorage::CMD_DISCOVER_NEW_AND_ENABLE ) {
$wpInstallStorage->doAction(
UserCommand::CMD_MASS_ENABLE,
$list
);
}
if ( $action == UserCommand::CMD_STATUS ) {
$wpInstall = $wpInstallStorage->getWPInstall($this->currWpPath);
$this->printStatusMsg($wpInstall);
}
if ( $originalAction != null ) {
$action = $originalAction;
}
echo "\n$action complete!\n\n";
}
}
/**
*
* @throws LSCMException Thrown indirectly by $this->doCacheRootCommand()
* call.
* @throws LSCMException Thrown indirectly by
* ControlPanel::getClassInstance() call.
* @throws LSCMException Thrown indirectly by
* $controlPanel->verifyCacheSetup() call.
* @throws LSCMException Thrown indirectly by $this->displayCacheRoots()
* call.
* @throws LSCMException Thrown indirectly by $this->doSpecialCommand()
* call.
* @throws LSCMException Thrown indirectly by $this->doVersionCommand()
* call.
* @throws LSCMException Thrown indirectly by
* $this->doWPInstallStorageAction() call.
*/
private function runCommand()
{
foreach ( $this->cacheRootCmds as $action ) {
$this->doCacheRootCommand($action);
}
$controlPanel = ControlPanel::getClassInstance();
$controlPanel->verifyCacheSetup();
if ( $this->displayCacheRoots ) {
$this->displayCacheRoots();
}
if ( $this->specialCmd ) {
$this->doSpecialCommand();
}
elseif ( $this->versionCmd ) {
$this->doVersionCommand();
}
else {
$this->doWPInstallStorageAction();
}
}
public static function run()
{
try {
$cli = new self();
$cli->runCommand();
}
catch ( Exception $e ) {
echo "[ERROR] {$e->getMessage()}\n\n";
exit(1);
}
}
}
webcachemgr/src/RedefineGlobalFuncs.php 0000664 00000001541 15055136440 0014162 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright (c) 2021
* @since 1.13.10
* *******************************************
*/
/**
* As of PHP 8.x, functions disabled using ini directive 'disable_functions'
* are no longer included in PHP's functions table and must be redefined to
* avoid fatal error "Call to undefined function" when called.
*
* This file is used to redefine internal PHP functions intentionally disabled
* before loading the WordPress environment.
*/
if ( !function_exists('ini_set') ) {
/**
*
* @since 1.13.10
*
* @param string $option
* @param string $value
*
* @return false
*/
function ini_set( $option, $value)
{
return false;
}
}
webcachemgr/src/Util.php 0000664 00000044236 15055136440 0011246 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2018-2025 LiteSpeed Technologies, Inc.
* *******************************************
*/
namespace Lsc\Wp;
use ZipArchive;
class Util
{
/**
*
* @param string $tag
*
* @return string
*/
public static function get_request_var( $tag )
{
if ( isset($_REQUEST[$tag]) ) {
return trim($_REQUEST[$tag]);
}
/**
* Request var not found in $_REQUEST, try checking POST and
* QUERY_STRING environment variables.
*/
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
$querystring = urldecode(getenv('POST'));
}
else {
$querystring = urldecode(getenv('QUERY_STRING'));
}
if ( $querystring != ''
&& preg_match("/(?:^|\?|&)$tag=([^&]+)/", $querystring, $m) ) {
return trim($m[1]);
}
return null;
}
/**
*
* @param string $tag
*
* @return array
*/
public static function get_request_list( $tag )
{
$varValue = null;
if ( isset($_REQUEST[$tag]) ) {
$varValue = $_REQUEST[$tag];
}
else {
/**
* Request var not found in $_REQUEST, try checking POST and
* QUERY_STRING environment variables.
*/
if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
$querystring = urldecode(getenv('POST'));
}
else {
$querystring = urldecode(getenv('QUERY_STRING'));
}
if ( $querystring != ''
&& preg_match_all("/(?:^|\?|&)$tag\[]=([^&]+)/", $querystring, $m) ) {
$varValue = $m[1];
}
}
return (is_array($varValue)) ? $varValue : null;
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::info() call.
*/
public static function restartLsws()
{
Logger::info('Performing a Graceful Restart to apply changes...');
/**
* @noinspection PhpMethodParametersCountMismatchInspection Suppress
* for PHP 5.x.
*/
if ( php_uname('s') == 'FreeBSD' ) {
$lswsCtl = '/usr/local/etc/rc.d/lsws.sh';
}
else {
$lswsCtl = '/sbin/service lsws';
}
exec("$lswsCtl restart");
}
/**
* @since 2.1.15
*
* @param int $startTime
* @param int $timeout
*
* @return bool
*/
public static function timedOut( $startTime, $timeout )
{
return ((time() - $startTime) > $timeout);
}
/**
* This function is used to get the file owner by name. Useful in cases
* where UID is not accepted or setting a files group to match its owner
* (It is not safe to assume UID == GID or GID exists for username 'x').
*
* @since 2.2.0
*
* @param string $filepath
*
* @return array Keys are id, name, group_id
*/
public static function populateOwnerInfo( $filepath )
{
clearstatcache();
$ownerID = fileowner($filepath);
$ownerInfo = posix_getpwuid($ownerID);
return array(
'user_id' => $ownerID,
'user_name' => $ownerInfo['name'],
'group_id' => filegroup($filepath)
);
}
/**
*
* @param string $file
* @param string $owner
* @param string $group
*/
public static function changeUserGroup( $file, $owner, $group )
{
chown($file, $owner);
chgrp($file, $group);
}
/**
* Set file permissions of $file2 to match those of $file1.
*
* @since 2.2.0
*
* @param string $file1
* @param string $file2
*/
public static function matchPermissions( $file1, $file2 )
{
/**
* convert fileperms() returned dec to oct
*/
chmod($file2, (fileperms($file1) & 0777));
}
/**
*
* @since 1.14.3
*
* @param string $url
* @param bool $headerOnly
*
* @return string
*/
public static function getUrlContentsUsingFileGetContents(
$url,
$headerOnly = false )
{
if ( ini_get('allow_url_fopen') ) {
/**
* silence warning when OpenSSL missing while getting LSCWP ver
* file.
*/
$url_content = @file_get_contents($url);
if ( $url_content !== false ) {
if ( $headerOnly ) {
return implode("\n", $http_response_header);
}
return $url_content;
}
}
return '';
}
/**
*
* @since 1.14.3
*
* @param string $url
* @param bool $headerOnly
*
* @return string
*/
public static function getUrlContentsUsingPhpCurl(
$url,
$headerOnly = false )
{
if ( function_exists('curl_version') ) {
$ch = curl_init();
curl_setopt_array(
$ch,
array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => $headerOnly,
CURLOPT_NOBODY => $headerOnly,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
)
);
$url_content = curl_exec($ch);
curl_close($ch);
if ( $url_content !== false ) {
return $url_content;
}
}
return '';
}
/**
*
* @since 1.14.3
*
* @param string $url
* @param string $headerOnly
*
* @return string
*/
public static function getUrlContentsUsingExecCurl(
$url,
$headerOnly = false )
{
$cmd = 'curl -s';
if ( $headerOnly ) {
$cmd .= ' -I';
}
exec("$cmd $url", $output, $ret);
if ( $ret === 0 ) {
return implode("\n", $output);
}
return '';
}
/**
*
* @param string $url
* @param bool $headerOnly
*
* @return string
*/
public static function get_url_contents( $url, $headerOnly = false )
{
$content = self::getUrlContentsUsingFileGetContents($url, $headerOnly);
if ( $content != '' ) {
return $content;
}
$content = self::getUrlContentsUsingPhpCurl($url, $headerOnly);
if ( $content != '' ) {
return $content;
}
return self::getUrlContentsUsingExecCurl($url, $headerOnly);
}
/**
*
* @param string $dir
*
* @return false|string
*/
public static function DirectoryMd5( $dir )
{
if ( !is_dir($dir) ) {
return false;
}
$fileMd5s = array();
$d = dir($dir);
while ( ($entry = $d->read()) !== false ) {
if ( $entry != '.' && $entry != '..' ) {
$currEntry = "$dir/$entry";
if ( is_dir($currEntry) ) {
$fileMd5s[] = self::DirectoryMd5($currEntry);
}
else {
$fileMd5s[] = md5_file($currEntry);
}
}
}
$d->close();
return md5(implode('', $fileMd5s));
}
/**
*
* @param string $file
* @param string $backup
*
* @return bool
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
private static function matchFileSettings( $file, $backup )
{
clearstatcache();
$ownerID = fileowner($file);
$groupID = filegroup($file);
if ( $ownerID === false || $groupID === false ) {
Logger::debug("Could not get owner/group of file $file");
unlink($backup);
Logger::debug("Removed file $backup");
return false;
}
self::changeUserGroup($backup, $ownerID, $groupID);
self::matchPermissions($file, $backup);
return true;
}
/**
*
* @param string $filepath
* @param string $bak
*
* @return string
*/
private static function getBackupSuffix(
$filepath,
$bak = '_lscachebak_orig' )
{
$i = 1;
if ( file_exists($filepath . $bak) ) {
$bak = sprintf("_lscachebak_%02d", $i);
while ( file_exists($filepath . $bak) ) {
$i++;
$bak = sprintf("_lscachebak_%02d", $i);
}
}
return $bak;
}
/**
*
* @param string $filepath
*
* @return bool
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
* @throws LSCMException Thrown indirectly by Logger::verbose() call.
* @throws LSCMException Thrown indirectly by self::matchFileSettings()
* call.
* @throws LSCMException Thrown indirectly by Logger::debug() call.
* @throws LSCMException Thrown indirectly by Logger::debug() call.
* @throws LSCMException Thrown indirectly by Logger::info() call.
*/
public static function createBackup( $filepath )
{
$backup = $filepath . self::getBackupSuffix($filepath);
if ( !copy($filepath, $backup) ) {
Logger::debug(
"Could not backup file $filepath to location $backup"
);
return false;
}
Logger::verbose("Created file $backup");
if ( !self::matchFileSettings($filepath, $backup) ) {
Logger::debug(
"Could not backup file $filepath to location $backup"
);
return false;
}
Logger::debug('Matched owner/group setting for both files');
Logger::info(
"Successfully backed up file $filepath to location $backup"
);
return true;
}
/**
*
* @param string $zipFile
* @param string $dest
*
* @return bool
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
public static function unzipFile( $zipFile, $dest )
{
if ( class_exists('\ZipArchive') ) {
$zipArchive = new ZipArchive();
if ( $zipArchive->open($zipFile) === true ) {
$extracted = $zipArchive->extractTo($dest);
$zipArchive->close();
if ( $extracted ) {
return true;
}
}
Logger::debug("Could not unzip $zipFile using ZipArchive.");
}
$output = array();
exec(
"unzip $zipFile -d $dest > /dev/null 2>&1",
$output,
$return_var
);
if ( $return_var == 0 ) {
return true;
}
else {
Logger::debug("Could not unzip $zipFile from cli.");
}
return false;
}
/**
* Check if a given directory is empty.
*
* @param string $dir
*
* @return bool
*/
public static function is_dir_empty( $dir )
{
if ( !($handle = @opendir($dir)) ) {
return true;
}
while ( ($entry = readdir($handle)) !== false ) {
if ( $entry != '.' && $entry != '..' ) {
return false;
}
}
return true;
}
/**
*
* @param string $vhCacheRoot
*/
public static function ensureVHCacheRootInCage( $vhCacheRoot )
{
$cageFsFile = '/etc/cagefs/cagefs.mp';
if ( file_exists($cageFsFile) ) {
if ( $vhCacheRoot[0] == '/' ) {
$cageVhCacheRoot =
'%' . str_replace('/$vh_user', '', $vhCacheRoot);
$matchFound = preg_grep(
"!^\s*" . str_replace('!', '\!', $cageVhCacheRoot) . "!im",
file($cageFsFile)
);
if ( !$matchFound ) {
file_put_contents(
$cageFsFile,
"\n$cageVhCacheRoot",
FILE_APPEND
);
exec('/usr/sbin/cagefsctl --remount-all');
}
}
}
}
/**
* Recursively a directory's contents and optionally the directory itself.
*
* @param string $dir Directory path
* @param bool $keepParent Only remove directory contents when true.
*
* @return bool
*/
public static function rrmdir( $dir, $keepParent = false )
{
if ( $dir != '' && is_dir($dir) ) {
if ( ($matches = glob("$dir/*")) === false ) {
return false;
}
foreach ( $matches as $file ) {
if ( is_dir($file) ) {
self::rrmdir($file);
}
else {
unlink($file);
}
}
if ( !$keepParent ) {
rmdir($dir);
}
return true;
}
return false;
}
/**
* Wrapper for idn_to_utf8() function call to avoid "undefined" exceptions
* when PHP intl module is not installed and enabled.
*
* @since 1.13.13.1
*
* @param string $domain
* @param int $flags
* @param int|null $variant
* @param array|null $idna_info
*
* @return false|string
*/
public static function tryIdnToUtf8(
$domain,
$flags = 0,
$variant = null,
&$idna_info = null
)
{
if ( empty($domain) || !function_exists('idn_to_utf8') ) {
return $domain;
}
if ( $variant == null ) {
$variant = INTL_IDNA_VARIANT_UTS46;
}
return idn_to_utf8($domain, $flags, $variant, $idna_info);
}
/**
* Wrapper for idn_to_ascii() function call to avoid "undefined" exceptions
* when PHP intl module is not installed and enabled.
*
* @since 1.13.13.1
*
* @param string $domain
* @param int|null $flags
* @param int|null $variant
* @param array|null $idna_info
*
* @return false|string
*/
public static function tryIdnToAscii(
$domain,
$flags = null,
$variant = null,
&$idna_info = null
)
{
if ( empty($domain) || !function_exists('idn_to_ascii') ) {
return $domain;
}
if ( $flags == null ) {
$flags = IDNA_DEFAULT;
}
if ( $variant == null ) {
$variant = INTL_IDNA_VARIANT_UTS46;
}
return idn_to_ascii($domain, $flags, $variant, $idna_info);
}
/**
* Version comparison function capable of properly comparing versions with
* trailing ".0" groups such as '6.1' which is equal to '6.1.0' which is
* equal to '6.1.000.0' etc.
*
* @since 1.14.2
*
* @param string $ver1
* @param string $ver2
* @param string|null $operator
*
* @return bool|int
*/
public static function betterVersionCompare(
$ver1,
$ver2,
$operator = null )
{
$pattern = '/(\.0+)+($|-)/';
return version_compare(
preg_replace($pattern, '', $ver1),
preg_replace($pattern, '', $ver2),
$operator
);
}
/**
*
* @since 1.15.0.1
*
* @param string $constantName
* @param array|bool|float|int|null|string $value
* @param bool $caseInsensitive Optional
* parameter used for define calls in PHP versions below 7.3.
*
* @return bool
*
* @noinspection PhpDeprecationInspection Ignore deprecation of define()
* parameter $case_insensitive for PHP versions below 7.3.
* @noinspection RedundantSuppression
*/
public static function define_wrapper(
$constantName,
$value,
$caseInsensitive = false )
{
if ( PHP_VERSION_ID < 70300 ) {
return define($constantName, $value, $caseInsensitive);
}
else {
return define($constantName, $value);
}
}
/**
*
* @since 1.17.1.1
*
* @param int $wpStatus
*
* @return string[] [ stateMsg => string, link => string ]
*/
public static function getFatalErrorStateMessageAndLink( $wpStatus )
{
$stateMsg = $anchor = '';
if ( $wpStatus & WPInstall::ST_ERR_EXECMD ) {
$stateMsg = 'WordPress fatal error encountered during action '
. 'execution. This is most likely caused by custom code in '
. 'this WordPress installation.';
$anchor = '#fatal-error-encountered-during-action-execution';
}
if ( $wpStatus & WPInstall::ST_ERR_EXECMD_DB ) {
$stateMsg = 'Error establishing WordPress database connection.';
}
elseif ( $wpStatus & WPInstall::ST_ERR_TIMEOUT ) {
$stateMsg = 'Timeout occurred during action execution.';
$anchor = '#timeout-occurred-during-action-execution';
}
elseif ( $wpStatus & WPInstall::ST_ERR_SITEURL ) {
$stateMsg = 'Could not retrieve WordPress siteURL.';
$anchor = '#could-not-retrieve-wordpress-siteurl';
}
elseif ( $wpStatus & WPInstall::ST_ERR_DOCROOT ) {
$stateMsg = 'Could not match WordPress siteURL to a known '
. 'control panel docroot.';
$anchor = '#could-not-match-wordpress-siteurl-to-a-known-'
. 'cpanel-docroot';
}
elseif ( $wpStatus & WPInstall::ST_ERR_WPCONFIG ) {
$stateMsg = 'Could not find a valid wp-config.php file.';
$anchor = '#could-not-find-a-valid-wp-configphp-file';
}
$stateMsg .= ' Click for more information.';
return array(
'stateMsg' => $stateMsg,
'link' => 'https://docs.litespeedtech.com/lsws/cp/cpanel/'
. "whm-litespeed-plugin/troubleshooting/$anchor"
);
}
}
webcachemgr/src/AjaxResponse.php 0000664 00000003453 15055136440 0012727 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2019-2025 LiteSpeed Technologies, Inc.
* @since 1.9
* *******************************************
*/
namespace Lsc\Wp;
/**
* @since 1.9
*/
class AjaxResponse
{
/**
* @since 1.9
* @var AjaxResponse
*/
protected static $instance;
/**
* @since 1.9
* @var string
*/
protected $ajaxContent;
/**
* @since 1.9
* @var string
*/
protected $headerContent;
/**
*
* @since 1.9
*/
private function __construct()
{
}
/**
*
* @since 1.9
*
* @return AjaxResponse
*/
private static function me()
{
if ( self::$instance == null ) {
self::$instance = new self();
}
return self::$instance;
}
/**
*
* @since 1.9
*
* @throws LSCMException
*/
public static function outputAndExit()
{
$output = '';
if ( self::$instance == null ) {
throw new LSCMException('AjaxResponse object never created!');
}
$m = self::me();
if ( !empty($m->headerContent) ) {
$output .= "{$m->headerContent}\n\n";
}
$output .= $m->ajaxContent;
ob_clean();
echo $output;
exit;
}
/**
*
* @since 1.9
*
* @param string $ajaxContent
*/
public static function setAjaxContent( $ajaxContent )
{
self::me()->ajaxContent = $ajaxContent;
}
/**
*
* @since 1.9
*
* @param string $headerContent
*/
public static function setHeaderContent( $headerContent )
{
self::me()->headerContent = $headerContent;
}
}
webcachemgr/src/Logger.php 0000664 00000043712 15055136440 0011546 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2018-2023 LiteSpeed Technologies, Inc.
* *******************************************
*/
namespace Lsc\Wp;
use Lsc\Wp\Context\ContextOption;
/**
* Logger is a pseudo singleton.
*
* Public Logger functions starting with 'p_' are intended for internal use to
* account for $instance sometimes being of a different non-extending logger
* class.
*/
class Logger
{
/**
* @var int
*/
const L_NONE = 0;
/**
* @var int
*/
const L_ERROR = 1;
/**
* @var int
*/
const L_WARN = 2;
/**
* @var int
*/
const L_NOTICE = 3;
/**
* @var int
*/
const L_INFO = 4;
/**
* @var int
*/
const L_VERBOSE = 5;
/**
* @var int
*/
const L_DEBUG = 9;
/**
* @var int
*/
const UI_INFO = 0;
/**
* @var int
*/
const UI_SUCC = 1;
/**
* @var int
*/
const UI_ERR = 2;
/**
* @var int
*/
const UI_WARN = 3;
/**
* @var null|Logger|object Object that implements all Logger class public
* functions (minus setInstance()). Caution, this requirement is not
* enforced in the code.
*/
protected static $instance;
/**
* @var int Highest log message level allowed to be logged. Set to the
* higher value between $this->logFileLvl and $this->logEchoLvl.
*/
protected $logLvl;
/**
* @var string File that log messages will be written to (if writable).
*/
protected $logFile;
/**
* @var int Highest log message level allowed to be written to the log
* file.
*/
protected $logFileLvl;
/**
* @var string Additional tag to be added at the start of any log messages.
*/
protected $addTagInfo = '';
/**
* @var bool When set to true, log messages will not be written to the log
* file until this logger object is destroyed.
*/
protected $bufferedWrite;
/**
* @var LogEntry[]|object[] Stores created objects that implement all
* LogEntry class public functions.
*/
protected $msgQueue = array();
/**
* @var int Highest log message level allowed to echo.
*/
protected $logEchoLvl;
/**
* @var bool When set to true, echoing of log messages is suppressed.
*/
protected $bufferedEcho;
/**
* @var string[][] Leveraged by control panel GUI to store and retrieve
* display messages. Also used as temporary storage for display only
* messages by UserCommand.
*/
protected $uiMsgs = array(
self::UI_INFO => array(),
self::UI_SUCC => array(),
self::UI_ERR => array(),
self::UI_WARN => array()
);
/**
*
* @param ContextOption $ctxOption
*/
final protected function __construct( ContextOption $ctxOption )
{
$this->logFile = $ctxOption->getDefaultLogFile();
$this->logFileLvl = $ctxOption->getLogFileLvl();
$this->bufferedWrite = $ctxOption->isBufferedWrite();
$this->logEchoLvl = $ctxOption->getLogEchoLvl();
$this->bufferedEcho = $ctxOption->isBufferedEcho();
$this->logLvl = max($this->logEchoLvl, $this->logFileLvl);
}
/**
*
* @throws LSCMException Thrown indirectly by $this->writeToFile() call.
*/
public function __destruct()
{
if ( $this->bufferedWrite ) {
$this->writeToFile($this->msgQueue);
}
}
/**
*
* @param ContextOption $contextOption
*
* @throws LSCMException Thrown when a static Logger instance has already
* been initialized.
*/
public static function Initialize( ContextOption $contextOption )
{
if ( static::$instance != null ) {
throw new LSCMException(
'Logger cannot be initialized twice.',
LSCMException::E_PROGRAM
);
}
static::$instance = new static($contextOption);
}
/**
* Set static::$instance to a pre-created logger object.
*
* This function is intended as an alternative to Initialize() and will
* throw an exception if static::$instance is already set.
*
* @since 1.9.1
*
* @param object $loggerObj
*
* @throws LSCMException Thrown when Logger instance is already set.
*/
public static function setInstance( $loggerObj )
{
if ( static::$instance != null ) {
throw new LSCMException(
'Logger instance already set.',
LSCMException::E_PROGRAM
);
}
static::$instance = $loggerObj;
}
/**
*
* @since 1.9
*
* @param string $logFile
*
* @throws LSCMException Thrown indirectly by static::me() call.
*/
public static function changeLogFileUsed( $logFile )
{
static::me()->p_setLogFile($logFile);
}
/**
*
* @since 1.9
*
* @param string $addInfo
*
* @throws LSCMException Thrown indirectly by static::me() call.
*/
public static function setAdditionalTagInfo( $addInfo )
{
static::me()->p_setAddTagInfo($addInfo);
}
/**
*
* @since 1.9.1
*
* @param string $msg
* @param int $type
*/
public function p_addUiMsg( $msg, $type )
{
switch ($type) {
case static::UI_INFO:
case static::UI_SUCC:
case static::UI_ERR:
case static::UI_WARN:
$this->uiMsgs[$type][] = $msg;
break;
//no default
}
}
/**
*
* @since 1.9.1
*
* @param LogEntry[]|object[] $entries Array of objects that implement all
* LogEntry class public functions.
*
* @throws LSCMException Thrown indirectly by $this->echoEntries() call.
*/
public function p_echoEntries( array $entries )
{
$this->echoEntries($entries);
}
/**
*
* @since 1.9.1
*
* @return string
*/
public function p_getAddTagInfo()
{
return $this->addTagInfo;
}
/**
*
* @since 1.9.1
*
* @return bool
*/
public function p_getBufferedEcho()
{
return $this->bufferedEcho;
}
/**
*
* @since 1.9.1
*
* @return bool
*/
public function p_getBufferedWrite()
{
return $this->bufferedWrite;
}
/**
*
* @since 1.9.1
*
* @return string
*/
public function p_getLogFile()
{
return $this->logFile;
}
/**
*
* @since 1.9.1
*
* @return LogEntry[]|object[]
*/
public function p_getMsgQueue()
{
return $this->msgQueue;
}
/**
*
* @since 1.9.1
*
* @param int $type
*
* @return string[]
*/
public function p_getUiMsgs( $type )
{
switch ($type) {
case static::UI_INFO:
case static::UI_SUCC:
case static::UI_ERR:
case static::UI_WARN:
return $this->uiMsgs[$type];
default:
return array();
}
}
/**
*
* @since 1.9.1
*
* @param string $msg
* @param int $lvl
*
* @throws LSCMException Thrown indirectly by $this->log() call.
*/
public function p_log( $msg, $lvl )
{
$this->log($msg, $lvl);
}
/**
*
* @since 1.9.1
*
* @param string $addInfo
*/
public function p_setAddTagInfo( $addInfo )
{
$this->addTagInfo = $addInfo;
}
/**
*
* @since 1.9.1
*
* @param string $logFile
*/
public function p_setLogFile( $logFile )
{
$this->logFile = $logFile;
}
/**
*
* @since 1.9.1
*
* @param int $logFileLvl
*/
public function p_setLogFileLvl( $logFileLvl )
{
$this->logFileLvl = $logFileLvl;
}
/**
*
* @since 1.9.1
*
* @param LogEntry[]|object[] $msgQueue
*/
public function p_setMsgQueue( array $msgQueue )
{
$this->msgQueue = $msgQueue;
}
/**
*
* @since 1.9.1
*
* @param LogEntry[]|object[] $entries Array of objects that implement all
* LogEntry class public functions.
*
* @throws LSCMException Thrown indirectly by $this->writeToFile() call.
*/
public function p_writeToFile( array $entries )
{
$this->writeToFile($entries);
}
/**
*
* @since 1.9
*
* @return string
*
* @throws LSCMException Thrown indirectly by static::me() call.
*/
public static function getAdditionalTagInfo()
{
return static::me()->p_getAddTagInfo();
}
/**
*
* @since 1.9
*
* @return string
*
* @throws LSCMException Thrown indirectly by static::me() call.
*/
public static function getLogFilePath()
{
return static::me()->p_getLogFile();
}
/**
*
* @since 1.9
*
* @return LogEntry[]|object[] Array of objects that implement all LogEntry
* class public functions.
*
* @throws LSCMException Thrown indirectly by static::me() call.
*/
public static function getLogMsgQueue()
{
return static::me()->p_getMsgQueue();
}
/**
*
* @param int $type
*
* @return string[]
*
* @throws LSCMException Thrown indirectly by static::me() call.
*/
public static function getUiMsgs( $type )
{
return static::me()->p_getUiMsgs($type);
}
/**
* Processes any buffered output, writing it to the log file, echoing it
* out, or both.
*
* @throws LSCMException Thrown indirectly by static::me() call.
* @throws LSCMException Thrown indirectly by $m->p_writeToFile() call.
* @throws LSCMException Thrown indirectly by $m->p_echoEntries() call.
*/
public static function processBuffer()
{
$clear = false;
$m = static::me();
if ( $m->p_getBufferedWrite() ) {
$m->p_writeToFile($m->p_getMsgQueue());
$clear = true;
}
if ( $m->p_getBufferedEcho() ) {
$m->p_echoEntries($m->p_getMsgQueue());
$clear = true;
}
if ( $clear ) {
$m->p_setMsgQueue(array());
}
}
/**
* Deprecated 06/25/19. Visibility going to be changed to "protected".
*
* @deprecated
*
* @param string $msg
* @param int $type
*
* @throws LSCMException Thrown indirectly by static::me() call.
*/
public static function addUiMsg( $msg, $type )
{
static::me()->p_addUiMsg($msg, $type);
}
/**
* Calls addUiMsg() with message level static::UI_INFO.
*
* @param string $msg
*
* @throws LSCMException Thrown indirectly by static::addUiMsg() call.
*/
public static function uiInfo( $msg )
{
static::addUiMsg($msg, static::UI_INFO);
}
/**
* Calls addUiMsg() with message level static::UI_SUCC.
*
* @param string $msg
*
* @throws LSCMException Thrown indirectly by static::addUiMsg() call.
*/
public static function uiSuccess( $msg )
{
static::addUiMsg($msg, static::UI_SUCC);
}
/**
* Calls addUiMsg() with message level static::UI_ERR.
*
* @param string $msg
*
* @throws LSCMException Thrown indirectly by static::addUiMsg() call.
*/
public static function uiError( $msg )
{
static::addUiMsg($msg, static::UI_ERR);
}
/**
* Calls addUiMsg() with message level static::UI_WARN.
*
* @param string $msg
*
* @throws LSCMException Thrown indirectly by static::addUiMsg() call.
*/
public static function uiWarning( $msg )
{
static::addUiMsg($msg, static::UI_WARN);
}
/**
*
* @param string $msg
* @param int $lvl
*
* @throws LSCMException Thrown indirectly by static::me() call.
* @throws LSCMException Thrown indirectly by static::me()->p_log() call.
*/
public static function logMsg( $msg, $lvl )
{
static::me()->p_log($msg, $lvl);
}
/**
* Calls logMsg() with message level static::L_ERROR.
*
* @param string $msg
*
* @throws LSCMException Thrown indirectly by static::logMsg() call.
*/
public static function error( $msg )
{
static::logMsg($msg, static::L_ERROR);
}
/**
* Calls logMsg() with message level static::L_WARN.
*
* @param string $msg
*
* @throws LSCMException Thrown indirectly by static::logMsg() call.
*/
public static function warn( $msg )
{
static::logMsg($msg, static::L_WARN);
}
/**
* Calls logMsg() with message level static::L_NOTICE.
*
* @param string $msg
*
* @throws LSCMException Thrown indirectly by static::logMsg() call.
*/
public static function notice( $msg )
{
static::logMsg($msg, static::L_NOTICE);
}
/**
* Calls logMsg() with message level static::L_INFO.
*
* @param string $msg
*
* @throws LSCMException Thrown indirectly by static::logMsg() call.
*/
public static function info( $msg )
{
static::logMsg($msg, static::L_INFO);
}
/**
* Calls logMsg() with message level static::L_VERBOSE.
*
* @param string $msg
*
* @throws LSCMException Thrown indirectly by static::logMsg() call.
*/
public static function verbose( $msg )
{
static::logMsg($msg, static::L_VERBOSE);
}
/**
* Calls logMsg() with message level static::L_DEBUG.
*
* @param string $msg
*
* @throws LSCMException Thrown indirectly by static::logMsg() call.
*/
public static function debug( $msg )
{
static::logMsg($msg, static::L_DEBUG);
}
/**
*
* @return Logger|object Object that implements all Logger class public
* functions.
*
* @throws LSCMException Thrown when Logger instance has not yet been
* initialized.
*/
protected static function me()
{
if ( static::$instance == null ) {
throw new LSCMException(
'Logger Uninitialized.',
LSCMException::E_PROGRAM
);
}
return static::$instance;
}
/**
*
* @param string $msg
* @param int $lvl
*
* @throws LSCMException Thrown indirectly by $this->writeToFile() call.
* @throws LSCMException Thrown indirectly by $this->echoEntries() call.
*/
protected function log( $msg, $lvl )
{
$entry = new LogEntry($msg, $lvl);
$this->msgQueue[] = $entry;
if ( !$this->bufferedWrite ) {
$this->writeToFile(array( $entry ));
}
if ( !$this->bufferedEcho ) {
$this->echoEntries(array( $entry ));
}
}
/**
*
* @param LogEntry[]|object[] $entries Array of objects that implements all
* LogEntry class public functions.
*
* @throws LSCMException Thrown indirectly by $e->getOutput() call.
*/
protected function writeToFile( array $entries )
{
$content = '';
foreach ( $entries as $e ) {
$content .= $e->getOutput($this->logFileLvl);
}
if ( $content != '' ) {
if ( $this->logFile ) {
file_put_contents(
$this->logFile,
$content,
FILE_APPEND | LOCK_EX
);
}
else {
error_log($content);
}
}
}
/**
*
* @param LogEntry[]|object[] $entries Array of objects that implement all
* LogEntry class public functions.
*
* @throws LSCMException Thrown indirectly by $entry->getOutput() call.
*/
protected function echoEntries( array $entries )
{
foreach ( $entries as $entry ) {
if ( ($msg = $entry->getOutput($this->logEchoLvl)) !== '' ) {
echo $msg;
}
}
}
/**
*
* @param int $lvl
*
* @return string
*/
public static function getLvlDescr( $lvl )
{
switch ($lvl) {
case static::L_ERROR:
return 'ERROR';
case static::L_WARN:
return 'WARN';
case static::L_NOTICE:
return 'NOTICE';
case static::L_INFO:
return 'INFO';
case static::L_VERBOSE:
return 'DETAIL';
case static::L_DEBUG:
return 'DEBUG';
default:
/**
* Do silently.
*/
return '';
}
}
/**
* Not used yet. Added for later cases where shared log level should be
* changed to match panel log level.
*
* @deprecated 1.9.1 Deprecated on 11/22/19. Function is likely not needed
* after recent logger changes.
*
* @param int $lvl
*
* @return bool
*
* @throws LSCMException Thrown indirectly by static::me() call.
*/
public static function setLogFileLvl( $lvl )
{
$lvl = (int)$lvl;
if ( static::isValidLogFileLvl($lvl) ) {
if ( $lvl > static::L_DEBUG ) {
$lvl = static::L_DEBUG;
}
static::me()->p_setLogFileLvl($lvl);
return true;
}
return false;
}
/**
*
* @param int $lvl
*
* @return bool
*/
protected static function isValidLogFileLvl( $lvl )
{
if ( is_int($lvl) && $lvl >= 0 ) {
return true;
}
return false;
}
/**
* Prevent cloning here and in extending classes.
*/
final protected function __clone() {}
}
webcachemgr/src/WpWrapper/WpConstants.php 0000664 00000001202 15055136440 0014525 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2023 LiteSpeed Technologies, Inc.
* @since 1.17
* *******************************************
*/
namespace Lsc\Wp\WpWrapper;
/**
* Wrapper class used to retrieve the value of WordPress core code specific
* global constants.
*
* @since 1.17
*/
class WpConstants
{
/**
*
* @since 1.17
*
* @param string $constantName
*
* @return mixed
*/
public static function getWpConstant( $constantName )
{
return constant($constantName);
}
} webcachemgr/src/WpWrapper/WpFuncs.php 0000664 00000021070 15055136440 0013634 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2023 LiteSpeed Technologies, Inc.
* @since 1.17
* *******************************************
*/
namespace Lsc\Wp\WpWrapper;
/**
* Wrapper class containing functions used to make WordPress core code specific
* calls.
*
* @since 1.17
*/
class WpFuncs
{
/**
* https://developer.wordpress.org/reference/functions/switch_to_blog/
*
* @since 1.17
*
* @param int $id
*
* @return true
*/
public static function switchToBlog( $id )
{
/** @noinspection PhpUndefinedFunctionInspection */
return switch_to_blog($id);
}
/**
* https://developer.wordpress.org/reference/functions/restore_current_blog/
*
* @since 1.17
*
* @return bool
*/
public static function restoreCurrentBlog()
{
/** @noinspection PhpUndefinedFunctionInspection */
return restore_current_blog();
}
/**
* https://developer.wordpress.org/reference/functions/get_option/
*
* @since 1.17
*
* @param string $option
* @param mixed $defaultValue
*
* @return mixed
*/
public static function getOption( $option, $defaultValue = false )
{
/** @noinspection PhpUndefinedFunctionInspection */
return get_option($option, $defaultValue);
}
/**
* https://developer.wordpress.org/reference/classes/wpdb/get_var/
*
* @since 1.17
*
* @param string|null $query
* @param int $x
* @param int $y
*
* @return string|null
*/
public static function getVar( $query = null, $x = 0, $y = 0 )
{
global $wpdb;
return $wpdb->get_var($query, $x, $y);
}
/**
* https://developer.wordpress.org/reference/functions/is_plugin_active/
*
* @since 1.17
*
* @param string $plugin
*
* @return bool
*/
public static function isPluginActive( $plugin )
{
/** @noinspection PhpUndefinedFunctionInspection */
return is_plugin_active($plugin);
}
/**
* https://developer.wordpress.org/reference/functions/is_plugin_active_for_network/
*
* @since 1.17
*
* @param string $plugin
*
* @return bool
*/
public static function isPluginActiveForNetwork( $plugin )
{
/** @noinspection PhpUndefinedFunctionInspection */
return is_plugin_active_for_network($plugin);
}
/**
* https://developer.wordpress.org/reference/functions/wp_filesystem/
*
* @since 1.17
*
* @param array|false $args
* @param string|false $context
* @param bool $allow_relaxed_file_ownership
*
* @return bool|null
*/
public static function WpFilesystem(
$args = false,
$context = false,
$allow_relaxed_file_ownership = false )
{
/** @noinspection PhpUndefinedFunctionInspection */
return WP_Filesystem($args, $context, $allow_relaxed_file_ownership);
}
/**
* https://developer.wordpress.org/reference/functions/unzip_file/
*
* @since 1.17
*
* @param string $file
* @param string $to
*
* @return true|WP_Error
*
* @noinspection PhpUndefinedClassInspection
*
*/
public static function unzipFile( $file, $to )
{
/** @noinspection PhpUndefinedFunctionInspection */
return unzip_file($file, $to);
}
/**
* https://developer.wordpress.org/reference/functions/deactivate_plugins/
*
* @since 1.17
*
* @param string|string[] $plugins
* @param bool $silent
* @param bool|null $network_wide
*/
public static function deactivatePlugins(
$plugins,
$silent = false,
$network_wide = null )
{
/** @noinspection PhpUndefinedFunctionInspection */
deactivate_plugins($plugins, $silent, $network_wide);
}
/**
* https://developer.wordpress.org/reference/functions/delete_plugins/
*
* @since 1.17
*
* @param string[] $plugins
*
* @return bool|null|WP_Error
*
* @noinspection PhpUndefinedClassInspection
*/
public static function deletePlugins( array $plugins )
{
/** @noinspection PhpUndefinedFunctionInspection */
return delete_plugins($plugins);
}
/**
* https://developer.wordpress.org/reference/functions/activate_plugin/
*
* @since 1.17
*
* @param string $plugin
* @param string $redirect
* @param bool $network_wide
* @param bool $silent
*
* @return null|WP_Error
*
* @noinspection PhpUndefinedClassInspection
*/
public static function activatePlugin(
$plugin,
$redirect = '',
$network_wide = false,
$silent = false )
{
/** @noinspection PhpUndefinedFunctionInspection */
return activate_plugin($plugin, $redirect, $network_wide, $silent);
}
/**
* https://developer.wordpress.org/reference/functions/add_filter/
*
* @since 1.17
*
* @param string $hook_name
* @param callable $callback
* @param int $priority
* @param int $accepted_args
*
* @return true
*/
public static function addFilter(
$hook_name,
callable $callback,
$priority = 10,
$accepted_args = 1 )
{
/** @noinspection PhpUndefinedFunctionInspection */
return add_filter($hook_name, $callback, $priority, $accepted_args);
}
/**
* https://developer.wordpress.org/reference/functions/remove_filter/
*
* @since 1.17
*
* @param string $hook_name
* @param callable|string|array $callback
* @param int $priority
*
* @return bool
*/
public static function removeFilter( $hook_name, $callback, $priority = 10 )
{
/** @noinspection PhpUndefinedFunctionInspection */
return remove_filter($hook_name, $callback, $priority);
}
/**
* https://developer.wordpress.org/reference/functions/is_wp_error/
*
* @since 1.17
*
* @param mixed $thing
*
* @return bool
*/
public static function isWpError( $thing )
{
/** @noinspection PhpUndefinedFunctionInspection */
return is_wp_error($thing);
}
/**
* https://developer.wordpress.org/reference/functions/wp_clean_plugins_cache/
*
* @since 1.17
*
* @param bool $clear_update_cache
*/
public static function wpCleanPluginsCache( $clear_update_cache = true )
{
/** @noinspection PhpUndefinedFunctionInspection */
wp_clean_plugins_cache($clear_update_cache);
}
/**
* https://developer.wordpress.org/reference/functions/get_plugin_data/
*
* @since 1.17
*
* @param string $plugin_file
* @param bool $markup
* @param bool $translate
*
* @return array
*/
public static function getPluginData(
$plugin_file,
$markup = true,
$translate = true )
{
/** @noinspection PhpUndefinedFunctionInspection */
return get_plugin_data($plugin_file, $markup, $translate);
}
/**
* https://developer.wordpress.org/reference/functions/get_locale/
*
* @since 1.17
*
* @return string
*/
public static function getLocale()
{
/** @noinspection PhpUndefinedFunctionInspection */
return get_locale();
}
/**
* https://developer.wordpress.org/reference/functions/apply_filters/
*
* @since 1.17
*
* @param string $hook_name
* @param mixed $value
* @param mixed $args
*
* @return mixed
*/
public static function applyFilters( $hook_name, $value, $args )
{
/** @noinspection PhpUndefinedFunctionInspection */
return apply_filters($hook_name, $value, $args);
}
/**
* https://developer.wordpress.org/reference/functions/wp_plugin_directory_constants/
*
* @since 1.17
*/
public static function wpPluginDirectoryConstants()
{
/** @noinspection PhpUndefinedFunctionInspection */
wp_plugin_directory_constants();
}
/**
* https://developer.wordpress.org/reference/functions/wp_cookie_constants/
*
* @since 1.17
*/
public static function wpCookieConstants()
{
/** @noinspection PhpUndefinedFunctionInspection */
wp_cookie_constants();
}
} webcachemgr/src/WpWrapper/WpTextdomainRegistry.php 0000664 00000002021 15055136440 0016416 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2023 LiteSpeed Technologies, Inc.
* @since 1.17
* *******************************************
*/
namespace Lsc\Wp\WpWrapper;
/**
* https://developer.wordpress.org/reference/classes/wp_textdomain_registry/
*
* @since 1.17
*/
class WpTextdomainRegistry
{
/**
* @since 1.17
* @var \WP_Textdomain_Registry
*
* @noinspection PhpUndefinedClassInspection
*/
private $wpTextdomainRegistry;
/**
*
* @since 1.17
*/
public function __construct()
{
/** @noinspection PhpUndefinedClassInspection */
$this->wpTextdomainRegistry = new \WP_Textdomain_Registry();
}
/**
*
* @since 1.17
*
* @return \WP_Textdomain_Registry
*
* @noinspection PhpUndefinedClassInspection
*/
public function getWpWpTextdomainRegistryObject()
{
return $this->wpTextdomainRegistry;
}
} webcachemgr/src/WpWrapper/PluginUpgrader.php 0000664 00000004657 15055136440 0015213 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2023-2025 LiteSpeed Technologies, Inc.
* @since 1.17
* *******************************************
*/
namespace Lsc\Wp\WpWrapper;
/**
* https://developer.wordpress.org/reference/classes/plugin_upgrader/
*
* @since 1.17
*/
class PluginUpgrader
{
/**
* https://developer.wordpress.org/reference/classes/plugin_upgrader/
*
* @since 1.17
* @var \Plugin_Upgrader
*
* @noinspection PhpUndefinedClassInspection
*/
private $pluginUpgrader;
/**
* https://developer.wordpress.org/reference/classes/wp_upgrader/__construct/
*
* @since 1.17
*
* @param \WP_Upgrader_Skin|null $skin
*
* @noinspection PhpDeprecatedImplicitlyNullableParameterInspection
* @noinspection PhpFullyQualifiedNameUsageInspection
* @noinspection PhpUndefinedClassInspection
* @noinspection RedundantSuppression
*/
public function __construct( \WP_Upgrader_Skin $skin = null )
{
/** @noinspection PhpUndefinedClassInspection */
$this->pluginUpgrader = new \Plugin_Upgrader($skin);
}
/**
*
* @since 1.17
*
* @return \Plugin_Upgrader
*
* @noinspection PhpUndefinedClassInspection
*/
public function getWpPluginUpgraderObject()
{
return $this->pluginUpgrader;
}
/**
*
* @since 1.17
*
* @return array|WP_Error
*
* @noinspection PhpUndefinedClassInspection
*/
public function getResult()
{
return $this->pluginUpgrader->result;
}
/**
* https://developer.wordpress.org/reference/classes/wp_upgrader/init/
*
* @since 1.17
*/
public function init()
{
$this->pluginUpgrader->init();
}
/**
* https://developer.wordpress.org/reference/classes/plugin_upgrader/upgrade_strings/
*
* @since 1.17
*/
public function upgradeStrings()
{
$this->pluginUpgrader->upgrade_strings();
}
/**
* https://developer.wordpress.org/reference/classes/wp_upgrader/run/
*
* @since 1.17
*
* @param array $options
*
* @return array|false|WP_Error
*
* @noinspection PhpUndefinedClassInspection
*/
public function run( array $options )
{
return $this->pluginUpgrader->run($options);
}
} webcachemgr/src/WpWrapper/Wpdb.php 0000664 00000002162 15055136441 0013145 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2023 LiteSpeed Technologies, Inc.
* @since 1.7
* *******************************************
*/
namespace Lsc\Wp\WpWrapper;
/**
* https://developer.wordpress.org/reference/classes/wpdb/
*
* @since 1.17
*/
class Wpdb
{
/**
* https://developer.wordpress.org/reference/classes/wpdb/
*
* @since 1.17
*
* @global \wpdb $wpdb
*
* @return string
*
* @noinspection PhpUndefinedClassInspection
*/
public static function getBlogs()
{
global $wpdb;
return $wpdb->blogs;
}
/**
* https://developer.wordpress.org/reference/classes/wpdb/get_col/
*
* @since 1.17
*
* @global \wpdb $wpdb
*
* @param string|null $query
* @param int $x
*
* @return array
*
* @noinspection PhpUndefinedClassInspection
*/
public static function getCol( $query = null, $x = 0 )
{
global $wpdb;
return $wpdb->get_col($query, $x);
}
} webcachemgr/src/WpWrapper/WpQuery.php 0000664 00000002043 15055136441 0013663 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2023 LiteSpeed Technologies, Inc.
* @since 1.17
* *******************************************
*/
namespace Lsc\Wp\WpWrapper;
/**
* https://developer.wordpress.org/reference/classes/wp_query/
*
* @since 1.17
*/
class WpQuery
{
/**
* @since 1.17
* @var \WP_Query
*
* @noinspection PhpUndefinedClassInspection
*/
private $wpQuery;
/**
* https://developer.wordpress.org/reference/classes/wp_query/__construct/
*
* @since 1.17
*
* @param string|array $query
*/
public function __construct( $query = '' )
{
/** @noinspection PhpUndefinedClassInspection */
$this->wpQuery = new \WP_Query($query);
}
/**
*
* @since 1.17
*
* @return \WP_Query
*
* @noinspection PhpUndefinedClassInspection
*/
public function getWpWpQueryObject()
{
return $this->wpQuery;
}
} webcachemgr/src/WPDashMsgs.php 0000664 00000011401 15055136441 0012276 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server WordPress Dash Notifier
*
* @author Michael Alegre
* @copyright 2019-2023 LiteSpeed Technologies, Inc.
* *******************************************
*/
namespace Lsc\Wp;
class WPDashMsgs
{
/**
* @var string
*/
const MSG_TYPE_RAP = 'rap';
/**
* @var string
*/
const MSG_TYPE_BAM = 'bam';
/**
* @var string
*/
const KEY_RAP_MSGS = 'rapMsgs';
/**
* @var string
*/
const KEY_BAM_MSGS = 'bamMsgs';
/**
* Do not change the following constant values, substr 'msg' is used in
* PanelController to determine action.
*/
/**
* @var string
*/
const ACTION_GET_MSG = 'msgGet';
/**
* @var string
*/
const ACTION_ADD_MSG = 'msgAdd';
/**
* @var string
*/
const ACTION_DELETE_MSG = 'msgDelete';
/**
* @var string
*/
protected $dataFile;
/**
* @var string[][]
*/
protected $msgData = array();
public function __construct( )
{
$this->dataFile =
realpath(__DIR__ . '/../../..') . '/admin/lscdata/wpDashMsgs.data';
$this->init();
}
protected function init()
{
if ( file_exists($this->dataFile) ) {
$data = json_decode(file_get_contents($this->dataFile), true);
if ( $data && is_array($data) ) {
$this->msgData = $data;
}
}
if ( !isset($this->msgData[self::KEY_RAP_MSGS]) ) {
$this->msgData[self::KEY_RAP_MSGS] = array();
}
if ( !isset($this->msgData[self::KEY_BAM_MSGS]) ) {
$this->msgData[self::KEY_BAM_MSGS] = array();
}
/**
* Set default rap message and plugin slug.
*/
$this->msgData[self::KEY_RAP_MSGS] = array_merge(
array(
'default' => array(
'msg' => 'Greetings! This is your hosting company '
. 'encouraging you to click the button to install the '
. 'LiteSpeed Cache plugin. This plugin will speed up '
. 'your WordPress site dramatically. Please contact us '
. 'with any questions.',
'slug' => 'litespeed-cache'
)
),
$this->msgData[self::KEY_RAP_MSGS]
);
}
/**
*
* @param string $type
*
* @return string[]|string[][]
*/
public function getMsgData( $type = '' )
{
switch ($type) {
case self::MSG_TYPE_RAP:
return $this->msgData[self::KEY_RAP_MSGS];
case self::MSG_TYPE_BAM:
return $this->msgData[self::KEY_BAM_MSGS];
default:
return $this->msgData;
}
}
/**
*
* @param string $type
* @param string $msgId
* @param string $msg
* @param string $slug
*
* @return bool
*/
public function addMsg( $type, $msgId, $msg, $slug = '' )
{
if ( $msgId === ''
|| $msgId === NULL
|| ($msgId == 'default' && $type == self::MSG_TYPE_RAP)
|| strlen($msgId) > 50
|| preg_match('/[^a-zA-Z0-9_-]/', $msgId) ) {
return false;
}
switch ($type) {
case self::MSG_TYPE_RAP:
$this->msgData[self::KEY_RAP_MSGS][$msgId] =
array( 'msg' => $msg, 'slug' => $slug );
break;
case self::MSG_TYPE_BAM:
$this->msgData[self::KEY_BAM_MSGS][$msgId] =
array( 'msg' => $msg );
break;
default:
return false;
}
$this->saveDataFile();
return true;
}
/**
*
* @param string $type
* @param string $msgId
*
* @return bool
*/
public function deleteMsg( $type, $msgId )
{
if ( $msgId === '' || $msgId === NULL ) {
return false;
}
switch ($type) {
case self::MSG_TYPE_RAP:
if ( $msgId == 'default' ) {
return false;
}
$key = self::KEY_RAP_MSGS;
break;
case self::MSG_TYPE_BAM:
$key = self::KEY_BAM_MSGS;
break;
default:
return false;
}
if ( isset($this->msgData[$key][$msgId]) ) {
unset($this->msgData[$key][$msgId]);
$this->saveDataFile();
return true;
}
return false;
}
protected function saveDataFile()
{
file_put_contents($this->dataFile, json_encode($this->msgData));
}
}
webcachemgr/src/LSCMException.php 0000664 00000001213 15055136441 0012733 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
* @author: LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright: (c) 2018
* ******************************************* */
namespace Lsc\Wp;
class LSCMException extends \Exception
{
const E_ERROR = 0;
/**
* show trace msg
*/
const E_PROGRAM = 100;
/**
* error shown to user
*/
const E_PERMISSION = 101;
const E_UNSUPPORTED = 102;
/**
* Exception is considered non-fatal. Used to determine
* UserCommand->runAsUser() return status.
*/
const E_NON_FATAL = 103;
}
webcachemgr/src/ThirdParty/Polyfill/LICENSE 0000664 00000002053 15055136441 0014501 0 ustar 00 Copyright (c) 2015-present Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. webcachemgr/src/ThirdParty/Polyfill/Utf8.php 0000664 00000003764 15055136441 0015045 0 ustar 00 <?php
/**
* This file contains paired-down/modified code originally found in Symfony
* package file Php72.php, used here as a PHP standard replacement for now
* deprecated PHP functions utf8_encode() and utf8_decode().
*
* Modified by: Michael Alegre (LiteSpeed Technologies, Inc.), 2023
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Lsc\Wp\ThirdParty\Polyfill;
/**
* @since 1.16.1
*/
class Utf8
{
/**
*
* @since 1.16.1
*
* @param $s
*
* @return false|string
*/
public static function encode($s)
{
$s .= $s;
$len = strlen($s);
for ($i = $len >> 1, $j = 0; $i < $len; ++$i, ++$j) {
if ( $s[$i] < "\x80" ) {
$s[$j] = $s[$i];
}
elseif ( $s[$i] < "\xC0" ) {
$s[$j] = "\xC2";
$s[++$j] = $s[$i];
}
else {
$s[$j] = "\xC3";
$s[++$j] = chr(ord($s[$i]) - 64);
}
}
return substr($s, 0, $j);
}
/**
*
* @since 1.16.1
*
* @param $s
*
* @return false|string
*/
public static function decode($s)
{
$s = (string) $s;
$len = strlen($s);
for ($i = 0, $j = 0; $i < $len; ++$i, ++$j) {
switch ($s[$i] & "\xF0") {
case "\xC0":
case "\xD0":
$c = (ord($s[$i] & "\x1F") << 6) | ord($s[++$i] & "\x3F");
$s[$j] = $c < 256 ? chr($c) : '?';
break;
case "\xF0":
++$i;
// fallthrough
case "\xE0":
$s[$j] = '?';
$i += 2;
break;
default:
$s[$j] = $s[$i];
}
}
return substr($s, 0, $j);
}
} webcachemgr/src/WPCaller.php 0000664 00000153356 15055136441 0012007 0 ustar 00 <?php
/** *********************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2018-2025 LiteSpeed Technologies, Inc.
* *******************************************
*/
namespace Lsc\Wp;
use Lsc\Wp\Context\Context;
use Lsc\Wp\WpWrapper\PluginUpgrader;
use Lsc\Wp\WpWrapper\WpConstants;
use Lsc\Wp\WpWrapper\WpFuncs;
use Lsc\Wp\WpWrapper\Wpdb;
use Lsc\Wp\WpWrapper\WpQuery;
use Lsc\Wp\WpWrapper\WpTextdomainRegistry;
/**
* Calls WP internal functions in SHORTINIT mode.
*/
class WPCaller
{
/**
* @var string
*/
const LSCWP_PLUGIN = 'litespeed-cache/litespeed-cache.php';
/**
* @var string
*/
const LSCWP_HTTP_HOST_TEST = 'litespeed_something_is_wrong';
/**
* @var null|WPCaller
*/
private static $instance = null;
/**
* @var WPInstall
*/
private $currInstall;
/**
* @since 1.13.4.4
* @var string
*/
private $advancedCacheFile;
/**
* @var bool
*/
private $loadLscwp;
/**
* @var string
*/
private $pluginEntry;
/**
* @since 1.13
* @var null|string
*/
private $installedLscwpVer = null;
/**
* @var string[]
*/
private $outputResult = array();
/**
* @var string
*/
private $massIncr = '';
/**
*
* @param WPInstall $curInstall
* @param bool $loadLscwp
*
* @throws LSCMException Thrown indirectly by $this->init() call.
*/
private function __construct( WPInstall $curInstall, $loadLscwp )
{
$this->currInstall = $curInstall;
$this->loadLscwp = $loadLscwp;
$this->init();
}
/**
*
* @since 1.13.4.4
*
* @throws LSCMException Thrown indirectly by $this->initWp() call.
*/
private function init()
{
$this->advancedCacheFile =
"{$this->currInstall->getPath()}/wp-content/advanced-cache.php";
$this->initWp();
}
/**
*
* @param WPInstall $currInstall
* @param bool $loadLscwp
*
* @return WPCaller
*
* @throws LSCMException Thrown indirectly by "new self()" call.
*/
public static function getInstance(
WPInstall $currInstall,
$loadLscwp = true )
{
if ( self::$instance == null
|| self::$instance->currInstall !== $currInstall ) {
self::$instance = new self($currInstall, $loadLscwp);
}
return self::$instance;
}
/**
*
* @param int $errno Not used at this time.
* @param string $errstr
*
* @return bool
*
* @noinspection PhpUnusedParameterInspection
*/
public static function warning_handler( $errno, $errstr )
{
$strs = array(
'ini_set() has been disabled for security reasons',
'Constant FS_METHOD already defined'
);
if ( in_array($errstr, $strs) ) {
/**
* Throw this warning out.
*/
return true;
}
return false;
}
/**
* Deprecated 03/12/19 as this function is no longer used.
*
* Prevents database table options not in the $allowedOptions list
* from having their value updated by others during execution.
*
* Run when WP function apply_filters('pre_update_option', ...) is called
* in WP function update_option().
*
* @deprecated
*
* @param mixed $value New option value.
* @param string $option Option name in db.
* @param mixed $old_value Old option value.
*
* @return mixed
*/
public static function lock_database( $value, $option, $old_value )
{
$allowedOptions = array(
'litespeed-cache-conf',
'_transient_lscwp_whm_install',
'active_plugins',
'_transient_doing_cron',
'_site_transient_update_plugins',
'uninstall_plugins'
);
if ( in_array($option, $allowedOptions) ) {
return $value;
}
else {
return $old_value;
}
}
/**
* Redefine disabled PHP global/core functions that no longer exist
* (PHP 8+).
*
* @since 1.13.10
*/
private static function redefineDisabledFunctions()
{
if ( Util::betterVersionCompare(phpversion(), '8.0', '>=') ) {
include_once(__DIR__ . '/RedefineGlobalFuncs.php');
}
}
/**
*
* @return string[]
*/
public function getOutputResult()
{
return $this->outputResult;
}
/**
* Adds key value pair to $this->outputResult to be grabbed later in
* the $output variable of the UserCommand::issue() exec call.
*
* @param string $key
* @param mixed $value
*/
private function outputResult( $key, $value )
{
$this->outputResult[$key] = $value;
}
/**
*
* @deprecated 1.9 Use Logger::getLogMsgQueue() to get these messages as
* LogEntry objects.
*
* @return string[]
*
* @throws LSCMException Thrown indirectly by Logger::getLogMsgQueue()
* call.
*/
public function getDebugMsgs()
{
$debugMsgs = array();
$msgQueue = Logger::getLogMsgQueue();
foreach ( $msgQueue as $logEntry ) {
$label = Logger::getLvlDescr($logEntry->getLvl());
$debugMsgs[] = "[$label] {$logEntry->getMsg()}";
}
return $debugMsgs;
}
/**
* @deprecated 1.9 Deprecated 07/30/19. Use
* Logger::getUiMsgs(Logger::UI_ERR) to get these messages.
*
* @return string[]
*
* @throws LSCMException Thrown indirectly by Logger::getUiMsgs() call.
*/
public function getErrMsgs()
{
return Logger::getUiMsgs(Logger::UI_ERR);
}
/**
*
* @deprecated 1.9 Deprecated 07/30/19. Use
* Logger::getUiMsgs(Logger::UI_SUCC) to get these messages.
*
* @return string[]
*
* @throws LSCMException Thrown indirectly by Logger::getUiMsgs() call.
*/
public function getSuccMsgs()
{
return Logger::getUiMsgs(Logger::UI_SUCC);
}
/**
*
* WP Variables $table_prefix
*
* @global string $table_prefix
*
* @return string
*/
private function getSiteURL()
{
global $table_prefix;
$siteURL = WpFuncs::getOption('siteurl');
if ( !$siteURL ) {
return '';
}
if ( strpos($siteURL, self::LSCWP_HTTP_HOST_TEST) !== false ) {
/**
* User is setting WP_SITEURL using fake $_SERVER['HTTP_HOST'].
* Get siteurl value from DB directly.
*/
return WpFuncs::getVar(
"SELECT option_value FROM {$table_prefix}options "
. "WHERE option_name = 'siteurl'"
);
}
return $siteURL;
}
/**
*
* @since 1.17.0.3
*
* @param string $advCacheFileContents
*
* @return bool
*/
private static function advancedCacheFileBelongsToLscwp(
$advCacheFileContents
)
{
if ( self::advancedCacheFileHasLscacheDefine($advCacheFileContents) ) {
return true;
}
if ( self::advancedCacheFileHasPlaceholderMsg($advCacheFileContents) ) {
return true;
}
return false;
}
/**
*
* @since 1.13.4.3
*
* @return bool
*/
private function generic3rdPartyAdvCachePluginExists()
{
if ( Util::betterVersionCompare($this->installedLscwpVer, '3.0.4', '>=') ) {
if ( file_exists($this->advancedCacheFile) ) {
$advCacheFileContents =
file_get_contents($this->advancedCacheFile);
if ( $advCacheFileContents !== '' ) {
/**
* Old LSCWP advanced-cache.php file is no longer used in
* these versions but is also never cleaned up. As a result,
* any existing advanced-cache.php files need to have their
* contents checked to avoid detecting an old LSCWP
* advanced-cache.php file as a generic 3rd-party
* advanced-cache plugin.
*/
return !self::advancedCacheFileBelongsToLscwp(
$advCacheFileContents
);
}
}
}
elseif ( !defined('LSCACHE_ADV_CACHE')
|| WpConstants::getWpConstant('LSCACHE_ADV_CACHE') !== true ) {
return true;
}
return false;
}
/**
*
* @since 1.13.8 Added optional parameter $output.
*
* @param WPInstall $install
* @param bool $output
*
* @return int
*
* @throws LSCMException Thrown indirectly by Logger::uiError() call.
* @throws LSCMException Thrown indirectly by $install->addUserFlagFile()
* call.
* @throws LSCMException Thrown indirectly by $install->addUserFlagFile()
* call.
* @throws LSCMException Thrown indirectly by Logger::notice() call.
* @throws LSCMException Thrown indirectly by Logger::notice() call.
*/
private function checkStatus( WPInstall $install, $output = false )
{
if ( $output ) {
if ( ($siteUrl = $this->getSiteURL()) === '' ) {
Logger::uiError(
'Could not retrieve siteURL to match against known '
. 'docroots.'
);
$install->addUserFlagFile();
return (WPInstall::ST_ERR_SITEURL | WPInstall::ST_FLAGGED);
}
$this->outputResult('SITEURL', $siteUrl);
}
$status = 0;
/**
* Check if plugin files exist first, as status in db could be stale if
* LSCWP was removed manually.
*/
if ( file_exists($this->pluginEntry)
&& WpFuncs::isPluginActive(self::LSCWP_PLUGIN) ) {
$status |= WPInstall::ST_PLUGIN_ACTIVE;
//TODO: Get rid of ST_LSC_ADVCACHE_DEFINED status or replace with
// new "is caching enabled" define check.
if ( $this->generic3rdPartyAdvCachePluginExists() ) {
$status |= WPInstall::ST_FLAGGED;
}
else {
$status |= WPInstall::ST_LSC_ADVCACHE_DEFINED;
}
}
else {
$status |= WPInstall::ST_PLUGIN_INACTIVE;
}
if ( $install->hasFlagFile() ) {
$status |= WPInstall::ST_FLAGGED;
}
if ( $status & WPInstall::ST_FLAGGED ) {
if ( $install->addUserFlagFile() ) {
Logger::notice('Install is flagged');
}
else {
Logger::notice('Install is not flagged');
}
}
return $status;
}
/**
*
* @param bool $output
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->checkStatus() call.
*/
public function updateStatus( $output = false )
{
$status = $this->checkStatus($this->currInstall, $output);
$this->currInstall->setStatus($status);
if ( $output ) {
$this->outputResult('STATUS', $status);
}
if ( $status & WPInstall::ST_ERR_SITEURL ) {
return UserCommand::EXIT_FAIL;
}
return UserCommand::EXIT_SUCC;
}
/**
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->updateStatus() call.
*/
private function getCurrStatus()
{
$this->updateStatus();
return $this->currInstall->getStatus();
}
/**
* Check if any known cache plugins that do not use an advanced-cache.php
* file are active for this WordPress installation. If any of these plugins
* are found, that plugin's slug is returned.
*
* @since 1.9.1
*
* @return string Empty string or detected active cache plugin slug.
*/
private function checkForKnownNonAdvCachePlugins()
{
$knownPlugins = array(
'wp-fastest-cache' => 'wp-fastest-cache/wpFastestCache.php'
);
foreach ( $knownPlugins as $slug => $plugin ) {
/**
* Check if plugin files exist first, as status in db could be
* stale if plugin files were removed manually.
*/
$pluginExistsAndIsActive = (
file_exists(
WpConstants::getWpConstant('WP_PLUGIN_DIR') . "/$plugin"
)
&&
WpFuncs::isPluginActive($plugin)
);
if ( $pluginExistsAndIsActive) {
return $slug;
}
}
return '';
}
/**
*
* @param bool $isMassAction
* @param bool $isNewInstall
*
* @return bool
*
* @throws LSCMException Thrown indirectly by $this->getCurrStatus() call.
* @throws LSCMException Thrown indirectly by
* $this->currInstall->addUserFlagFile() call.
* @throws LSCMException Thrown indirectly by Logger::uiSuccess() call.
* @throws LSCMException Thrown indirectly by Logger::notice() call.
* @throws LSCMException Thrown indirectly by
* $this->currInstall->addUserFlagFile() call.
* @throws LSCMException Thrown indirectly by Logger::uiError() call.
* @throws LSCMException Thrown indirectly by Logger::notice() call.
* @throws LSCMException Thrown indirectly by Logger::uiSuccess() call.
* @throws LSCMException Thrown indirectly by Logger::notice() call.
* @throws LSCMException Thrown indirectly by
* $this->currInstall->addUserFlagFile() call.
* @throws LSCMException Thrown indirectly by Logger::uiError() call.
* @throws LSCMException Thrown indirectly by Logger::notice() call.
*/
private function canEnable( $isMassAction, $isNewInstall )
{
$status = $this->getCurrStatus();
if ( $status & WPInstall::ST_PLUGIN_INACTIVE ) {
if ( !$isNewInstall && $isMassAction ) {
$this->currInstall->addUserFlagFile();
Logger::uiSuccess(
'LSCWP Detected As Manually Disabled - Flag Set'
);
Logger::notice(
'Ignore - Previously disabled, flag it from mass operation'
);
return false;
}
$thirdPartyCachePluginSlug =
$this->checkForKnownNonAdvCachePlugins();
if ( $thirdPartyCachePluginSlug != '' ) {
$this->currInstall->addUserFlagFile();
Logger::uiError(
'Cannot Enable LSCWP - Detected another active cache '
. "plugin \"$thirdPartyCachePluginSlug\". Flag set."
);
Logger::notice(
'Ignore - Detected another active cache plugin '
. "\"$thirdPartyCachePluginSlug\". Flagged."
);
return false;
}
}
elseif ( !$isNewInstall ) {
/**
* already active
*/
if ( $status & WPInstall::ST_LSC_ADVCACHE_DEFINED ) {
Logger::uiSuccess('LSCWP Already Enabled - No Action Taken');
Logger::notice('Ignore - Already enabled');
}
else {
$this->currInstall->addUserFlagFile();
Logger::uiError(
'LSCWP Already Enabled But Not Caching - Detected another '
. 'active cache plugin. Please visit the WordPress '
. 'Dashboard for further instructions.'
);
Logger::notice(
'Ignore - Existing install but advanced cache not set'
);
}
return false;
}
return true;
}
/**
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->canEnable() call.
* @throws LSCMException Thrown indirectly by $this->enable_lscwp() call.
* @throws LSCMException Thrown indirectly by
* $this->directEnableNewInstall() call.
*/
public function directEnable()
{
$isNewInstall = !file_exists($this->pluginEntry);
if ( !$this->canEnable(false, $isNewInstall) ) {
$this->outputResult('STATUS', $this->currInstall->getStatus());
return UserCommand::EXIT_FAIL;
}
if ( !$isNewInstall ) {
$status = $this->enable_lscwp();
}
else {
$status = $this->directEnableNewInstall();
}
$this->outputResult('STATUS', $status);
return UserCommand::EXIT_SUCC;
}
/**
*
* @return int
*
* @throws LSCMException Thrown when unable to extract downloaded LSCWP
* files.
* @throws LSCMException Thrown indirectly by $this->downloadLSCWPZip()
* call.
* @throws LSCMException Thrown indirectly by $this->enable_lscwp() call.
* @throws LSCMException Thrown indirectly by
* $this->removeLscwpPluginFiles() call.
*/
private function directEnableNewInstall()
{
$pluginDir = WpConstants::getWpConstant('WP_PLUGIN_DIR');
$lscwpZip = "$pluginDir/litespeed-cache.latest-stable.zip";
$this->downloadLSCWPZip($lscwpZip);
WpFuncs::WpFilesystem();
$unzipRet = WpFuncs::unzipFile($lscwpZip, $pluginDir);
unlink($lscwpZip);
if ( $unzipRet !== true ) {
throw new LSCMException(
"Unable to extract downloaded LSCWP files.",
LSCMException::E_NON_FATAL
);
}
$this->currInstall->addNewLscwpFlagFile();
$customIni = Context::LOCAL_PLUGIN_DIR . '/'
. PluginVersion::LSCWP_DEFAULTS_INI_FILE_NAME;
if ( file_exists($customIni) ) {
copy(
$customIni,
"$pluginDir/litespeed-cache/data/"
. PluginVersion::LSCWP_DEFAULTS_INI_FILE_NAME
);
}
$this->installedLscwpVer = $this->getPluginVersionFromFile();
$status = $this->enable_lscwp();
if ( $status & WPInstall::ST_PLUGIN_INACTIVE) {
$this->removeLscwpPluginFiles();
}
else {
$this->updateTranslationFiles();
}
return $status;
}
/**
*
* @param string $lscwpZip
*
* @return null
*
* @throws LSCMException Thrown when LSCWP download operation fails.
*/
private function downloadLscwpZip( $lscwpZip )
{
$pluginDir = WpConstants::getWpConstant('WP_PLUGIN_DIR');
$url = 'https://downloads.wordpress.org/plugin/'
. 'litespeed-cache.latest-stable.zip';
exec(
"wget -q --tries=1 --no-check-certificate $url -P $pluginDir",
$output1,
$return_var1
);
if ( $return_var1 === 0 && file_exists($lscwpZip) ) {
return;
}
/**
* Fall back to curl in case wget is disabled for user.
*/
exec(
"cd $pluginDir && curl -O -s --retry 1 --insecure $url",
$output2,
$return_var2
);
if ( $return_var2 === 0 && file_exists($lscwpZip) ) {
return;
}
throw new LSCMException(
"Failed to download LSCWP with wget exit status $return_var1 and "
. "curl exit status $return_var2.",
LSCMException::E_NON_FATAL
);
}
/**
*
* @param array $extraArgs Not used at this time.
* @param bool $massOp True when called from massEnable().
*
* @return int
*
* @throws LSCMException Thrown indirectly by PluginVersion::getInstance()
* call.
* @throws LSCMException Thrown indirectly by
* PluginVersion::getInstance()->prepareUserInstall() call.
* @throws LSCMException Thrown indirectly by $this->canEnable() call.
* @throws LSCMException Thrown indirectly by $this->enable_lscwp() call.
* @throws LSCMException Thrown indirectly by
* $this->removeLscwpPluginFiles() call.
*
* @noinspection PhpUnusedParameterInspection
*/
public function enable( array $extraArgs, $massOp = false )
{
$isNewInstall = PluginVersion::getInstance()->prepareUserInstall(
WpConstants::getWpConstant('WP_PLUGIN_DIR')
);
if ( $isNewInstall ) {
$this->installedLscwpVer = $this->getPluginVersionFromFile();
$this->currInstall->addNewLscwpFlagFile();
}
if ( !$this->canEnable($massOp, $isNewInstall) ) {
$status = $this->currInstall->getStatus();
$ret = UserCommand::EXIT_FAIL;
}
else {
$status = $this->enable_lscwp();
$ret = UserCommand::EXIT_SUCC;
}
if ( $isNewInstall ) {
if ( $status & WPInstall::ST_PLUGIN_INACTIVE ) {
$this->removeLscwpPluginFiles();
}
else {
$this->updateTranslationFiles();
}
}
$this->outputResult('STATUS', $this->currInstall->getStatus());
return $ret;
}
/**
*
* @param string[] $extraArgs
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->enable() call.
*/
public function massEnable( array $extraArgs )
{
$ret = $this->enable($extraArgs, true);
if ( $this->massIncr != '' ) {
$this->outputResult('MASS_INCR', $this->massIncr);
}
return $ret;
}
/**
*
* @param bool $isMassAction
*
* @return bool
*
* @throws LSCMException Thrown indirectly by $this->getCurrStatus() call.
* @throws LSCMException Thrown indirectly by Logger::notice() call.
* @throws LSCMException Thrown indirectly by Logger::uiSuccess() call.
* @throws LSCMException Thrown indirectly by
* $this->currInstall->addUserFlagFile() call.
* @throws LSCMException Thrown indirectly by Logger::uiSuccess() call.
* @throws LSCMException Thrown indirectly by Logger::notice() call.
* @throws LSCMException Thrown indirectly by
* $this->currInstall->addUserFlagFile() call.
* @throws LSCMException Thrown indirectly by Logger::uiSuccess() call.
*/
private function canDisable( $isMassAction )
{
$status = $this->getCurrStatus();
if ( $status & WPInstall::ST_PLUGIN_INACTIVE ) {
Logger::notice('Ignore - Already disabled');
Logger::uiSuccess(
'LiteSpeed Cache Already Disabled - No Action Taken'
);
return false;
}
if ( $isMassAction ) {
if ( !($status & WPInstall::ST_LSC_ADVCACHE_DEFINED) ) {
$this->currInstall->addUserFlagFile();
Logger::uiSuccess(
'LSCWP Detected As Manually Enabled But Not Caching - Flag '
. 'Set. If desired, this installation can be disabled '
. 'from the Manage Cache Installations screen.'
);
Logger::notice(
'Ignore for mass disable - Installed manually as advanced '
. 'cache not set.'
);
return false;
}
if ( WpFuncs::isPluginActiveForNetwork(self::LSCWP_PLUGIN) ) {
$this->currInstall->addUserFlagFile();
Logger::uiSuccess(
'LiteSpeed Cache Detected As Network Activated - Flag Set '
. '& No Action Taken'
);
return false;
}
}
return true;
}
/**
*
* @param string[] $extraArgs Not used at this time.
* @param bool $massOp True when called from MassDisable().
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->canDisable() call.
* @throws LSCMException Thrown indirectly by $this->performDisable() call.
* @throws LSCMException Thrown indirectly by Logger::uiSuccess() call.
*
* @noinspection PhpUnusedParameterInspection
*/
public function disable( array $extraArgs, $massOp = false )
{
if ( !$this->canDisable($massOp) ) {
$ret = UserCommand::EXIT_FAIL;
}
else {
if ( $this->performDisable(true) & WPInstall::ST_PLUGIN_ACTIVE ) {
$ret = UserCommand::EXIT_FAIL;
}
else {
Logger::uiSuccess('LiteSpeed Cache Disabled');
$this->massIncr = 'SUCC';
$ret = UserCommand::EXIT_SUCC;
}
}
$this->outputResult('STATUS', $this->currInstall->getStatus());
return $ret;
}
/**
*
* @param string[] $extraArgs
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->disable() call.
*/
public function massDisable( array $extraArgs )
{
$ret = $this->disable($extraArgs, true);
if ( $this->massIncr != '' ) {
$this->outputResult('MASS_INCR', $this->massIncr);
}
return $ret;
}
/**
* Includes LSCWP files needed to properly disable the LSCWP plugin.
*
* @since 1.13 Removed param $lscwpVer.
*/
private function includeDisableRequiredFiles()
{
$dir = WpConstants::getWpConstant('WP_PLUGIN_DIR') . '/litespeed-cache';
if ( Util::betterVersionCompare($this->installedLscwpVer, '3.0', '>=') ) {
require_once "$dir/src/admin.cls.php";
}
elseif ( Util::betterVersionCompare($this->installedLscwpVer, '1.1.2.2', '>') ) {
require_once "$dir/admin/litespeed-cache-admin.class.php";
}
else {
require_once "$dir/admin/class-litespeed-cache-admin.php";
}
if ( Util::betterVersionCompare($this->installedLscwpVer, '1.1.0', '<')
&& Util::betterVersionCompare($this->installedLscwpVer, '1.0.6', '>') ) {
require_once "$dir/admin/class-litespeed-cache-admin-rules.php";
}
}
/**
*
* @param bool $uninstall
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->disable_lscwp() call.
*/
private function performDisable( $uninstall )
{
$this->includeDisableRequiredFiles();
return $this->disable_lscwp($uninstall);
}
/**
*
* @param string[] $fromVersions
* @param string $toVersion
* @param bool $massOp Not used at this time.
*
* @return bool
*
* @noinspection PhpUnusedParameterInspection
*/
private function canUpgrade( array $fromVersions, $toVersion, $massOp )
{
if ( !file_exists($this->pluginEntry) ) {
return false;
}
if ( $toVersion == $this->installedLscwpVer ) {
return false;
}
foreach ( $fromVersions as $fromVer ) {
$fromVerParts = explode('.', $fromVer);
$installedVerParts = explode('.', $this->installedLscwpVer);
$i = 0;
while ( isset($fromVerParts[$i]) ) {
$fromVerPart = $fromVerParts[$i];
if ( $fromVerPart == 'x' ) {
return true;
}
if ( !isset($installedVerParts[$i])
|| $installedVerParts[$i] != $fromVerPart ) {
continue 2;
}
$i++;
}
if ( !isset($installedVerParts[$i]) ) {
return true;
}
}
return false;
}
/**
*
* @param string[] $extraArgs
* @param bool $massOp
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->updateStatus() call.
* @throws LSCMException Thrown indirectly by $this->upgrade_lscwp() call.
*/
public function upgrade( array $extraArgs, $massOp = false )
{
$toVersion = $extraArgs[1];
$canUpgrade = $this->canUpgrade(
explode(',', $extraArgs[0]),
$toVersion,
$massOp
);
if ( !$canUpgrade ) {
$this->updateStatus(true);
return UserCommand::EXIT_FAIL;
}
else {
$this->upgrade_lscwp($toVersion);
return UserCommand::EXIT_SUCC;
}
}
/**
*
* @param string[] $extraArgs
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->upgrade() call.
*/
public function massUpgrade( array $extraArgs )
{
$ret = $this->upgrade($extraArgs, true);
if ( $this->massIncr != '' ) {
$this->outputResult('MASS_INCR', $this->massIncr);
}
return $ret;
}
/**
*
* @param bool $uninstall
*/
private function deactivate_lscwp( $uninstall )
{
WpFuncs::deactivatePlugins(self::LSCWP_PLUGIN);
if ( $uninstall ) {
//Todo: add some msg about having removed plugin files?
WpFuncs::deletePlugins(array( self::LSCWP_PLUGIN ));
}
}
/**
*
* @param bool $uninstall
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->getCurrStatus() call.
*/
private function disable_lscwp( $uninstall )
{
if ( WpConstants::getWpConstant('MULTISITE') ) {
$blogs =
Wpdb::getCol("SELECT blog_id FROM " . Wpdb::getBlogs() . ';');
foreach ( $blogs as $id ) {
WpFuncs::switchToBlog($id);
$this->deactivate_lscwp($uninstall);
WpFuncs::restoreCurrentBlog();
}
}
else {
$this->deactivate_lscwp($uninstall);
}
return $this->getCurrStatus();
}
/**
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->getCurrStatus() call.
* @throws LSCMException Thrown indirectly by $this->performDisable() call.
* @throws LSCMException Thrown indirectly by Logger::uiError() call.
* @throws LSCMException Thrown indirectly by
* $this->currInstall->addUserFlagFile() call.
* @throws LSCMException Thrown indirectly by Logger::uiError() call.
* @throws LSCMException Thrown indirectly by Logger::uiSuccess() call.
*/
private function enable_lscwp()
{
/**
* Should not check directly, can error on success due to object cache.
*/
WpFuncs::activatePlugin(self::LSCWP_PLUGIN);
$status = $this->getCurrStatus();
if ( !($status & WPInstall::ST_LSC_ADVCACHE_DEFINED) ) {
$status = $this->performDisable(true);
Logger::uiError(
'Detected '
. "{$this->currInstall->getPath()}/wp-content/advanced-cache.php "
. 'as belonging to another cache plugin. Please deactivate '
. 'the related cache plugin and try again. You may also '
. 'try manually installing through the WordPress Dashboard '
. 'and following the instructions given.'
);
$this->massIncr = 'FAIL';
}
elseif ( $status & WPInstall::ST_PLUGIN_ACTIVE ) {
if (
!is_writable($this->currInstall->getWpConfigFile())
&&
(
!defined('WP_CACHE')
||
WpConstants::getWpConstant('WP_CACHE') !== true
)
) {
/**
* LSCACHE_ADV_CACHE is incorrectly defined true at this point.
* Detected status must be manually corrected.
*/
$status &= ~WPInstall::ST_LSC_ADVCACHE_DEFINED;
$this->currInstall->setStatus($status);
$this->currInstall->addUserFlagFile();
$status = $this->currInstall->getStatus();
Logger::uiError(
'LSCWP Enabled But Not Caching - Please visit the '
. 'WordPress Dashboard for further instructions.'
);
}
else {
Logger::uiSuccess('LSCWP Enabled');
}
$this->massIncr = 'SUCC';
}
return $status;
}
/**
*
* @param string $ver
* @param bool $runHooks
*
* @throws LSCMException Thrown when LSCWP plugin version upgrade fails.
*/
private function upgrade_lscwp( $ver, $runHooks = true )
{
/**
* Label the following $upgraderWrapper output (Cannot be buffered).
*/
echo "[UPGRADE]\n";
$upgraderWrapper = new PluginUpgrader;
$upgraderWrapper->init();
$upgraderWrapper->upgradeStrings();
$lscwpPackageURL =
"https://downloads.wordpress.org/plugin/litespeed-cache.$ver.zip";
if ( $runHooks ) {
WpFuncs::addFilter(
'upgrader_pre_install',
array(
$upgraderWrapper->getWpPluginUpgraderObject(),
'deactivate_plugin_before_upgrade'
),
10,
2
);
WpFuncs::addFilter(
'upgrader_clear_destination',
array(
$upgraderWrapper->getWpPluginUpgraderObject(),
'delete_old_plugin'
),
10,
4
);
}
$upgraderWrapper->run(
array(
'package' => $lscwpPackageURL,
'destination' =>
WpConstants::getWpConstant('WP_PLUGIN_DIR'),
'clear_destination' => true,
'clear_working' => true,
'hook_extra' => array(
'plugin' => $this->pluginEntry,
'type' => 'plugin',
'action' => 'update',
)
)
);
/**
* Start new messages on a new line
*/
echo "\n";
if ( $runHooks ) {
/**
* Cleanup our hooks, in case something else does an upgrade on
* this connection.
*/
WpFuncs::removeFilter(
'upgrader_pre_install',
array(
$upgraderWrapper->getWpPluginUpgraderObject(),
'deactivate_plugin_before_upgrade'
)
);
WpFuncs::removeFilter(
'upgrader_clear_destination',
array(
$upgraderWrapper->getWpPluginUpgraderObject(),
'delete_old_plugin'
)
);
}
if ( !$upgraderWrapper->getResult()
|| WpFuncs::isWpError($upgraderWrapper->getResult()) ) {
throw new LSCMException(
"Failed to upgrade to v$ver.",
LSCMException::E_NON_FATAL
);
}
$this->updateTranslationFiles();
/**
* Force refresh of plugin update information
*/
WpFuncs::wpCleanPluginsCache();
}
/**
* Gets LSCWP version from the litespeed-cache.php file.
*
* @return string
*/
private function getPluginVersionFromFile()
{
$lscwp_data = WpFuncs::getPluginData($this->pluginEntry, false, false);
return $lscwp_data['Version'];
}
/**
* Checks for local plugin translation files and copies them to the plugin
* languages directory if able. This function will also attempt to inform
* the root user when a locale's translation should be retrieved or removed.
*/
public function updateTranslationFiles()
{
$locale = WpFuncs::getLocale();
if ( $locale == 'en_US' ) {
return;
}
$localTranslationDir = Context::LOCAL_PLUGIN_DIR
. "/$this->installedLscwpVer/translations";
$moFileName = "litespeed-cache-$locale.mo";
$poFileName = "litespeed-cache-$locale.po";
$localMoFile = "$localTranslationDir/$moFileName";
$localPoFile = "$localTranslationDir/$poFileName";
$zipFile = "$localTranslationDir/$locale.zip";
$translationFlag = "$localTranslationDir/"
. PluginVersion::TRANSLATION_CHECK_FLAG_BASE . "_$locale";
$langDir =
$this->currInstall->getPath() . '/wp-content/languages/plugins';
if ( !file_exists($langDir) ) {
mkdir($langDir, 0755);
}
if ( file_exists($localMoFile) && file_exists($localPoFile) ) {
copy($localMoFile, "$langDir/$moFileName");
copy($localPoFile, "$langDir/$poFileName");
}
elseif ( file_exists($zipFile) ) {
WpFuncs::WpFilesystem();
if ( WpFuncs::unzipFile($zipFile, $langDir) !== true ) {
$this->outputResult(
'BAD_TRANSLATION',
"$locale $this->installedLscwpVer"
);
}
}
elseif ( !file_exists($translationFlag)
|| (time() - filemtime($translationFlag)) > 86400 ) {
$this->outputResult(
'GET_TRANSLATION',
"$locale $this->installedLscwpVer"
);
}
}
/**
*
* @since 1.13.4.4
* @since 1.17.0.3 Added required parameter $advCacheFileContents.
*
* @param string $advCacheFileContents
*
* @return bool
*/
private static function advancedCacheFileHasLscacheDefine(
$advCacheFileContents
)
{
$definePosition = strpos($advCacheFileContents, 'LSCACHE_ADV_CACHE');
return ($definePosition !== false);
}
/**
* Check if advanced-cache.php file contains LSCWP placeholder text. This
* file with generic placeholder text was re-added by LSCWP for improved
* compatibility with WordPress versions lower than v5.3.
*
* @since 1.17.0.3
*
* @param string $advCacheFileContent
*
* @return bool
*/
private static function advancedCacheFileHasPlaceholderMsg(
$advCacheFileContent
)
{
$definePosition = strpos(
$advCacheFileContent,
'A compatibility placeholder for WordPress < v5.3'
);
return ($definePosition !== false);
}
private function includeLSCWPAdvancedCacheFile()
{
if ( file_exists($this->advancedCacheFile) ) {
$advCacheFileContents =
file_get_contents($this->advancedCacheFile);
if (
$advCacheFileContents !== ''
&&
$this->advancedCacheFileHasLscacheDefine(
$advCacheFileContents
)
) {
include_once $this->advancedCacheFile;
}
}
}
/**
*
* @throws LSCMException Thrown indirectly by
* $this->currInstall->removePluginFiles() call.
*/
public function removeLscwpPluginFiles()
{
$this->currInstall->removePluginFiles(dirname($this->pluginEntry));
}
/**
*
* @param string[] $extraArgs
* @param bool $massOp Not used at this time.
*
* @return int
*
* @throws LSCMException Thrown indirectly by
* DashNotifier::prepareUserInstall() call.
* @throws LSCMException Thrown indirectly by DashNotifier::doNotify()
* call.
* @throws LSCMException Thrown indirectly by Logger::uiSuccess() call.
* @throws LSCMException Thrown indirectly by Logger::uiError() call.
*
* @noinspection PhpUnusedParameterInspection
*/
public function dashNotify( array $extraArgs, $massOp = false )
{
if ( DashNotifier::canNotify($this->currInstall->getPath()) ) {
DashNotifier::prepareUserInstall();
if ( DashNotifier::doNotify(base64_decode($extraArgs[0])) ) {
Logger::uiSuccess('Notified Successfully');
$this->massIncr = 'SUCC';
return UserCommand::EXIT_SUCC;
}
Logger::uiError('Failed to Notify');
$this->massIncr = 'FAIL';
}
else {
$this->massIncr = 'BYPASS';
}
return UserCommand::EXIT_FAIL;
}
/**
*
* @param string[] $extraArgs
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->dashNotify() call.
*/
public function massDashNotify( array $extraArgs )
{
$ret = $this->dashNotify($extraArgs, true);
if ( $this->massIncr != '' ) {
$this->outputResult('MASS_INCR', $this->massIncr);
}
return $ret;
}
/**
*
* @param string[] $extraArgs Unused for now.
* @param bool $massOp Unused for now.
*
* @return int
*
* @throws LSCMException Thrown indirectly by Logger::uiSuccess() call.
*
* @noinspection PhpUnusedParameterInspection
*/
public function dashDisable( array $extraArgs, $massOp = false )
{
if ( WpConstants::getWpConstant('MULTISITE') ) {
$blogs =
Wpdb::getCol('SELECT blog_id FROM ' . Wpdb::getBlogs() . ';');
foreach ( $blogs as $id ) {
WpFuncs::switchToBlog($id);
DashNotifier::deactivate(true);
WpFuncs::restoreCurrentBlog();
}
}
else {
DashNotifier::deactivate(true);
}
if ( WpFuncs::isPluginActive(DashNotifier::DASH_PLUGIN) ) {
$this->massIncr = 'FAIL';
return UserCommand::EXIT_FAIL;
}
Logger::uiSuccess('Dash Notifier Disabled');
$this->massIncr = 'SUCC';
return UserCommand::EXIT_SUCC;
}
/**
*
* @param string[] $extraArgs
*
* @return int
*
* @throws LSCMException Thrown indirectly by $this->dashDisable() call.
*/
public function massDashDisable( array $extraArgs )
{
$ret = $this->dashDisable($extraArgs, true);
if ( $this->massIncr != '' ) {
$this->outputResult('MASS_INCR', $this->massIncr);
}
return $ret;
}
/**
*
* @since 1.12
*
* @param bool $setOutputResult
*
* @return string
*/
public function getQuicCloudAPIKey( $setOutputResult = false )
{
$key = WpFuncs::applyFilters('litespeed_conf', 'api_key', null);
if ( $key == 'api_key' || $key == null ) {
$key = '';
}
if ( $setOutputResult ) {
$this->outputResult('API_KEY', $key);
}
return $key;
}
/**
* Set global server and environment variables.
*
* @since 1.9.8
*
* @param string $key
* @param mixed $val
*/
private function setEnvVar( $key, $val )
{
$_SERVER[$key] = $val;
putenv("$key=$val");
}
/**
* Checks if the current WordPress installation is a multisite install and
* does some preload setup if so.
*
* Patterns and multisite check logic based on WordPress function
* is_multisite().
*
* @since 1.9.8
*
* @return bool
*
* @throws LSCMException Thrown when DOMAIN_CURRENT_SITE is not found with
* MULTISITE defined.
* @throws LSCMException Thrown when PATH_CURRENT_SITE is not found with
* MULTISITE defined.
*/
private function isMultisite()
{
$config_content =
file_get_contents($this->currInstall->getWpConfigFile());
$isMultiSite = (
preg_match(
'/define\(\s*[\'"]MULTISITE[\'"]\s*,[^;]*;/',
$config_content,
$m1
)
&&
preg_match(
'/define\(\s*[\'"]MULTISITE[\'"]\s*,\s*true\s*\)\s*;/',
$m1[0]
)
)
||
(
preg_match(
'/define\(\s*[\'"]SUBDOMAIN_INSTALL[\'"]\s*,[^;]*;/',
$config_content
)
||
preg_match(
'/define\(\s*[\'"]VHOST[\'"]\s*,[^;]*;/',
$config_content
)
||
preg_match(
'/define\(\s*[\'"]SUNRISE[\'"]\s*,[^;]*;/',
$config_content
)
);
if ( !$isMultiSite ) {
return false;
}
$domainCurrentSiteFound = preg_match(
'/define\(\s*[\'"]DOMAIN_CURRENT_SITE[\'"]\s*,'
. '\s*[\'"](.+)[\'"]\s*\)\s*;/',
$config_content,
$m2
);
if ( !$domainCurrentSiteFound ) {
throw new LSCMException(
'Cannot find DOMAIN_CURRENT_SITE with MULTISITE defined.'
);
}
$this->currInstall->setServerName($m2[1]);
$pathCurrentSiteFound = preg_match(
'/define\(\s*[\'"]PATH_CURRENT_SITE[\'"]\s*,'
. '\s*[\'"](.+)[\'"]\s*\)\s*;/',
$config_content,
$m3
);
if ( !$pathCurrentSiteFound ) {
throw new LSCMException(
'Cannot find PATH_CURRENT_SITE with MULTISITE defined.'
);
}
$this->setEnvVar('REQUEST_URI', $m3[1]);
Util::define_wrapper('WP_NETWORK_ADMIN', true);
return true;
}
/**
*
* WP Variables: $wpdb, $shortcode_tags
*
* @global \wpdb $wpdb
* @global array $shortcode_tags
*
* @throws LSCMException Thrown when detected WordPress version is lower
* then 4.0.
* @throws LSCMException Thrown when unable to find a required WordPress
* include file.
* @throws LSCMException Thrown indirectly by $this->isMultisite() call.
*
* @noinspection PhpUndefinedClassInspection
*/
private function initWp()
{
/**
* Declared global variables for use in included files.
*
* @noinspection PhpUnusedLocalVariableInspection
*/
global $wpdb, $shortcode_tags;
error_reporting(E_ALL);
/**
* Attempt to override any WordPress memory limits.
*/
Util::define_wrapper('WP_MEMORY_LIMIT', '512M');
Util::define_wrapper('WP_MAX_MEMORY_LIMIT', '512M');
/**
* Only load core WordPress functionality.
*/
Util::define_wrapper('SHORTINIT', true);
$wpPath = $this->currInstall->getPath();
/**
* Set WP version data global variables, including $wp_version.
*/
include_once "$wpPath/wp-includes/version.php";
/** @noinspection PhpUndefinedVariableInspection $wp_version is defined
* and made available in previous version.php include
*/
if ( Util::betterVersionCompare($wp_version, '4.0', '<') ) {
throw new LSCMException(
"Detected WordPress version as $wp_version. Version 4.0 '
. 'required at minimum."
);
}
/**
* Set needed server variables.
*/
$_SERVER['SCRIPT_FILENAME'] = "$wpPath/wp-admin/plugins.php";
if ( ! $this->isMultisite() ) {
$this->setEnvVar('REQUEST_URI', '');
}
/**
* Set for LSCWP v1.1.5.1+ plugin logic.
*/
if ( $docRoot = $this->currInstall->getDocRoot() ) {
/**
* For enable/disable.
*/
$this->setEnvVar('DOCUMENT_ROOT', $docRoot);
}
$serverName = $this->currInstall->getServerName();
if ( empty($serverName) ) {
$serverName = self::LSCWP_HTTP_HOST_TEST;
}
/**
* For security plugins.
*/
$this->setEnvVar('HTTP_HOST', $serverName);
/**
* Version specific includes may fail on RC releases.
*/
$includeFiles = array(
'/wp-load.php',
'/wp-includes/default-constants.php',
'/wp-includes/formatting.php',
'/wp-includes/meta.php',
'/wp-includes/l10n.php',
'/wp-includes/class-wp-walker.php',
'/wp-includes/capabilities.php'
);
if ( Util::betterVersionCompare($wp_version, '4.4.0', '>=') ) {
$includeFiles[] = '/wp-includes/class-wp-roles.php';
$includeFiles[] = '/wp-includes/class-wp-role.php';
$includeFiles[] = '/wp-includes/class-wp-user.php';
$includeFiles[] = '/wp-includes/rest-api.php';
$includeFiles[] = '/wp-includes/class-wp-http-encoding.php';
$includeFiles[] = '/wp-includes/class-wp-http-proxy.php';
$includeFiles[] = '/wp-includes/class-wp-http-response.php';
$includeFiles[] = '/wp-includes/class-wp-http-curl.php';
$includeFiles[] = '/wp-includes/class-wp-http-cookie.php';
}
$includeFiles[] = '/wp-includes/query.php';
$includeFiles[] = '/wp-includes/theme.php';
$includeFiles[] = '/wp-includes/class-wp-theme.php';
$includeFiles[] = '/wp-includes/user.php';
$includeFiles[] = '/wp-includes/general-template.php';
$includeFiles[] = '/wp-includes/link-template.php';
$includeFiles[] = '/wp-includes/post.php';
$includeFiles[] = '/wp-includes/kses.php';
$includeFiles[] = '/wp-includes/cron.php';
$includeFiles[] = '/wp-includes/update.php';
$includeFiles[] = '/wp-includes/shortcodes.php';
$includeFiles[] = '/wp-includes/http.php';
if ( Util::betterVersionCompare($wp_version, '5.9.0', '>=') ) {
$includeFiles[] = '/wp-includes/class-wp-http.php';
}
else {
$includeFiles[] = '/wp-includes/class-http.php';
}
if ( Util::betterVersionCompare($wp_version, '4.6.0', '>=') ) {
$includeFiles[] = '/wp-includes/class-wp-http-requests-response.php';
}
if ( Util::betterVersionCompare($wp_version, '4.7.0', '>=') ) {
$includeFiles[] = '/wp-includes/class-wp-http-requests-hooks.php';
/**
* Content contained in /wp-includes/query.php for earlier versions.
*/
$includeFiles[] = '/wp-includes/class-wp-query.php';
}
if ( Util::betterVersionCompare($wp_version, '5.0.0', '>=') ) {
$includeFiles[] = '/wp-includes/blocks.php';
$includeFiles[] = '/wp-includes/class-wp-block-parser.php';
}
if ( Util::betterVersionCompare($wp_version, '6.1.0', '>=') ) {
$includeFiles[] = '/wp-includes/class-wp-textdomain-registry.php';
}
$includeFiles[] = '/wp-includes/ms-functions.php';
$includeFiles[] = '/wp-includes/ms-deprecated.php';
$includeFiles[] = '/wp-includes/pluggable.php';
$includeFiles[] = '/wp-admin/includes/plugin.php';
$includeFiles[] = '/wp-admin/includes/file.php';
$includeFiles[] = '/wp-admin/includes/class-wp-upgrader.php';
$includeFiles[] = '/wp-admin/includes/misc.php';
$includeFiles[] = '/wp-admin/includes/template.php';
if ( Util::betterVersionCompare($wp_version, '6.5.0', '>=') ) {
$includeFiles[] = '/wp-includes/class-wp-plugin-dependencies.php';
}
set_error_handler('\Lsc\Wp\WPCaller::warning_handler');
/**
* Force WP to use PHP I/O file handling.
*/
Util::define_wrapper('FS_METHOD', 'direct');
/**
* Trigger an early return from WP Rocket advanced-cache.php to prevent
* WP Rocket from serving a cached copy and killing the process. This
* occurs when calling an action from our control panel plugins and is
* fixed by more closely matching the environment of a direct cli call.
*/
unset($_SERVER['REQUEST_METHOD']);
self::redefineDisabledFunctions();
foreach ( $includeFiles as $file ) {
$file = $wpPath . $file;
if ( !file_exists($file) ) {
throw new LSCMException(
"Could not include missing file $file."
);
}
include_once $file;
}
restore_error_handler();
/**
* Needs to be defined after including files.
*/
Util::define_wrapper('WP_ADMIN', true);
/**
* Define common WP constants and set 'wp_plugin_paths' array.
*/
WpFuncs::wpPluginDirectoryConstants();
/**
* Do not load other plugins.
*/
$GLOBALS['wp_plugin_paths'] = array();
WpFuncs::wpCookieConstants();
/**
* Create global wp_query (WordPress) object entry. Needed during
* LSCWP uninstall.
*/
$wpQueryWrapper = new WpQuery();
$GLOBALS['wp_the_query'] = $wpQueryWrapper->getWpWpQueryObject();
$GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
if ( Util::betterVersionCompare($wp_version, '6.1.0', '>=') ) {
$wpTextdomainRegistryWrapper = new WpTextdomainRegistry();
$GLOBALS['wp_textdomain_registry'] =
$wpTextdomainRegistryWrapper->getWpWpTextdomainRegistryObject();
}
$this->pluginEntry = WpConstants::getWpConstant('WP_PLUGIN_DIR')
. '/' . self::LSCWP_PLUGIN;
if ( $this->loadLscwp && file_exists($this->pluginEntry) ) {
include $this->pluginEntry;
$this->installedLscwpVer = $this->getPluginVersionFromFile();
if ( Util::betterVersionCompare($this->installedLscwpVer, '3.0.4', '<') ) {
$this->includeLSCWPAdvancedCacheFile();
}
}
}
}
webcachemgr/src/View/Model/DashNotifierViewModel.php 0000664 00000005105 15055136441 0016467 0 ustar 00 <?php
/* * ******************************************
* LiteSpeed Web Server Cache Manager
* @author: LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright: (c) 2019
* ******************************************* */
namespace Lsc\Wp\View\Model;
use \Lsc\Wp\Context\Context;
use \Lsc\Wp\Logger;
use \Lsc\Wp\LSCMException;
use \Lsc\Wp\WPDashMsgs;
use \Lsc\Wp\WPInstallStorage;
class DashNotifierViewModel
{
const STEP_CONFIRM = 0;
const STEP_DO_ACTION = 1;
const FLD_ICON_DIR = 'iconDir';
const FLD_DISCOVERED_COUNT = 'discoveredCount';
const FLD_RAP_MSG_IDS = 'rapMsgIds';
const FLD_BAM_MSG_IDS = 'bamMsgIds';
/**
* @var WPInstallStorage
*/
protected $wpInstallStorage;
/**
* @var WPDashMsgs
*/
protected $wpDashMsgs;
/**
* @var mixed[]
*/
protected $tplData = array();
/**
*
* @param WPInstallStorage $wpInstallStorage
* @param WPDashMsgs $wpDashMsgs
*/
public function __construct( WPInstallStorage $wpInstallStorage,
WPDashMsgs $wpDashMsgs )
{
$this->wpInstallStorage = $wpInstallStorage;
$this->wpDashMsgs = $wpDashMsgs;
$this->init();
}
protected function init()
{
$this->setIconDir();
$this->setStoredMsgIds();
$this->setDiscoveredCount();
}
/**
*
* @param string $field
* @return null|string
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
protected function setIconDir()
{
$iconDir = '';
try
{
$iconDir = Context::getOption()->getIconDir();
}
catch ( LSCMException $e )
{
Logger::debug($e->getMessage() . ' Could not get icon directory.');
}
$this->tplData[self::FLD_ICON_DIR] = $iconDir;
}
protected function setStoredMsgIds()
{
$msgs = $this->wpDashMsgs->getMsgData();
$this->tplData[self::FLD_RAP_MSG_IDS] =
array_keys($msgs[WPDashMsgs::KEY_RAP_MSGS]);
$this->tplData[self::FLD_BAM_MSG_IDS] =
array_keys($msgs[WPDashMsgs::KEY_BAM_MSGS]);
}
protected function setDiscoveredCount()
{
$this->tplData[self::FLD_DISCOVERED_COUNT] =
$this->wpInstallStorage->getCount();
}
/**
*
* @return string
*/
public function getTpl()
{
return realpath(__DIR__ . '/../Tpl') . '/DashNotifier.tpl';
}
}
webcachemgr/src/View/Model/VersionManageViewModel.php 0000664 00000012450 15055136442 0016650 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright (c) 2018-2022 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\View\Model;
use Lsc\Wp\WPInstallStorage;
use Lsc\Wp\Context\Context;
use Lsc\Wp\PluginVersion;
use Lsc\Wp\Logger;
use Lsc\Wp\LSCMException;
class VersionManageViewModel
{
/**
* @var string
*/
const FLD_ICON = 'icon';
/**
* @var string
*/
const FLD_VERSION_LIST = 'versionList';
/**
* @var string
*/
const FLD_ALLOWED_VER_LIST = 'allowedList';
/**
* @var string
*/
const FLD_ACTIVE_VER = 'activeVer';
/**
* @var string
*/
const FLD_ERR_MSGS = 'errMsgs';
/**
* @var string
*/
const FLD_STATE = 'state';
/**
* @var int
*/
const ST_INSTALLS_DISCOVERED = 2;
/**
* @deprecated 1.13.4.1 Added back as a deprecated constant after
* accidental removal in v1.13.4. Use
* self::ST_NO_NON_ERROR_INSTALLS_DISCOVERED instead.
*
* @var int
*/
const ST_NO_INSTALLS_DISCOVERED = 1;
/**
* @var int
*/
const ST_NO_NON_ERROR_INSTALLS_DISCOVERED = 1;
/**
* @var int
*/
const ST_SCAN_NEEDED = 0;
/**
* @var WPInstallStorage
*/
protected $wpInstallStorage;
/**
* @var (boolean|string|string[])[]
*/
protected $tplData = array();
/**
*
* @param WPInstallStorage $wpInstallStorage
*
* @throws LSCMException Thrown indirectly by $this->init() call.
*/
public function __construct( WPInstallStorage $wpInstallStorage )
{
$this->wpInstallStorage = $wpInstallStorage;
$this->init();
}
/**
*
* @throws LSCMException Thrown indirectly by $this->setIconPath() call.
* @throws LSCMException Thrown indirectly by $this->setActiveVerData()
* call.
* @throws LSCMException Thrown indirectly by $this->setVerListData() call.
* @throws LSCMException Thrown indirectly by $this->setMsgData() call.
*/
protected function init()
{
$this->setIconPath();
$this->setActiveVerData();
$this->setVerListData();
$this->setStateData();
$this->setMsgData();
}
/**
*
* @param string $field
*
* @return null|boolean|string|string[]
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function setIconPath()
{
$iconPath = '';
try {
$iconDir = Context::getOption()->getIconDir();
$iconPath = "$iconDir/lscwpCurrentVersion.svg";
}
catch ( LSCMException $e ) {
Logger::debug($e->getMessage() . ' Could not get icon directory.');
}
$this->tplData[self::FLD_ICON] = $iconPath;
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function setActiveVerData()
{
try {
$currVer = PluginVersion::getCurrentVersion();
}
catch ( LSCMException $e ) {
Logger::debug(
$e->getMessage() . ' Could not get active LSCWP version.'
);
$currVer = false;
}
$this->tplData[self::FLD_ACTIVE_VER] = $currVer;
}
protected function setStateData()
{
if ( $this->wpInstallStorage->getError() == 0 ) {
if ( $this->wpInstallStorage->getCount(true) > 0 ) {
$this->tplData[self::FLD_STATE] = self::ST_INSTALLS_DISCOVERED;
}
else {
$this->tplData[self::FLD_STATE] =
self::ST_NO_NON_ERROR_INSTALLS_DISCOVERED;
}
}
else {
$this->tplData[self::FLD_STATE] = self::ST_SCAN_NEEDED;
}
}
/**
*
* @throws LSCMException Thrown indirectly by PluginVersion::getInstance()
* call.
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function setVerListData()
{
$vermgr = PluginVersion::getInstance();
try
{
$verList = $vermgr->getShortVersions();
$allowedList = $vermgr->getAllowedVersions();
}
catch ( LSCMException $e )
{
Logger::debug(
$e->getMessage() . ' Could not retrieve version list.'
);
$verList = $allowedList = array();
}
$this->tplData[self::FLD_VERSION_LIST] = $verList;
$this->tplData[self::FLD_ALLOWED_VER_LIST] = $allowedList;
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::getUiMsgs() call.
*/
protected function setMsgData()
{
$this->tplData[self::FLD_ERR_MSGS] = Logger::getUiMsgs(Logger::UI_ERR);
}
/**
*
* @return string
*
* @throws LSCMException Thrown indirectly by Context::getOption() call.
*/
public function getTpl()
{
return Context::getOption()->getSharedTplDir() . '/VersionManage.tpl';
}
}
webcachemgr/src/View/Model/MassDashNotifyProgressViewModel.php 0000664 00000004247 15055136442 0020540 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2019-2025 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\View\Model;
use Lsc\Wp\Context\Context;
use Lsc\Wp\LSCMException;
use Lsc\Wp\Logger;
class MassDashNotifyProgressViewModel
{
const FLD_ICON = 'icon';
const FLD_INSTALLS_COUNT = 'installsCount';
const FLD_ACTIVE_VER = 'activeVer';
/**
* @var string
*/
protected $sessionKey = 'massDashNotifyInfo';
/**
* @var array
*/
protected $tplData = array();
/**
*
* @throws LSCMException Thrown indirectly by $this->init() call.
*/
public function __construct()
{
$this->init();
}
/**
*
* @throws LSCMException Thrown indirectly by $this->setIconPath() call.
*/
protected function init()
{
$this->setIconPath();
$this->grabSessionData();
}
/**
*
* @param string $field
*
* @return null|mixed
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function setIconPath()
{
$iconPath = '';
try
{
$iconPath = Context::getOption()->getIconDir() . '/wpNotifier.svg';
}
catch ( LSCMException $e )
{
Logger::debug("{$e->getMessage()} Could not get icon directory.");
}
$this->tplData[self::FLD_ICON] = $iconPath;
}
protected function grabSessionData()
{
$info = $_SESSION[$this->sessionKey];
$this->tplData[self::FLD_INSTALLS_COUNT] = count($info['installs']);
}
/**
*
* @return string
*
* @throws LSCMException Thrown indirectly by Context::getOption() call.
*/
public function getTpl()
{
return Context::getOption()->getSharedTplDir()
. '/MassDashNotifyProgress.tpl';
}
}
webcachemgr/src/View/Model/MassEnableDisableViewModel.php 0000664 00000005442 15055136442 0017413 0 ustar 00 <?php
/* * ******************************************
* LiteSpeed Web Server Cache Manager
* @author: LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright: (c) 2018-2019
* ******************************************* */
namespace Lsc\Wp\View\Model;
use \Lsc\Wp\Context\Context;
use \Lsc\Wp\Logger;
use \Lsc\Wp\LSCMException;
use \Lsc\Wp\PluginVersion;
use \Lsc\Wp\WPInstallStorage;
class MassEnableDisableViewModel
{
const FLD_ICON = 'icon';
const FLD_ACTIVE_VER = 'activeVer';
const FLD_STATE = 'allowCacheOp';
const ST_INSTALLS_DISCOVERED = 2;
const ST_NO_INSTALLS_DISCOVERED = 1;
const ST_SCAN_NEEDED = 0;
/**
* @var WPInstallStorage
*/
protected $wpInstallStorage;
/**
* @var mixed[]
*/
protected $tplData = array();
/**
*
* @param WPInstallStorage $wpInstallStorage
*/
public function __construct( WPInstallStorage $wpInstallStorage )
{
$this->wpInstallStorage = $wpInstallStorage;
$this->init();
}
protected function init()
{
$this->setIconPath();
$this->setActiveVerData();
$this->setStateData();
}
/**
*
* @param string $field
* @return null|mixed
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
protected function setIconPath()
{
$iconPath = '';
try
{
$iconDir = Context::getOption()->getIconDir();
$iconPath = "{$iconDir}/massEnableDisableCache.svg";
}
catch ( LSCMException $e )
{
Logger::debug($e->getMessage() . ' Could not get icon directory.');
}
$this->tplData[self::FLD_ICON] = $iconPath;
}
protected function setActiveVerData()
{
try
{
$currVer = PluginVersion::getCurrentVersion();
}
catch ( LSCMException $e )
{
Logger::debug($e->getMessage() . ' Could not get active LSCWP version.');
$currVer = false;
}
$this->tplData[self::FLD_ACTIVE_VER] = $currVer;
}
protected function setStateData()
{
if ( $this->wpInstallStorage->getError() == 0 ) {
if ( $this->wpInstallStorage->getCount(true) > 0 ) {
$this->tplData[self::FLD_STATE] = self::ST_INSTALLS_DISCOVERED;
}
else {
$this->tplData[self::FLD_STATE] = self::ST_NO_INSTALLS_DISCOVERED;
}
}
else {
$this->tplData[self::FLD_STATE] = self::ST_SCAN_NEEDED;
}
}
public function getTpl()
{
return Context::getOption()->getSharedTplDir() . '/MassEnableDisable.tpl';
}
}
webcachemgr/src/View/Model/MassDashDisableProgressViewModel.php 0000664 00000004176 15055136442 0020634 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2019-2025 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\View\Model;
use Lsc\Wp\Context\Context;
use Lsc\Wp\LSCMException;
use Lsc\Wp\Logger;
class MassDashDisableProgressViewModel
{
const FLD_ICON = 'icon';
const FLD_INSTALLS_COUNT = 'installsCount';
/**
* @var string
*/
protected $sessionKey = 'massDashDisableInfo';
/**
* @var array
*/
protected $tplData = array();
/**
*
* @throws LSCMException Thrown indirectly by $this->init() call.
*/
public function __construct()
{
$this->init();
}
/**
*
* @throws LSCMException Thrown indirectly by $this->setIconPath() call.
*/
protected function init()
{
$this->setIconPath();
$this->grabSessionData();
}
/**
*
* @param string $field
*
* @return null|mixed
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function setIconPath()
{
$iconPath = '';
try
{
$iconPath = Context::getOption()->getIconDir() . '/wpNotifier.svg';
}
catch ( LSCMException $e )
{
Logger::debug("{$e->getMessage()} Could not get icon directory.");
}
$this->tplData[self::FLD_ICON] = $iconPath;
}
protected function grabSessionData()
{
$info = $_SESSION[$this->sessionKey];
$this->tplData[self::FLD_INSTALLS_COUNT] = count($info['installs']);
}
/**
*
* @return string
*
* @throws LSCMException Thrown indirectly by Context::getOption() call.
*/
public function getTpl()
{
return Context::getOption()->getSharedTplDir()
. '/MassDashDisableProgress.tpl';
}
}
webcachemgr/src/View/Model/FlagUnflagAllProgressViewModel.php 0000664 00000005512 15055136442 0020277 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2025 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\View\Model;
use Lsc\Wp\Context\Context;
use Lsc\Wp\Logger;
use Lsc\Wp\LSCMException;
class FlagUnflagAllProgressViewModel
{
const FLD_ACTION = 'action';
const FLD_ICON = 'icon';
const FLD_INSTALLS_COUNT = 'installsCount';
/**
* @var string Should be either 'flag' or 'unflag'.
*/
protected $action = '';
/**
* @var (int|string)[]
*/
protected $tplData = [];
/**
*
* @param string $action Should be 'flag' or 'unflag'.
*
* @throws LSCMException Thrown when $action value is unrecognized.
* @throws LSCMException Thrown indirectly by $this->init() call.
*/
public function __construct( $action )
{
switch ( $action ) {
case 'flag':
case 'unflag':
$this->action = $action;
break;
default:
throw new LSCMException(
'Unrecognized $action value passed to FlagUnflagAllProgressViewModel constructor.'
);
}
$this->init();
}
/**
*
* @throws LSCMException Thrown indirectly by $this->setIconPath() call.
*/
protected function init()
{
$this->setIconPath();
$this->setAction();
$this->grabSessionData();
}
/**
*
* @param string $field
*
* @return null|int|string
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function setIconPath()
{
$iconPath = '';
try
{
$iconPath = Context::getOption()->getIconDir()
. '/manageCacheInstallations.svg';
}
catch ( LSCMException $e )
{
Logger::debug("{$e->getMessage()}. Could not get icon directory.");
}
$this->tplData[self::FLD_ICON] = $iconPath;
}
protected function setAction()
{
$this->tplData[self::FLD_ACTION] = $this->action;
}
protected function grabSessionData()
{
$this->tplData[self::FLD_INSTALLS_COUNT] =
count($_SESSION['mass_' . $this->action . '_info']['installs']);
}
/**
*
* @return string
*
* @throws LSCMException Thrown indirectly by Context::getOption() call.
*/
public function getTpl()
{
return Context::getOption()->getSharedTplDir()
. '/FlagUnflagAllProgress.tpl';
}
}
webcachemgr/src/View/Model/CacheRootNotSetViewModel.php 0000664 00000001272 15055136442 0017116 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2018-2025 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\View\Model;
use Lsc\Wp\Context\Context;
use Lsc\Wp\LSCMException;
class CacheRootNotSetViewModel
{
public function __construct()
{
/**
* Nothing to do
*/
}
/**
*
* @return string
*
* @throws LSCMException Thrown indirectly by Context::getOption() call.
*/
public function getTpl()
{
return Context::getOption()->getSharedTplDir() . '/CacheRootNotSet.tpl';
}
}
webcachemgr/src/View/Model/ScanProgressStepViewModel.php 0000664 00000007173 15055136442 0017365 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
* @author: LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright: (c) 2020
* @since 1.13.3
* ******************************************* */
namespace Lsc\Wp\View\Model;
use \Lsc\Wp\Context\Context;
use \Lsc\Wp\LSCMException;
use \Lsc\Wp\Logger;
/**
*
* @since 1.13.3
*/
class ScanProgressStepViewModel
{
/**
* @since 1.13.3
* @var string
*/
const FLD_TITLE = 'title';
/**
* @since 1.13.3
* @var string
*/
const FLD_ICON = 'icon';
/**
* @since 1.13.3
* @var string
*/
const FLD_MGR_STEP = 'mgrStep';
/**
* @since 1.13.3
* @var string
*/
const FLD_TOTAL_COUNT = 'totalCount';
/**
* @since 1.13.3
* @var string
*/
const FLD_INSTALLS_COUNT = 'installsCount';
/**
* @since 1.13.3
* @var int
*/
const OP_SCAN = 1;
/**
* @since 1.13.3
* @var int
*/
protected $mgrStep;
/**
* @since 1.13.3
* @var (int|string)[]
*/
protected $tplData = array();
/**
*
* @since 1.13.3
*
* @param int $mgrStep
* @throws LSCMException Thrown indirectly.
*/
public function __construct( $mgrStep )
{
$this->mgrStep = $this->tplData[self::FLD_MGR_STEP] = $mgrStep;
$this->init();
}
/**
*
* @since 1.13.3
*
* @throws LSCMException Thrown indirectly.
*/
protected function init()
{
$this->setTitle();
$this->setIconPath();
$this->grabSessionData();
}
/**
*
* @since 1.13.3
*
* @param string $field
* @return null|int|string
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
/**
*
* @since 1.13.3
*/
protected function setTitle()
{
if ( $this->mgrStep == self::OP_SCAN ) {
$title = 'Scanning/Re-scanning For All WordPress Installations...';
}
else {
$title = 'Discovering New WordPress Installations...';
}
$this->tplData[self::FLD_TITLE] = $title;
}
/**
*
* @since 1.13.3
*
* @throws LSCMException Thrown indirectly.
*/
protected function setIconPath()
{
$iconPath = '';
try
{
$iconDir = Context::getOption()->getIconDir();
$iconPath = "{$iconDir}/manageCacheInstallations.svg";
}
catch ( LSCMException $e )
{
Logger::debug($e->getMessage() . ' Could not get icon directory.');
}
$this->tplData[self::FLD_ICON] = $iconPath;
}
/**
*
* @since 1.13.3
*/
protected function grabSessionData()
{
$info = $_SESSION['scanInfo'];
if ( !empty($info['homeDirs']) ) {
$total = count($info['homeDirs']);
}
else {
$total = count($info['installs']);
}
$this->tplData[self::FLD_TOTAL_COUNT] = $total;
}
/**
*
* @since 1.13.3
*
* @return string
* @throws LSCMException Thrown indirectly.
*/
public function getTpl()
{
$info = $_SESSION['scanInfo'];
if ( !empty($info['homeDirs']) ) {
return Context::getOption()->getSharedTplDir()
. '/ScanProgressStep1.tpl';
}
else {
return Context::getOption()->getSharedTplDir()
. '/ScanProgressStep2.tpl';
}
}
}
webcachemgr/src/View/Model/MassEnableDisableProgressViewModel.php 0000664 00000006473 15055136442 0021145 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2018-2025 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\View\Model;
use Lsc\Wp\Context\Context;
use Lsc\Wp\PluginVersion;
use Lsc\Wp\LSCMException;
use Lsc\Wp\Logger;
class MassEnableDisableProgressViewModel
{
const FLD_ICON = 'icon';
const FLD_ACTION = 'action';
const FLD_INSTALLS_COUNT = 'installsCount';
const FLD_ACTIVE_VER = 'activeVer';
/**
* @var string
*/
protected $action;
/**
* @var string
*/
protected $sessionKey;
/**
* @var array
*/
protected $tplData = array();
/**
*
* @param string $action
*
* @throws LSCMException Thrown indirectly by $this->init() call.
*/
public function __construct( $action )
{
$this->action = $action;
$this->sessionKey = 'mass' . ucfirst($this->action) . 'Info';
$this->init();
}
/**
*
* @throws LSCMException Thrown indirectly by $this->setIconPath().
* @throws LSCMException Thrown indirectly by $this->setActiveVerData()
* call.
*/
protected function init()
{
$this->setIconPath();
$this->tplData[self::FLD_ACTION] = $this->action;
$this->grabSessionData();
$this->setActiveVerData();
}
/**
*
* @param string $field
*
* @return null|mixed
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function setIconPath()
{
$iconPath = '';
try
{
$iconPath = Context::getOption()->getIconDir()
. '/massEnableDisableCache.svg';
}
catch ( LSCMException $e )
{
Logger::debug("{$e->getMessage()} Could not get icon directory.");
}
$this->tplData[self::FLD_ICON] = $iconPath;
}
protected function grabSessionData()
{
$info = $_SESSION[$this->sessionKey];
$this->tplData[self::FLD_INSTALLS_COUNT] = count($info['installs']);
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function setActiveVerData()
{
try {
$activeVer = PluginVersion::getCurrentVersion();
}
catch ( LSCMException $e ) {
Logger::debug(
"{$e->getMessage()} Could not get active LSCWP version."
);
$activeVer = false;
/**
* Unset session data early.
*/
if ( $this->tplData[self::FLD_ACTION] == 'enable' ) {
unset($_SESSION[$this->sessionKey]);
}
}
$this->tplData[self::FLD_ACTIVE_VER] = $activeVer;
}
/**
*
* @return string
*
* @throws LSCMException Thrown indirectly by Context::getOption() call.
*/
public function getTpl()
{
return Context::getOption()->getSharedTplDir()
. '/MassEnableDisableProgress.tpl';
}
}
webcachemgr/src/View/Model/ManageViewModel.php 0000664 00000034314 15055136442 0015305 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2018-2025 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\View\Model;
use Lsc\Wp\Context\Context;
use Lsc\Wp\Util;
use Lsc\Wp\WPInstallStorage;
use Lsc\Wp\WPInstall;
use Lsc\Wp\PluginVersion;
use Lsc\Wp\Logger;
use Lsc\Wp\LSCMException;
class ManageViewModel
{
/**
* @var string
*/
const FLD_ICON_DIR = 'iconDir';
/**
* @var string
*/
const FLD_SCAN_BTN_NAME = 'scanBtnName';
/**
* @var string
*/
const FLD_BTN_STATE = 'btnState';
/**
* @var string
*/
const FLD_ACTIVE_VER = 'activeVer';
/**
* @var string
*/
const FLD_SHOW_LIST = 'showList';
/**
* @var string
*/
const FLD_LIST_DATA = 'listData';
/**
* @var string
*/
const FLD_COUNT_DATA = 'countData';
/**
* @var string
*/
const FLD_INFO_MSGS = 'infoMsgs';
/**
* @var string
*/
const FLD_SUCC_MSGS = 'succMsgs';
/**
* @var string
*/
const FLD_ERR_MSGS = 'errMsgs';
/**
* @var string
*/
const FLD_WARN_MSGS = 'warnMsgs';
/**
* @var string
*/
const COUNT_DATA_INSTALLS = 'installs';
/**
* @var string
*/
const COUNT_DATA_ENABLED = 'enabled';
/**
* @var string
*/
const COUNT_DATA_DISABLED = 'disabled';
/**
* @var string
*/
const COUNT_DATA_WARN = 'warn';
/**
* @var string
*/
const COUNT_DATA_ERROR = 'err';
/**
* @var string
*/
const COUNT_DATA_FLAGGED = 'flagged';
/**
* @var string
*/
const COUNT_DATA_UNFLAGGED = 'unflagged';
/**
* @var WPInstallStorage
*/
protected $wpInstallStorage;
/**
* @var array
*/
protected $tplData = [];
/**
* @var string
*/
protected $iconDir = '';
/**
* @since 1.13.3
* @var string[][]
*/
protected $statusInfo = [
'disabled' => [
'sort' => 'disabled',
'state' => '<span '
. 'class="glyphicon glyphicon-flash status-disabled" '
. 'data-uk-tooltip title="LSCWP is disabled."></span>',
'btn_content' => '<span class="enable_btn"></span>',
'btn_title' => 'Click to enable LSCache',
'onclick' => 'onclick="javascript:lscwpEnableSingle(this);"',
'btn_attributes' => 'data-uk-tooltip',
'btn_state' => ''
],
'enabled' => [
'sort' => 'enabled',
'state' => '<span '
. 'class="glyphicon glyphicon-flash status-enabled" '
. 'data-uk-tooltip title="LSCWP is enabled."></span>',
'btn_content' => '<span class="disable_btn"></span>',
'btn_title' => 'Click to disable LSCache',
'onclick' =>
'onclick="javascript:lscwpDisableSingle(this);"',
'btn_attributes' => 'data-uk-tooltip',
'btn_state' => ''
],
'adv_cache' => [
'sort' => 'warning',
'state' => '<span class="status-warning" data-uk-tooltip '
. 'title="LSCache is enabled but not caching. Please visit the '
. 'WordPress Dashboard for more information."></span>',
'btn_content' => '<span class="disable_btn"></span>',
'btn_title' => 'Click to disable LSCache',
'onclick' =>
'onclick="javascript:lscwpDisableSingle(this);"',
'btn_attributes' => 'data-uk-tooltip',
'btn_state' => ''
],
'disabled_no_active_ver' => [
'sort' => 'disabled',
'state' => '<span '
. 'class="glyphicon glyphicon-flash status-disabled" '
. 'data-uk-tooltip title="LSCWP is disabled."></span>',
'btn_content' => '<span class="inactive-action-btn" '
. 'data-uk-tooltip '
. 'title="No active LSCWP version set! Cannot enable LSCache.">'
. '</span>',
'btn_title' => '',
'onclick' => '',
'btn_attributes' => '',
'btn_state' => 'disabled',
],
'error' => [
'sort' => 'error',
/**
* 'state' added individually later.
*/
'btn_title' => '',
'btn_content' => '<span class="inactive-action-btn"></span>',
'onclick' => '',
'btn_attributes' => '',
'btn_state' => 'disabled'
]
];
/**
* @since 1.13.3
* @var string[][]
*/
protected $flagInfo = [
'unflagged' => [
'sort' => 'unflagged',
'icon' => '<span '
. 'class="glyphicon glyphicon-flag ls-flag ls-flag-unset">'
. '</span>',
'btn_title' => 'Click to set flag',
'onclick' => 'onclick="javascript:lscwpFlagSingle(this);"',
'btn_attributes' => 'data-uk-tooltip'
],
'flagged' => [
'sort' => 'flagged',
'icon' => '<span '
. 'class="glyphicon glyphicon-flag ls-flag ls-flag-set">'
. '</span>',
'btn_title' => 'Click to unset flag',
'onclick' => 'onclick="javascript:lscwpUnflagSingle(this);"',
'btn_attributes' => 'data-uk-tooltip'
],
];
/**
*
* @param WPInstallStorage $wpInstallStorage
*
* @throws LSCMException Thrown indirectly by $this->init() call.
*/
public function __construct( WPInstallStorage $wpInstallStorage )
{
$this->wpInstallStorage = $wpInstallStorage;
$this->init();
}
/**
*
* @throws LSCMException thrown indirectly by $this->setIconDir() call.
* @throws LSCMException thrown indirectly by $this->setActiveVerData()
* call.
* @throws LSCMException thrown indirectly by $this->setMsgData() call.
*/
protected function init()
{
$this->setIconDir();
$this->setBtnDataAndListVisibility();
$this->setActiveVerData();
$this->setListAndCountData();
$this->setMsgData();
}
/**
*
* @param string $field
*
* @return null|mixed
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function setIconDir()
{
$iconDir = '';
try
{
$iconDir = Context::getOption()->getIconDir();
}
catch ( LSCMException $e )
{
Logger::debug("{$e->getMessage()}. Could not get icon directory.");
}
$this->tplData[self::FLD_ICON_DIR] = $iconDir;
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::uiInfo() call.
*/
protected function setBtnDataAndListVisibility()
{
$scanBtnName = 'Re-scan';
$btnState = 'disabled';
if ( ($errStatus = $this->wpInstallStorage->getError()) !== 0 ) {
$this->tplData[self::FLD_SHOW_LIST] = false;
if ( $errStatus == WPInstallStorage::ERR_NOT_EXIST ) {
$scanBtnName = 'Scan';
$msg = 'Start by clicking Scan. This will discover all '
. 'active WordPress installations and add them to a list '
. 'below.';
}
elseif ( $errStatus == WPInstallStorage::ERR_VERSION_LOW ) {
$scanBtnName = 'Scan';
$msg = 'To further improve Cache Management features '
. 'in this version, current installations must be '
. 're-discovered. Please perform a Scan now.';
}
else {
$msg = 'Scan data could not be read. Please perform a Re-scan.';
}
Logger::uiInfo($msg);
}
else {
$this->tplData[self::FLD_SHOW_LIST] = true;
if ( $this->wpInstallStorage->getCount() > 0 ) {
$btnState = '';
}
}
$this->tplData[self::FLD_SCAN_BTN_NAME] = $scanBtnName;
$this->tplData[self::FLD_BTN_STATE] = $btnState;
}
protected function setListAndCountData()
{
$listData = [];
$countData = [
self::COUNT_DATA_INSTALLS => 0,
self::COUNT_DATA_ENABLED => 0,
self::COUNT_DATA_DISABLED => 0,
self::COUNT_DATA_WARN => 0,
self::COUNT_DATA_ERROR => 0,
self::COUNT_DATA_FLAGGED => 0,
self::COUNT_DATA_UNFLAGGED => 0
];
$wpInstalls = $this->wpInstallStorage->getAllWPInstalls();
if ( $wpInstalls !== null ) {
$countData[self::COUNT_DATA_INSTALLS] = count($wpInstalls);
foreach ( $wpInstalls as $wpInstall ) {
$listData[$wpInstall->getPath()] = [
'statusData' =>
$this->getStatusDisplayData($wpInstall, $countData),
'flagData' =>
$this->getFlagDisplayData($wpInstall, $countData),
'siteUrl' => Util::tryIdnToUtf8(
(string)$wpInstall->getData(WPInstall::FLD_SITEURL)
)
];
}
}
$this->tplData[self::FLD_LIST_DATA] = $listData;
$this->tplData[self::FLD_COUNT_DATA] = $countData;
}
/**
*
* @param WPInstall $wpInstall
* @param int[] $countData
*
* @return string[]
*/
protected function getStatusDisplayData(
WPInstall $wpInstall,
array &$countData
)
{
$wpStatus = $wpInstall->getStatus();
if ( $wpInstall->hasFatalError($wpStatus) ) {
$countData[self::COUNT_DATA_ERROR]++;
$fatalErrStateInfo =
Util::getFatalErrorStateMessageAndLink($wpStatus);
$currStatusData = $this->statusInfo['error'];
$currStatusData['state'] = '<a '
. "href=\"{$fatalErrStateInfo['link']}\" "
. 'target="_blank" rel="noopener" data-uk-tooltip '
. "title =\"{$fatalErrStateInfo['stateMsg']}\" "
. 'class="status-error"></a>';
}
elseif ( ($wpStatus & WPInstall::ST_PLUGIN_INACTIVE ) ) {
$countData[self::COUNT_DATA_DISABLED]++;
if ( !$this->getTplData(self::FLD_ACTIVE_VER) ) {
$currStatusData = $this->statusInfo['disabled_no_active_ver'];
}
else {
$currStatusData = $this->statusInfo['disabled'];
}
}
elseif ( !($wpStatus & WPInstall::ST_LSC_ADVCACHE_DEFINED) ) {
$countData[self::COUNT_DATA_WARN]++;
$currStatusData = $this->statusInfo['adv_cache'];
}
else {
$countData[self::COUNT_DATA_ENABLED]++;
$currStatusData = $this->statusInfo['enabled'];
}
return $currStatusData;
}
/**
*
* @param WPInstall $wpInstall
* @param int[] $countData
*
* @return string[]
*/
protected function getFlagDisplayData(
WPInstall $wpInstall,
array &$countData
)
{
if ( ($wpInstall->getStatus() & WPInstall::ST_FLAGGED ) ) {
$countData[self::COUNT_DATA_FLAGGED]++;
$currFlagData = $this->flagInfo['flagged'];
}
else {
$countData[self::COUNT_DATA_UNFLAGGED]++;
$currFlagData = $this->flagInfo['unflagged'];
}
return $currFlagData;
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
* @throws LSCMException Thrown indirectly by Logger::uiWarning() call.
*/
protected function setActiveVerData()
{
try
{
$currVer = PluginVersion::getCurrentVersion();
}
catch ( LSCMException $e )
{
Logger::debug(
"{$e->getMessage()} Could not get active LSCWP version."
);
Logger::uiWarning(
'Active LiteSpeed Cache Plugin version is not set. Enable '
. 'operations cannot be performed. Please go to '
. '<a href="?do=lscwpVersionManager" '
. 'title="Go to Version Manager">Version Manager</a> to '
. 'select a version.'
);
$currVer = false;
}
$this->tplData[self::FLD_ACTIVE_VER] = $currVer;
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::getUiMsgs() call.
* @throws LSCMException Thrown indirectly by Logger::getUiMsgs() call.
* @throws LSCMException Thrown indirectly by Logger::getUiMsgs() call.
* @throws LSCMException Thrown indirectly by Logger::getUiMsgs() call.
*/
protected function setMsgData()
{
$this->tplData[self::FLD_INFO_MSGS] =
Logger::getUiMsgs(Logger::UI_INFO);
$this->tplData[self::FLD_WARN_MSGS] =
Logger::getUiMsgs(Logger::UI_WARN);
$msgs = $this->wpInstallStorage->getAllCmdMsgs();
$this->tplData[self::FLD_SUCC_MSGS] = array_merge(
$msgs['succ'],
Logger::getUiMsgs(Logger::UI_SUCC)
);
$this->tplData[self::FLD_ERR_MSGS] = array_merge(
$msgs['fail'],
$msgs['err'],
Logger::getUiMsgs(Logger::UI_ERR)
);
}
/**
*
* @return string
*
* @throws LSCMException Thrown indirectly by Context::getOption() call.
*/
public function getTpl()
{
return Context::getOption()->getSharedTplDir() . '/Manage.tpl';
}
}
webcachemgr/src/View/Model/VersionChangeViewModel.php 0000664 00000003366 15055136442 0016653 0 ustar 00 <?php
/* * ******************************************
* LiteSpeed Web Server Cache Manager
* @author: LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright: (c) 2018-2019
* ******************************************* */
namespace Lsc\Wp\View\Model;
use \Lsc\Wp\Context\Context;
use \Lsc\Wp\LSCMException;
use \Lsc\Wp\Logger;
class VersionChangeViewModel
{
const FLD_ICON = 'icon';
const FLD_INSTALLS_COUNT = 'installsCount';
const FLD_VER_NUM = 'verNum';
/**
* @var (int|string)[]
*/
protected $tplData = array();
public function __construct()
{
$this->init();
}
protected function init()
{
$this->setIconPath();
$this->grabSessionData();
}
/**
*
* @param string $field
* @return null|int|string
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
protected function setIconPath()
{
$iconPath = '';
try
{
$iconDir = Context::getOption()->getIconDir();
$iconPath = "{$iconDir}/lscwpCurrentVersion.svg";
}
catch ( LSCMException $e )
{
Logger::debug($e->getMessage() . ' Could not get icon directory.');
}
$this->tplData[self::FLD_ICON] = $iconPath;
}
protected function grabSessionData()
{
$info = $_SESSION['verInfo'];
$this->tplData[self::FLD_INSTALLS_COUNT] = count($info['installs']);
$this->tplData[self::FLD_VER_NUM] = $info['verNum'];
}
public function getTpl()
{
return Context::getOption()->getSharedTplDir() . '/VersionChange.tpl';
}
}
webcachemgr/src/View/Model/Ajax/CacheMgrRowViewModel.php 0000664 00000022475 15055136442 0017146 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2018-2025 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\View\Model\Ajax;
use Lsc\Wp\Context\Context;
use Lsc\Wp\LSCMException;
use Lsc\Wp\PluginVersion;
use Lsc\Wp\Util;
use Lsc\Wp\WPInstall;
class CacheMgrRowViewModel
{
const FLD_LIST_DATA = 'listData';
/**
* @var WPInstall
*/
protected $wpInstall;
/**
* @var array
*/
protected $tplData = array();
/**
*
* @param WPInstall $wpInstall
*/
public function __construct( WPInstall $wpInstall )
{
$this->wpInstall = $wpInstall;
$this->init();
}
protected function init()
{
$this->getActiveVerData();
$this->setListRowData();
}
/**
*
* @param string $field
*
* @return null|mixed
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
/**
*
* @param string $type
*
* @return string
*/
public function getSortVal( $type )
{
$listData = $this->getTplData(self::FLD_LIST_DATA);
return $listData[$this->wpInstall->getPath()]["{$type}Data"]['sort'];
}
protected function setListRowData()
{
$this->tplData[self::FLD_LIST_DATA] = [
$this->wpInstall->getPath() => [
'statusData' => $this->getStatusDisplayData(),
'flagData' => $this->getFlagDisplayData(),
'siteUrl' => Util::tryIdnToUtf8(
(string)$this->wpInstall->getData(WPInstall::FLD_SITEURL)
)
]
];
}
/**
*
* @return string[]
*/
protected function getStatusDisplayData()
{
$statusInfo = [
'disabled' => [
'sort' => 'disabled',
'state' => '<span '
. 'class="glyphicon glyphicon-flash status-disabled" '
. 'data-uk-tooltip title="LSCWP is disabled."></span>',
'btn_content' => '<span class="enable_btn"></span>',
'btn_title' => 'Click to enable LSCache',
'onclick' =>
'onclick="javascript:lscwpEnableSingle(this);"',
'btn_attributes' => 'data-uk-tooltip',
'btn_state' => ''
],
'enabled' => [
'sort' => 'enabled',
'state' => '<span '
. 'class="glyphicon glyphicon-flash status-enabled" '
. 'data-uk-tooltip title="LSCWP is enabled."></span>',
'btn_content' => '<span class="disable_btn"></span>',
'btn_title' => 'Click to disable LSCache',
'onclick' =>
'onclick="javascript:lscwpDisableSingle(this);"',
'btn_attributes' => 'data-uk-tooltip',
'btn_state' => ''
],
'adv_cache' => [
'sort' => 'warning',
'state' => '<span class="status-warning" '
. 'data-uk-tooltip '
. 'title="LSCache is enabled but not caching. Please visit '
. 'the WordPress Dashboard for more information."></span>',
'btn_content' => '<span class="disable_btn"></span>',
'btn_title' => 'Click to disable LSCache',
'onclick' =>
'onclick="javascript:lscwpDisableSingle(this);"',
'btn_attributes' => 'data-uk-tooltip',
'btn_state' => ''
],
'disabled_no_active_ver' => [
'sort' => 'disabled',
'state' => '<span '
. 'class="glyphicon glyphicon-flash status-disabled" '
. 'data-uk-tooltip title="LSCWP is disabled."></span>',
'btn_content' => '<span class="inactive-action-btn" '
. 'data-uk-tooltip '
. 'title="No active LSCWP version set! Cannot enable '
. 'LSCache."></span>',
'onclick' => '',
'btn_attributes' => '',
'btn_state' => 'disabled'
],
'error' => [
'sort' => 'error',
/**
* 'state' added individually later.
*/
'btn_title' => '',
'btn_content' => '<span class="inactive-action-btn"></span>',
'onclick' => '',
'btn_attributes' => '',
'btn_state' => 'disabled'
],
'removed' => [
'sort' => 'removed',
'state' => '<span class="status-removed" '
. 'data-uk-tooltip '
. 'title="Installation could not be found and has been '
. 'removed."></span>',
'btn_content' => '<span class="inactive-action-btn"></span>',
'onclick' => '',
'btn_attributes' => '',
'btn_state' => 'disabled'
]
];
$wpStatus = $this->wpInstall->getStatus();
if ( $wpStatus & WPInstall::ST_ERR_REMOVE ) {
$currStatusData = $statusInfo['removed'];
}
elseif ( $this->wpInstall->hasFatalError($wpStatus) ) {
$fatalErrStateInfo =
Util::getFatalErrorStateMessageAndLink($wpStatus);
$currStatusData = $statusInfo['error'];
$currStatusData['state'] = '<a '
. "href=\"{$fatalErrStateInfo['link']}\" "
. 'target="_blank" rel="noopener" data-uk-tooltip '
. "title =\"{$fatalErrStateInfo['stateMsg']}\" "
. 'class="status-error"></a>';
}
elseif ( ($wpStatus & WPInstall::ST_PLUGIN_INACTIVE ) ) {
if ( !$this->getActiveVerData() ) {
$currStatusData = $statusInfo['disabled_no_active_ver'];
}
else {
$currStatusData = $statusInfo['disabled'];
}
}
elseif ( !($wpStatus & WPInstall::ST_LSC_ADVCACHE_DEFINED) ) {
$currStatusData = $statusInfo['adv_cache'];
}
else {
$currStatusData = $statusInfo['enabled'];
}
return $currStatusData;
}
/**
*
* @return string[]
*/
protected function getFlagDisplayData()
{
$flagInfo = [
0 => [
'sort' => 'unflagged',
'icon' => '<span '
. 'class="glyphicon glyphicon-flag ls-flag ls-flag-unset"'
. '></span>',
'btn_title' => 'Click to set flag',
'onclick' => 'onclick="lscwpFlagSingle(this);"',
'btn_attributes' => 'data-uk-tooltip'
],
1 => [
'sort' => 'flagged',
'icon' => '<span '
. 'class="glyphicon glyphicon-flag ls-flag ls-flag-set"'
. '></span>',
'btn_title' => 'Click to unset flag',
'onclick' => 'onclick="lscwpUnflagSingle(this);"',
'btn_attributes' => 'data-uk-tooltip'
],
2 => [
'sort' => 'removed',
'icon' => '<span '
. 'class="glyphicon glyphicon-flag ls-flag ls-flag-removed"'
. '></span>',
'btn_title' => '',
'onclick' => '',
'btn_attributes' => ''
]
];
$wpStatus = $this->wpInstall->getStatus();
if ( $wpStatus & WPInstall::ST_ERR_REMOVE ) {
$currFlagData = $flagInfo[2];
}
elseif ( ($wpStatus & WPInstall::ST_FLAGGED ) ) {
$currFlagData = $flagInfo[1];
}
else {
$currFlagData = $flagInfo[0];
}
return $currFlagData;
}
/**
*
* @return bool|string
*/
protected function getActiveVerData()
{
try {
return PluginVersion::getCurrentVersion();
}
catch ( LSCMException $e ) {
//don't care about the exception in ajax load.
return false;
}
}
/**
*
* @param string $tplID
*
* @return null|string
*
* @throws LSCMException Thrown indirectly by Context::getOption() call.
*/
public function getTpl( $tplID )
{
$sharedTplDir = Context::getOption()->getSharedTplDir();
switch ( $tplID ) {
case 'actions_td':
return "$sharedTplDir/Ajax/CacheMgrActionsCol.tpl";
case 'status_td':
return "$sharedTplDir/Ajax/CacheMgrStatusCol.tpl";
case 'flag_td':
return "$sharedTplDir/Ajax/CacheMgrFlagCol.tpl";
//no default
}
}
}
webcachemgr/src/View/Model/UnflagAllProgressViewModel.php 0000664 00000004062 15055136442 0017504 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2018-2025 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\View\Model;
use Lsc\Wp\Context\Context;
use Lsc\Wp\Logger;
use Lsc\Wp\LSCMException;
class UnflagAllProgressViewModel
{
const FLD_ICON = 'icon';
const FLD_INSTALLS_COUNT = 'installsCount';
/**
* @var (int|string)[]
*/
protected $tplData = [];
/**
*
* @throws LSCMException Thrown indirectly by $this->init() call.
*/
public function __construct()
{
$this->init();
}
/**
*
* @throws LSCMException Thrown indirectly by $this->setIconPath() call.
*/
protected function init()
{
$this->setIconPath();
$this->grabSessionData();
}
/**
*
* @param string $field
*
* @return null|int|string
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
/**
*
* @throws LSCMException Thrown indirectly by Logger::debug() call.
*/
protected function setIconPath()
{
$iconPath = '';
try
{
$iconPath = Context::getOption()->getIconDir()
. '/manageCacheInstallations.svg';
}
catch ( LSCMException $e )
{
Logger::debug("{$e->getMessage()}. Could not get icon directory.");
}
$this->tplData[self::FLD_ICON] = $iconPath;
}
protected function grabSessionData()
{
$this->tplData[self::FLD_INSTALLS_COUNT] =
count($_SESSION['unflagInfo']['installs']);
}
/**
*
* @return string
*
* @throws LSCMException Thrown indirectly by Context::getOption() call.
*/
public function getTpl()
{
return Context::getOption()->getSharedTplDir()
. '/UnflagAllProgress.tpl';
}
}
webcachemgr/src/View/Model/MissingTplViewModel.php 0000664 00000002010 15055136442 0016172 0 ustar 00 <?php
/* * ******************************************
* LiteSpeed Web Server Cache Manager
* @author: LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright: (c) 2018-2019
* ******************************************* */
namespace Lsc\Wp\View\Model;
use \Lsc\Wp\Context\Context;
class MissingTplViewModel
{
const FLD_MSG = 'msg';
/**
* @var string[]
*/
private $tplData = array();
/**
*
* @param string $msg
*/
public function __construct( $msg )
{
$this->init($msg);
}
private function init( $msg )
{
$this->tplData[self::FLD_MSG] = $msg;
}
/**
*
* @param string $field
* @return null|string
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
public function getTpl()
{
return Context::getOption()->getSharedTplDir() . '/MissingTpl.tpl';
}
}
webcachemgr/src/View/Model/ScanProgressViewModel.php 0000664 00000005275 15055136443 0016533 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright (c) 2018-2020
* @deprecated 1.13.3 This file will be removed in a future release.
* ******************************************* */
namespace Lsc\Wp\View\Model;
use \Lsc\Wp\Context\Context;
use \Lsc\Wp\LSCMException;
use \Lsc\Wp\Logger;
/**
*
* @deprecated 1.13.3
*/
class ScanProgressViewModel
{
const FLD_TITLE = 'title';
const FLD_ICON = 'icon';
const FLD_MGR_STEP = 'mgrStep';
const FLD_HOME_DIR_COUNT = 'homeDirCount';
const OP_SCAN = 1;
const OP_DISCOVER_NEW = 2;
/**
* @var int
*/
protected $mgrStep;
/**
* @var (int|string)[]
*/
protected $tplData = array();
/**
*
* @param int $mgrStep
* @throws LSCMException Thrown indirectly.
*/
public function __construct( $mgrStep )
{
$this->mgrStep = $this->tplData[self::FLD_MGR_STEP] = $mgrStep;
$this->init();
}
/**
*
* @throws LSCMException Thrown indirectly.
*/
protected function init()
{
$this->setTitle();
$this->setIconPath();
$this->grabSessionData();
}
/**
*
* @param string $field
* @return null|int|string
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
protected function setTitle()
{
if ( $this->mgrStep == self::OP_SCAN ) {
$title = 'Scanning/Re-scanning For All WordPress Installations...';
}
else {
$title = 'Discovering New WordPress Installations...';
}
$this->tplData[self::FLD_TITLE] = $title;
}
/**
*
* @throws LSCMException Thrown indirectly.
*/
protected function setIconPath()
{
$iconPath = '';
try
{
$iconDir = Context::getOption()->getIconDir();
$iconPath = "{$iconDir}/manageCacheInstallations.svg";
}
catch ( LSCMException $e )
{
Logger::debug($e->getMessage() . ' Could not get icon directory.');
}
$this->tplData[self::FLD_ICON] = $iconPath;
}
protected function grabSessionData()
{
$info = $_SESSION['scanInfo'];
$this->tplData[self::FLD_HOME_DIR_COUNT] = count($info['homeDirs']);
}
/**
*
* @return string
* @throws LSCMException Thrown indirectly.
*/
public function getTpl()
{
return Context::getOption()->getSharedTplDir() . '/ScanProgress.tpl';
}
}
webcachemgr/src/View/Model/RefreshStatusProgressViewModel.php 0000664 00000003260 15055136443 0020441 0 ustar 00 <?php
/* * ******************************************
* LiteSpeed Web Server Cache Manager
* @author: LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright: (c) 2018-2019
* ******************************************* */
namespace Lsc\Wp\View\Model;
use \Lsc\Wp\Context\Context;
use \Lsc\Wp\Logger;
use \Lsc\Wp\LSCMException;
class RefreshStatusProgressViewModel
{
const FLD_ICON = 'icon';
const FLD_INSTALLS_COUNT = 'installsCount';
/**
* @var (string|int)[]
*/
protected $tplData = array();
public function __construct()
{
$this->init();
}
protected function init()
{
$this->setIconPath();
$this->grabSessionData();
}
/**
*
* @param string $field
* @return null|int|string
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
protected function setIconPath()
{
$iconPath = '';
try
{
$iconDir = Context::getOption()->getIconDir();
$iconPath = "{$iconDir}/manageCacheInstallations.svg";
}
catch ( LSCMException $e )
{
Logger::debug($e->getMessage() . ' Could not get icon directory.');
}
$this->tplData[self::FLD_ICON] = $iconPath;
}
protected function grabSessionData()
{
$info = $_SESSION['refreshInfo'];
$this->tplData[self::FLD_INSTALLS_COUNT] = count($info['installs']);
}
public function getTpl()
{
return Context::getOption()->getSharedTplDir() . '/RefreshStatusProgress.tpl';
}
}
webcachemgr/src/View/Model/DataFileMsgViewModel.php 0000664 00000004065 15055136443 0016236 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author Michael Alegre
* @copyright 2018-2025 LiteSpeed Technologies, Inc.
* ******************************************* */
namespace Lsc\Wp\View\Model;
use Lsc\Wp\Context\Context;
use Lsc\Wp\LSCMException;
use Lsc\Wp\WPInstallStorage;
class DataFileMsgViewModel
{
const FLD_TITLE = 'title';
const FLD_DISCOVER = 'discover';
/**
* @var WPInstallStorage
*/
private $wpInstallStorage;
/**
* @var string[]
*/
private $tplData = array();
/**
*
* @param WPInstallStorage $wpInstallStorage
*/
public function __construct( WPInstallStorage $wpInstallStorage )
{
$this->wpInstallStorage = $wpInstallStorage;
$this->init();
}
private function init()
{
$this->setTitleAndDiscover();
}
/**
*
* @param string $field
* @return null|string
*/
public function getTplData( $field )
{
if ( !isset($this->tplData[$field]) ) {
return null;
}
return $this->tplData[$field];
}
private function setTitleAndDiscover()
{
switch ( $this->wpInstallStorage->getError() ) {
case WPInstallStorage::ERR_NOT_EXIST:
$title = 'No Scan Data Found';
$discover = 'discover';
break;
case WPInstallStorage::ERR_CORRUPTED:
$title = 'Scan Data Corrupted';
$discover = 're-discover';
break;
default:
$title = 'Scan Data Needs To Be Updated';
$discover = 're-discover';
}
$this->tplData[self::FLD_TITLE] = $title;
$this->tplData[self::FLD_DISCOVER] = $discover;
}
/**
*
* @return string
*
* @throws LSCMException Thrown indirectly by Context::getOption() call.
*/
public function getTpl()
{
return Context::getOption()->getSharedTplDir() . '/DataFileMsg.tpl';
}
}
webcachemgr/src/View/AjaxView.php 0000664 00000003036 15055136443 0012755 0 ustar 00 <?php
/** ******************************************
* LiteSpeed Web Server Cache Manager
*
* @author LiteSpeed Technologies, Inc. (https://www.litespeedtech.com)
* @copyright (c) 2018-2020
* ******************************************* */
namespace Lsc\Wp\View;
use \Lsc\Wp\LSCMException;
class AjaxView
{
/**
* @var object
*/
private $viewModel;
/**
* @var string
*/
private $sharedTplDir = __DIR__;
/**
*
* @param object $viewModel
*/
public function __construct( $viewModel )
{
$this->viewModel = $viewModel;
}
/**
*
* @param string $tplID
* @return string
* @throws LSCMException Thrown directly and indirectly.
*/
public function getAjaxContent( $tplID = '' )
{
ob_start();
try
{
$this->loadAjaxTpl($this->viewModel->getTpl($tplID));
}
catch ( LSCMException $e )
{
ob_clean();
throw $e;
}
return ob_get_clean();
}
/**
*
* @param string $tplPath
* @throws LSCMException
*/
private function loadAjaxTpl( $tplPath )
{
$tplFile = basename($tplPath);
$custTpl = "{$this->sharedTplDir}/Cust/{$tplFile}";
if ( file_exists($custTpl) ) {
include $custTpl;
}
elseif ( file_exists($tplPath) ) {
include $tplPath;
}
else {
throw new LSCMException("Could not load ajax template {$tplPath}.");
}
}
}
webcachemgr/src/View/Tpl/DataFileMsg.tpl 0000664 00000001164 15055136443 0014126 0 ustar 00 <?php
use \Lsc\Wp\View\Model\DataFileMsgViewModel as ViewModel;
$title = $this->viewModel->getTplData(ViewModel::FLD_TITLE);
$discover = $this->viewModel->getTplData(ViewModel::FLD_DISCOVER);
$d = array(
'title' => $title
);
$this->loadTplBlock('Title.tpl', $d);
?>
<div>
<p>
Please go to
<a href="?do=lscwp_manage" title="Go to Manage Cache Installations">
Manage Cache Installations
</a>
and Scan to <?php echo $discover; ?> all active WordPress installations
before continuing.
</p>
</div>
<?php
$d = array(
'back' => 'Back'
);
$this->loadTplBlock('ButtonPanelBackNext.tpl', $d);
webcachemgr/src/View/Tpl/Blocks/InputSubmitBtn.tpl 0000664 00000001752 15055136443 0016155 0 ustar 00 <?php
/**
* Expects: $d['name'], $d['value']
* Optional: $d['class'], $d['title'], $d['confirm'], $d['onclick'],
* $d['attributes'], $d['state'], and $d['text']
*/
?>
<button type="submit" name="<?php echo $d['name']; ?>"
value="<?php echo $d['value']; ?>"
<?php if ( isset($d['class']) ) : ?>
class="<?php echo $d['class']; ?>"
<?php
endif;
if ( isset($d['title']) ):
?>
title="<?php echo $d['title']; ?>"
<?php
endif;
if ( isset($d['confirm']) ) :
?>
onclick="return confirm('<?php echo $d['confirm']; ?>')"
<?php elseif ( isset($d['onclick']) ): ?>
onclick="return <?php echo $d['onclick']; ?>"
<?php
endif;
echo (isset($d['attributes'])) ? " {$d['attributes']}" : '';
echo (isset($d['state'])) ? " {$d['state']}" : '';
?>
>
<?php echo (isset($d['text'])) ? $d['text'] : $d['value']; ?>
</button>
webcachemgr/src/View/Tpl/FlagUnflagAllProgress.tpl 0000664 00000003122 15055136443 0016166 0 ustar 00 <?php
use Lsc\Wp\View\Model\FlagUnflagAllProgressViewModel as ViewModel;
$action = $this->viewModel->getTplData(ViewModel::FLD_ACTION);
$icon = $this->viewModel->getTplData(ViewModel::FLD_ICON);
$installCount = $this->viewModel->getTplData(ViewModel::FLD_INSTALLS_COUNT);
$ucAction = ucfirst($action);
/** @noinspection SpellCheckingInspection */
$this->loadTplBlock(
'Title.tpl',
[
'title' => "{$ucAction}ging WordPress Installations...",
'icon' => $icon
]
);
?>
<div id="progress-box" class="msg-box">
<?php echo $ucAction; ?>ging <span id ="currIndex">0</span> out of
<span id="totalCount"><?php echo $installCount; ?></span> ...
</div>
<?php
$this->loadTplBlock(
'ButtonPanelBackNext.tpl',
[ 'back' => 'Back', 'backDo' => 'lscwp_manage', 'visibility' => 'hidden' ]
);
?>
<button class="accordion accordion-error" type="button" style="display: none">
Error Messages <span id ="errMsgCnt" class="badge errMsg-badge">0</span>
</button>
<div class="panel panel-error">
<?php
$this->loadTplBlock(
'DivMsgBox.tpl',
[ 'id' => 'errMsgs', 'class' => 'scrollable' ]
);
?>
</div>
<button class="accordion accordion-success" type="button" style="display: none">
Success Messages <span id="succMsgCnt" class="badge succMsg-badge">0</span>
</button>
<div class="panel panel-success">
<?php
$this->loadTplBlock(
'DivMsgBox.tpl',
[ 'id' => 'succMsgs', 'class' => 'scrollable' ]
);
?>
</div>
<script type="text/javascript">
lswsInitDropdownBoxes();
lscwpFlagUnflagAllUpdate(<?php echo ($action == 'unflag') ? '4' : '5'; ?>);
</script>