Bearsampp 2025.8.29
Loading...
Searching...
No Matches
Util Class Reference

Static Public Member Functions

static changePath ($filesToScan, $rootPath=null)
static checkInternetState ()
static cleanArgv ($name, $type='text')
static cleanGetVar ($name, $type='text')
static cleanPostVar ($name, $type='text')
static clearFolder ($path, $exclude=array())
static clearFolders ($paths, $exclude=array())
static contains ($string, $search)
static cp1252ToUtf8 ($data)
static decryptFile ()
static deleteFolder ($path)
static disableLaunchStartup ()
static enableLaunchStartup ()
static endWith ($string, $search)
static findRepos ($initPath, $startPath, $checkFile, $maxDepth=1)
static formatUnixPath ($path)
static formatWindowsPath ($path)
static getApiJson ($url)
static getAppBinsRegKey ($fromRegistry=true)
static getAppPathRegKey ()
static getChangelogUrl ($utmSource=true)
static getCurlHttpHeaders ($url)
static getFilesToScan ($path=null)
static getFolderList ($path)
static getFopenHttpHeaders ($url)
static getGithubRawUrl ($file)
static getGithubUrl ($part=null)
static getGithubUserUrl ($part=null)
static getHeaders ($host, $port, $ssl=false)
static getHttpHeaders ($pingUrl)
static getLatestVersion ($url)
static getMicrotime ()
static getNssmEnvPaths ()
static getPowerShellPath ()
static getProcessorRegKey ()
static getRemoteFilesize ($url, $humanFileSize=true)
static getStartupLnkPath ()
static getSysPathRegKey ()
static getVersionList ($path)
static getWebsiteUrl ($path='', $fragment='', $utmSource=true)
static getWebsiteUrlNoUtm ($path='', $fragment='')
static humanFileSize ($size, $unit='')
static imgToBase64 ($path)
static installService ($bin, $port, $syntaxCheckCmd, $showWindow=false)
static is32BitsOs ()
static isAlphanumeric ($string)
static isLaunchStartup ()
static isPortInUse ($port)
static isValidDomainName ($domainName)
static isValidIp ($ip)
static isValidPort ($port)
static logDebug ($data, $file=null)
static logError ($data, $file=null)
static logInfo ($data, $file=null)
static logInitClass ($classInstance)
static logReloadClass ($classInstance)
static logSeparator ()
static logTrace ($data, $file=null)
static logWarning ($data, $file=null)
static openFileContent ($caption, $content)
static random ($length=32, $withNumeric=true)
static removeService ($service, $name)
static replaceDefine ($path, $var, $value)
static replaceInFile ($path, $replaceList)
static setAppBinsRegKey ($value)
static setAppPathRegKey ($value)
static setSysPathRegKey ($value)
static setupCurlHeaderWithToken ()
static startLoading ()
static startService ($bin, $syntaxCheckCmd, $showWindow=false)
static startWith ($string, $search)
static stopLoading ()
static utf8ToCp1252 ($data)

Data Fields

const LOG_DEBUG = 'DEBUG'
const LOG_ERROR = 'ERROR'
const LOG_INFO = 'INFO'
const LOG_TRACE = 'TRACE'
const LOG_WARNING = 'WARNING'

Static Private Member Functions

static findFile ($startPath, $findFile)
static findFiles ($startPath, $includes=array(''), $recursive=true)
static getPathsToScan ()
static log ($data, $type, $file=null)

Detailed Description

Utility class providing a wide range of static methods for various purposes including:

  • Cleaning and retrieving command line, GET, and POST variables based on type specifications.
  • String manipulation methods to check if strings contain, start with, or end with specified substrings.
  • File and directory management functions for deleting, clearing, or finding files and directories.
  • Logging functionalities tailored for different levels of verbosity (ERROR, WARNING, INFO, DEBUG, TRACE).
  • System utilities for handling registry operations, managing environment variables, and executing system commands.
  • Network utilities to validate IPs, domains, and manage HTTP requests.
  • Helper functions for encoding, decoding, and file operations.

This class is designed to be used as a helper or utility class where methods are accessed statically. This means you do not need to instantiate it to use the methods, but can simply call them using the Util::methodName() syntax.

Usage Example:

$cleanedData = Util::cleanGetVar('data', 'text');
Util::logError('An error occurred');
$isAvailable = Util::isValidIp('192.168.1.1');
static logError($data, $file=null)
static cleanGetVar($name, $type='text')
static isValidIp($ip)

Each method is self-contained and provides specific functionality, making this class a central point for common utility operations needed across a PHP application, especially in environments like web servers or command-line interfaces.

Definition at line 34 of file class.util.php.

Member Function Documentation

◆ changePath()

changePath ( $filesToScan,
$rootPath = null )
static

Replaces old path references with new path references in the specified files.

Parameters
array$filesToScanArray of file paths to scan and modify.
string | null$rootPathThe new root path to replace the old one. If null, uses a default root path.
Returns
array Returns an array with the count of occurrences changed and the count of files changed.

Definition at line 1205 of file class.util.php.

1206 {
1208
1209 $result = array(
1210 'countChangedOcc' => 0,
1211 'countChangedFiles' => 0
1212 );
1213
1214 $rootPath = $rootPath != null ? $rootPath : $bearsamppRoot->getRootPath();
1215 $unixOldPath = self::formatUnixPath($bearsamppCore->getLastPathContent());
1216 $windowsOldPath = self::formatWindowsPath($bearsamppCore->getLastPathContent());
1217 $unixCurrentPath = self::formatUnixPath($rootPath);
1218 $windowsCurrentPath = self::formatWindowsPath($rootPath);
1219
1220 foreach ($filesToScan as $fileToScan) {
1221 $tmpCountChangedOcc = 0;
1222 $fileContentOr = file_get_contents($fileToScan);
1223 $fileContent = $fileContentOr;
1224
1225 // old path
1226 preg_match('#' . $unixOldPath . '#i', $fileContent, $unixMatches);
1227 if (!empty($unixMatches)) {
1228 $fileContent = str_replace($unixOldPath, $unixCurrentPath, $fileContent, $countChanged);
1229 $tmpCountChangedOcc += $countChanged;
1230 }
1231 preg_match('#' . str_replace('\\', '\\\\', $windowsOldPath) . '#i', $fileContent, $windowsMatches);
1232 if (!empty($windowsMatches)) {
1233 $fileContent = str_replace($windowsOldPath, $windowsCurrentPath, $fileContent, $countChanged);
1234 $tmpCountChangedOcc += $countChanged;
1235 }
1236
1237 // placeholders
1238 preg_match('#' . Core::PATH_LIN_PLACEHOLDER . '#i', $fileContent, $unixMatches);
1239 if (!empty($unixMatches)) {
1240 $fileContent = str_replace(Core::PATH_LIN_PLACEHOLDER, $unixCurrentPath, $fileContent, $countChanged);
1241 $tmpCountChangedOcc += $countChanged;
1242 }
1243 preg_match('#' . Core::PATH_WIN_PLACEHOLDER . '#i', $fileContent, $windowsMatches);
1244 if (!empty($windowsMatches)) {
1245 $fileContent = str_replace(Core::PATH_WIN_PLACEHOLDER, $windowsCurrentPath, $fileContent, $countChanged);
1246 $tmpCountChangedOcc += $countChanged;
1247 }
1248
1249 if ($fileContentOr != $fileContent) {
1250 $result['countChangedOcc'] += $tmpCountChangedOcc;
1251 $result['countChangedFiles'] += 1;
1252 file_put_contents($fileToScan, $fileContent);
1253 }
1254 }
1255
1256 return $result;
1257 }
$result
global $bearsamppRoot
global $bearsamppCore
const PATH_LIN_PLACEHOLDER
const PATH_WIN_PLACEHOLDER
static formatWindowsPath($path)
static formatUnixPath($path)

References $bearsamppCore, $bearsamppRoot, $result, formatUnixPath(), formatWindowsPath(), Core\PATH_LIN_PLACEHOLDER, and Core\PATH_WIN_PLACEHOLDER.

Referenced by ActionStartup\changePath(), and ActionSwitchVersion\processWindow().

◆ checkInternetState()

checkInternetState ( )
static

Checks the current state of the internet connection.

This method attempts to reach a well-known website (e.g., www.google.com) to determine the state of the internet connection. It returns true if the connection is successful, otherwise it returns false.

Returns
bool True if the internet connection is active, false otherwise.

Definition at line 1999 of file class.util.php.

2000 {
2001 $connected = @fsockopen('www.google.com', 80);
2002 if ($connected) {
2003 fclose($connected);
2004
2005 return true; // Internet connection is active
2006 } else {
2007 return false; // Internet connection is not active
2008 }
2009 }

Referenced by QuickPick\getQuickpickMenu(), and QuickPick\installModule().

◆ cleanArgv()

cleanArgv ( $name,
$type = 'text' )
static

Cleans and returns a specific command line argument based on the type specified.

Parameters
string$nameThe index of the argument in the $_SERVER['argv'] array.
string$typeThe type of the argument to return: 'text', 'numeric', 'boolean', or 'array'.
Returns
mixed Returns the cleaned argument based on the type or false if the argument is not set.

Definition at line 53 of file class.util.php.

54 {
55 if (isset($_SERVER['argv'])) {
56 if ($type == 'text') {
57 return (isset($_SERVER['argv'][$name]) && !empty($_SERVER['argv'][$name])) ? trim($_SERVER['argv'][$name]) : '';
58 } elseif ($type == 'numeric') {
59 return (isset($_SERVER['argv'][$name]) && is_numeric($_SERVER['argv'][$name])) ? intval($_SERVER['argv'][$name]) : '';
60 } elseif ($type == 'boolean') {
61 return (isset($_SERVER['argv'][$name])) ? true : false;
62 } elseif ($type == 'array') {
63 return (isset($_SERVER['argv'][$name]) && is_array($_SERVER['argv'][$name])) ? $_SERVER['argv'][$name] : array();
64 }
65 }
66
67 return false;
68 }

Referenced by Action\process().

◆ cleanGetVar()

cleanGetVar ( $name,
$type = 'text' )
static

Cleans and returns a specific $_GET variable based on the type specified.

Parameters
string$nameThe name of the $_GET variable.
string$typeThe type of the variable to return: 'text', 'numeric', 'boolean', or 'array'.
Returns
mixed Returns the cleaned $_GET variable based on the type or false if the variable is not set.

Definition at line 78 of file class.util.php.

79 {
80 if (is_string($name)) {
81 if ($type == 'text') {
82 return (isset($_GET[$name]) && !empty($_GET[$name])) ? stripslashes($_GET[$name]) : '';
83 } elseif ($type == 'numeric') {
84 return (isset($_GET[$name]) && is_numeric($_GET[$name])) ? intval($_GET[$name]) : '';
85 } elseif ($type == 'boolean') {
86 return (isset($_GET[$name])) ? true : false;
87 } elseif ($type == 'array') {
88 return (isset($_GET[$name]) && is_array($_GET[$name])) ? $_GET[$name] : array();
89 }
90 }
91
92 return false;
93 }

Referenced by Homepage\__construct().

◆ cleanPostVar()

cleanPostVar ( $name,
$type = 'text' )
static

Cleans and returns a specific $_POST variable based on the type specified.

Parameters
string$nameThe name of the $_POST variable.
string$typeThe type of the variable to return: 'text', 'number', 'float', 'boolean', 'array', or 'content'.
Returns
mixed Returns the cleaned $_POST variable based on the type or false if the variable is not set.

Definition at line 103 of file class.util.php.

104 {
105 if (is_string($name)) {
106 if ($type == 'text') {
107 return (isset($_POST[$name]) && !empty($_POST[$name])) ? stripslashes(trim($_POST[$name])) : '';
108 } elseif ($type == 'number') {
109 return (isset($_POST[$name]) && is_numeric($_POST[$name])) ? intval($_POST[$name]) : '';
110 } elseif ($type == 'float') {
111 return (isset($_POST[$name]) && is_numeric($_POST[$name])) ? floatval($_POST[$name]) : '';
112 } elseif ($type == 'boolean') {
113 return (isset($_POST[$name])) ? true : false;
114 } elseif ($type == 'array') {
115 return (isset($_POST[$name]) && is_array($_POST[$name])) ? $_POST[$name] : array();
116 } elseif ($type == 'content') {
117 return (isset($_POST[$name]) && !empty($_POST[$name])) ? trim($_POST[$name]) : '';
118 }
119 }
120
121 return false;
122 }

◆ clearFolder()

clearFolder ( $path,
$exclude = array() )
static

Recursively clears all files and directories within a specified directory, excluding specified items.

Parameters
string$pathThe path of the directory to clear.
array$excludeAn array of filenames to exclude from deletion.
Returns
array|null Returns an array with the operation status and count of files deleted, or null if the directory cannot be opened.

Definition at line 234 of file class.util.php.

235 {
236 $result = array();
237 $result['return'] = true;
238 $result['nb_files'] = 0;
239
240 $handle = @opendir($path);
241 if (!$handle) {
242 return null;
243 }
244
245 while (false !== ($file = readdir($handle))) {
246 if ($file == '.' || $file == '..' || in_array($file, $exclude)) {
247 continue;
248 }
249 if (is_dir($path . '/' . $file)) {
250 $r = self::clearFolder($path . '/' . $file);
251 if (!$r) {
252 $result['return'] = false;
253
254 return $result;
255 }
256 } else {
257 $r = @unlink($path . '/' . $file);
258 if ($r) {
259 $result['nb_files']++;
260 } else {
261 $result['return'] = false;
262
263 return $result;
264 }
265 }
266 }
267
268 closedir($handle);
269
270 return $result;
271 }
static clearFolder($path, $exclude=array())

References $result, and clearFolder().

Referenced by ActionClearFolders\__construct(), ActionStartup\cleanTmpFolders(), clearFolder(), and clearFolders().

◆ clearFolders()

clearFolders ( $paths,
$exclude = array() )
static

Recursively deletes files from a specified directory while excluding certain files.

Parameters
string$pathThe path to the directory to clear.
array$excludeAn array of filenames to exclude from deletion.
Returns
array Returns an array with the status of the operation and the number of files deleted.

Definition at line 216 of file class.util.php.

217 {
218 $result = array();
219 foreach ($paths as $path) {
220 $result[$path] = self::clearFolder($path, $exclude);
221 }
222
223 return $result;
224 }

References $result, and clearFolder().

◆ contains()

contains ( $string,
$search )
static

Checks if a string contains a specified substring.

Parameters
string$stringThe string to search in.
string$searchThe substring to search for.
Returns
bool Returns true if the substring is found in the string, otherwise false.

Definition at line 132 of file class.util.php.

133 {
134 if (!empty($string) && !empty($search)) {
135 $result = stripos($string, $search);
136 if ($result !== false) {
137 return true;
138 } else {
139 return false;
140 }
141 } else {
142 return false;
143 }
144 }

References $result.

Referenced by BinMailpit\checkPort(), BinXlight\checkPort(), BinMariadb\getCmdLineOutput(), BinMysql\getCmdLineOutput(), is32BitsOs(), and Win32Ps\killBins().

◆ cp1252ToUtf8()

cp1252ToUtf8 ( $data)
static

Converts Windows-1252 encoded data to UTF-8 encoding.

Parameters
string$dataThe Windows-1252 encoded data.
Returns
string Returns the data encoded in UTF-8.

Definition at line 927 of file class.util.php.

928 {
929 return iconv('WINDOWS-1252', 'UTF-8//IGNORE', $data);
930 }

◆ decryptFile()

decryptFile ( )
static

Decrypts a file encrypted with a specified method and returns the content.

Returns
string|false Decrypted content or false on failure.

Definition at line 1922 of file class.util.php.

1923 {
1925
1926 $stringfile = $bearsamppCore->getResourcesPath() . '/string.dat';
1927 $encryptedFile = $bearsamppCore->getResourcesPath() . '/github.dat';
1928 $method = 'AES-256-CBC'; // The same encryption method used
1929
1930 // Get key string
1931 $stringPhrase = @file_get_contents($stringfile);
1932 if ($stringPhrase === false) {
1933 Util::logDebug("Failed to read the file at path: {$stringfile}");
1934
1935 return false;
1936 }
1937
1938 $stringKey = convert_uudecode($stringPhrase);
1939
1940 // Read the encrypted data from the file
1941 $encryptedData = file_get_contents($encryptedFile);
1942 if ($encryptedData === false) {
1943 Util::logDebug("Failed to read the file at path: {$encryptedFile}");
1944
1945 return false;
1946 }
1947
1948 // Decode the base64 encoded data
1949 $data = base64_decode($encryptedData);
1950 if ($data === false) {
1951 Util::logDebug("Failed to decode the data from path: {$encryptedFile}");
1952
1953 return false;
1954 }
1955
1956 // Extract the IV which was prepended to the encrypted data
1957 $ivLength = openssl_cipher_iv_length($method);
1958 $iv = substr($data, 0, $ivLength);
1959 $encrypted = substr($data, $ivLength);
1960
1961 // Decrypt the data
1962 $decrypted = openssl_decrypt($encrypted, $method, $stringKey, 0, $iv);
1963 if ($decrypted === false) {
1964 Util::logDebug("Decryption failed for data from path: {$encryptedFile}");
1965
1966 return false;
1967 }
1968
1969 return $decrypted;
1970 }
static logDebug($data, $file=null)
global $bearsamppConfig
Definition homepage.php:27

References $bearsamppConfig, $bearsamppCore, and logDebug().

Referenced by setupCurlHeaderWithToken().

◆ deleteFolder()

deleteFolder ( $path)
static

Recursively deletes a directory and all its contents.

Parameters
string$pathThe path of the directory to delete.

Definition at line 278 of file class.util.php.

279 {
280 if (is_dir($path)) {
281 if (substr($path, strlen($path) - 1, 1) != '/') {
282 $path .= '/';
283 }
284 $files = glob($path . '*', GLOB_MARK);
285 foreach ($files as $file) {
286 if (is_dir($file)) {
287 self::deleteFolder($file);
288 } else {
289 unlink($file);
290 }
291 }
292 rmdir($path);
293 }
294 }
static deleteFolder($path)

References deleteFolder().

Referenced by deleteFolder(), and ActionStartup\rotationLogs().

◆ disableLaunchStartup()

disableLaunchStartup ( )
static

Disables launching the application at startup by removing the shortcut from the startup folder.

Returns
bool True on success, false on failure.

Definition at line 649 of file class.util.php.

650 {
651 $startupLnkPath = self::getStartupLnkPath();
652
653 // Check if file exists before attempting to delete
654 if (file_exists($startupLnkPath)) {
655 return @unlink($startupLnkPath);
656 }
657
658 // Return true if the file doesn't exist (already disabled)
659 return true;
660 }
static getStartupLnkPath()

References getStartupLnkPath().

Referenced by ActionLaunchStartup\__construct(), and ActionStartup\checkLaunchStartup().

◆ enableLaunchStartup()

enableLaunchStartup ( )
static

Enables launching the application at startup by creating a shortcut in the startup folder.

Returns
bool True on success, false on failure.

Definition at line 639 of file class.util.php.

640 {
641 return Vbs::createShortcut(self::getStartupLnkPath());
642 }
static createShortcut($savePath)

References Vbs\createShortcut().

Referenced by ActionLaunchStartup\__construct(), and ActionStartup\checkLaunchStartup().

◆ endWith()

endWith ( $string,
$search )
static

Checks if a string ends with a specified substring.

This method trims the right side whitespace of the input string before checking if it ends with the specified search substring.

Parameters
string$stringThe string to check.
string$searchThe substring to look for at the end of the string.
Returns
bool Returns true if the string ends with the search substring, otherwise false.

Definition at line 177 of file class.util.php.

178 {
179 $length = strlen($search);
180 $start = $length * -1;
181
182 return (substr($string, $start) === $search);
183 }

Referenced by Batch\exec(), BinApache\getAlias(), BinPhp\getExtensionsFromFolder(), LangProc\getList(), TplAppLogs\getMenuLogs(), BinApache\getModulesFromFolder(), Batch\getProcessUsingPort(), and BinApache\getVhosts().

◆ findFile()

findFile ( $startPath,
$findFile )
staticprivate

Recursively searches for a file starting from a specified directory.

Parameters
string$startPathThe directory path to start the search.
string$findFileThe filename to search for.
Returns
string|false Returns the path to the file if found, or false if not found.

Definition at line 304 of file class.util.php.

305 {
306 $result = false;
307
308 $handle = @opendir($startPath);
309 if (!$handle) {
310 return false;
311 }
312
313 while (false !== ($file = readdir($handle))) {
314 if ($file == '.' || $file == '..') {
315 continue;
316 }
317 if (is_dir($startPath . '/' . $file)) {
318 $result = self::findFile($startPath . '/' . $file, $findFile);
319 if ($result !== false) {
320 break;
321 }
322 } elseif ($file == $findFile) {
323 $result = self::formatUnixPath($startPath . '/' . $file);
324 break;
325 }
326 }
327
328 closedir($handle);
329
330 return $result;
331 }
static findFile($startPath, $findFile)

References $result, findFile(), and formatUnixPath().

Referenced by findFile(), and getPowerShellPath().

◆ findFiles()

findFiles ( $startPath,
$includes = array(''),
$recursive = true )
staticprivate

Recursively finds files in a directory that match a set of inclusion patterns.

Parameters
string$startPathThe directory path to start the search from.
array$includesAn array of file patterns to include in the search. Patterns starting with '!' are excluded.
bool$recursiveDetermines whether the search should be recursive.
Returns
array An array of files that match the inclusion patterns.

Definition at line 1158 of file class.util.php.

1159 {
1160 $result = array();
1161
1162 $handle = @opendir($startPath);
1163 if (!$handle) {
1164 return $result;
1165 }
1166
1167 while (false !== ($file = readdir($handle))) {
1168 if ($file == '.' || $file == '..') {
1169 continue;
1170 }
1171 if (is_dir($startPath . '/' . $file) && $recursive) {
1172 $tmpResults = self::findFiles($startPath . '/' . $file, $includes);
1173 foreach ($tmpResults as $tmpResult) {
1174 $result[] = $tmpResult;
1175 }
1176 } elseif (is_file($startPath . '/' . $file)) {
1177 foreach ($includes as $include) {
1178 if (self::startWith($include, '!')) {
1179 $include = ltrim($include, '!');
1180 if (self::startWith($file, '.') && !self::endWith($file, $include)) {
1181 $result[] = self::formatUnixPath($startPath . '/' . $file);
1182 } elseif ($file != $include) {
1183 $result[] = self::formatUnixPath($startPath . '/' . $file);
1184 }
1185 } elseif (self::endWith($file, $include) || $file == $include || empty($include)) {
1186 $result[] = self::formatUnixPath($startPath . '/' . $file);
1187 }
1188 }
1189 }
1190 }
1191
1192 closedir($handle);
1193
1194 return $result;
1195 }
static findFiles($startPath, $includes=array(''), $recursive=true)

References $result, findFiles(), and formatUnixPath().

Referenced by findFiles(), and getFilesToScan().

◆ findRepos()

findRepos ( $initPath,
$startPath,
$checkFile,
$maxDepth = 1 )
static

Recursively searches for repositories starting from a given path up to a specified depth.

Parameters
string$initPathThe initial path from where the search begins.
string$startPathThe current path from where to search.
string$checkFileThe file name to check for in the directory to consider it a repository.
int$maxDepthThe maximum depth of directories to search into.
Returns
array Returns an array of paths that contain the specified file.

Definition at line 840 of file class.util.php.

841 {
842 $depth = substr_count(str_replace($initPath, '', $startPath), '/');
843 $result = array();
844
845 $handle = @opendir($startPath);
846 if (!$handle) {
847 return $result;
848 }
849
850 while (false !== ($file = readdir($handle))) {
851 if ($file == '.' || $file == '..') {
852 continue;
853 }
854 if (is_dir($startPath . '/' . $file) && ($initPath == $startPath || $depth <= $maxDepth)) {
855 $tmpResults = self::findRepos($initPath, $startPath . '/' . $file, $checkFile, $maxDepth);
856 foreach ($tmpResults as $tmpResult) {
857 $result[] = $tmpResult;
858 }
859 } elseif (is_file($startPath . '/' . $checkFile) && !in_array($startPath, $result)) {
860 $result[] = self::formatUnixPath($startPath);
861 }
862 }
863
864 closedir($handle);
865
866 return $result;
867 }
static findRepos($initPath, $startPath, $checkFile, $maxDepth=1)

References $result, findRepos(), and formatUnixPath().

Referenced by ToolGit\findRepos(), and findRepos().

◆ formatUnixPath()

formatUnixPath ( $path)
static

Converts a Windows-style path to a Unix-style path.

Parameters
string$pathThe Windows-style path to convert.
Returns
string Returns the converted Unix-style path.

Definition at line 888 of file class.util.php.

889 {
890 return str_replace('\\', '/', $path);
891 }

Referenced by changePath(), Root\errorHandler(), Win32Ps\findByPath(), findFile(), findFiles(), findRepos(), BinApache\getAliasContent(), getNssmEnvPaths(), Vbs\getSpecialPath(), BinApache\getVhostContent(), Win32Ps\killBins(), ActionStartup\killOldInstances(), ActionGenSslCertificate\processWindow(), ActionStartup\processWindow(), and ToolGit\reload().

◆ formatWindowsPath()

formatWindowsPath ( $path)
static

◆ getApiJson()

getApiJson ( $url)
static

Sends a GET request to the specified URL and returns the response.

Parameters
string$urlThe URL to send the GET request to.
Returns
string The trimmed response data from the URL.

Definition at line 1559 of file class.util.php.

1560 {
1562
1563 $ch = curl_init();
1564 curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
1565 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1566 curl_setopt($ch, CURLOPT_VERBOSE, true);
1567 curl_setopt($ch, CURLOPT_URL, $url);
1568 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1569 curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
1570 $data = curl_exec($ch);
1571 if (curl_errno($ch)) {
1572 Util::logError('CURL Error: ' . curl_error($ch));
1573 }
1574 curl_close($ch);
1575
1576 return trim($data);
1577 }
static setupCurlHeaderWithToken()

References logError(), and setupCurlHeaderWithToken().

Referenced by getLatestVersion().

◆ getAppBinsRegKey()

getAppBinsRegKey ( $fromRegistry = true)
static

Definition at line 452 of file class.util.php.

453 {
454 global $bearsamppRegistry;
455
456 if ($fromRegistry) {
457 $value = $bearsamppRegistry->getValue(
461 );
462 self::logDebug('App reg key from registry: ' . $value);
463 } else {
464 global $bearsamppBins, $bearsamppTools;
465 $value = '';
466 if ($bearsamppBins->getApache()->isEnable()) {
467 $value .= $bearsamppBins->getApache()->getSymlinkPath() . '/bin;';
468 }
469 if ($bearsamppBins->getPhp()->isEnable()) {
470 $value .= $bearsamppBins->getPhp()->getSymlinkPath() . ';';
471 $value .= $bearsamppBins->getPhp()->getSymlinkPath() . '/pear;';
472 $value .= $bearsamppBins->getPhp()->getSymlinkPath() . '/deps;';
473 $value .= $bearsamppBins->getPhp()->getSymlinkPath() . '/imagick;';
474 }
475 if ($bearsamppBins->getNodejs()->isEnable()) {
476 $value .= $bearsamppBins->getNodejs()->getSymlinkPath() . ';';
477 }
478 if ($bearsamppTools->getComposer()->isEnable()) {
479 $value .= $bearsamppTools->getComposer()->getSymlinkPath() . ';';
480 $value .= $bearsamppTools->getComposer()->getSymlinkPath() . '/vendor/bin;';
481 }
482 if ($bearsamppTools->getGhostscript()->isEnable()) {
483 $value .= $bearsamppTools->getGhostscript()->getSymlinkPath() . '/bin;';
484 }
485 if ($bearsamppTools->getGit()->isEnable()) {
486 $value .= $bearsamppTools->getGit()->getSymlinkPath() . '/bin;';
487 }
488 if ($bearsamppTools->getNgrok()->isEnable()) {
489 $value .= $bearsamppTools->getNgrok()->getSymlinkPath() . ';';
490 }
491 if ($bearsamppTools->getPerl()->isEnable()) {
492 $value .= $bearsamppTools->getPerl()->getSymlinkPath() . '/perl/site/bin;';
493 $value .= $bearsamppTools->getPerl()->getSymlinkPath() . '/perl/bin;';
494 $value .= $bearsamppTools->getPerl()->getSymlinkPath() . '/c/bin;';
495 }
496 if ($bearsamppTools->getPython()->isEnable()) {
497 $value .= $bearsamppTools->getPython()->getSymlinkPath() . '/bin;';
498 }
499 if ($bearsamppTools->getRuby()->isEnable()) {
500 $value .= $bearsamppTools->getRuby()->getSymlinkPath() . '/bin;';
501 }
502 $value = self::formatWindowsPath($value);
503 self::logDebug('Generated app bins reg key: ' . $value);
504 }
505
506 return $value;
507 }
global $bearsamppBins
const HKEY_LOCAL_MACHINE
const APP_BINS_REG_ENTRY

References $bearsamppBins, Registry\APP_BINS_REG_ENTRY, Registry\ENV_KEY, formatWindowsPath(), Registry\HKEY_LOCAL_MACHINE, and logDebug().

Referenced by ActionStartup\checkBinsRegKey(), Win32Service\create(), and ActionSwitchVersion\processWindow().

◆ getAppPathRegKey()

getAppPathRegKey ( )
static

Retrieves the application path from the registry.

Returns
mixed The value of the application path registry key or false on error.

Definition at line 533 of file class.util.php.

534 {
535 global $bearsamppRegistry;
536
537 return $bearsamppRegistry->getValue(
541 );
542 }
const APP_PATH_REG_ENTRY

References Registry\APP_PATH_REG_ENTRY, Registry\ENV_KEY, and Registry\HKEY_LOCAL_MACHINE.

Referenced by ActionStartup\checkPathRegKey().

◆ getChangelogUrl()

getChangelogUrl ( $utmSource = true)
static

Constructs the URL to the changelog page, optionally including UTM parameters.

Parameters
bool$utmSourceWhether to include UTM source parameters.
Returns
string The URL to the changelog page.

Definition at line 1339 of file class.util.php.

1340 {
1341 return self::getWebsiteUrl('doc/changelog', null, $utmSource);
1342 }
static getWebsiteUrl($path='', $fragment='', $utmSource=true)

References getWebsiteUrl().

◆ getCurlHttpHeaders()

getCurlHttpHeaders ( $url)
static

Retrieves HTTP headers from a given URL using cURL.

This method initializes a cURL session, sets various options to fetch headers including disabling SSL peer verification, and executes the request. It logs the raw response for debugging purposes and parses the headers from the response.

Parameters
string$urlThe URL from which to fetch the headers.
Returns
array An array of headers if successful, otherwise an empty array.

Definition at line 1477 of file class.util.php.

1478 {
1479 $result = array();
1480
1481 $ch = curl_init();
1482 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1483 curl_setopt($ch, CURLOPT_VERBOSE, true);
1484 curl_setopt($ch, CURLOPT_HEADER, true);
1485 curl_setopt($ch, CURLOPT_URL, $url);
1486 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
1487
1488 $response = @curl_exec($ch);
1489 if (empty($response)) {
1490 return $result;
1491 }
1492
1493 self::logTrace('getCurlHttpHeaders:' . $response);
1494 $responseHeaders = explode("\r\n\r\n", $response, 2);
1495 if (!isset($responseHeaders[0]) || empty($responseHeaders[0])) {
1496 return $result;
1497 }
1498
1499 return explode("\n", $responseHeaders[0]);
1500 }
$response
static logTrace($data, $file=null)

References $response, $result, and logTrace().

Referenced by getHttpHeaders().

◆ getFilesToScan()

getFilesToScan ( $path = null)
static

Retrieves a list of files to scan from specified paths or default paths.

Parameters
string | null$pathOptional. The path to start scanning from. If null, uses default paths.
Returns
array Returns an array of files found during the scan.

Definition at line 963 of file class.util.php.

964 {
965 $result = array();
966 $pathsToScan = !empty($path) ? $path : self::getPathsToScan();
967 foreach ($pathsToScan as $pathToScan) {
968 $startTime = self::getMicrotime();
969 $findFiles = self::findFiles($pathToScan['path'], $pathToScan['includes'], $pathToScan['recursive']);
970 foreach ($findFiles as $findFile) {
971 $result[] = $findFile;
972 }
973 self::logDebug($pathToScan['path'] . ' scanned in ' . round(self::getMicrotime() - $startTime, 3) . 's');
974 }
975
976 return $result;
977 }
static getMicrotime()
static getPathsToScan()

References $result, findFiles(), getMicrotime(), getPathsToScan(), and logDebug().

Referenced by ActionSwitchVersion\processWindow(), and ActionStartup\scanFolders().

◆ getFolderList()

getFolderList ( $path)
static

Retrieves a list of folders from a specified directory, excluding certain directories.

Parameters
string$pathThe directory path from which to list folders.
Returns
array|bool An array of folder names, or false if the directory cannot be opened.

Definition at line 1837 of file class.util.php.

1838 {
1839 $result = array();
1840
1841 $handle = @opendir($path);
1842 if (!$handle) {
1843 return false;
1844 }
1845
1846 while (false !== ($file = readdir($handle))) {
1847 $filePath = $path . '/' . $file;
1848 if ($file != '.' && $file != '..' && is_dir($filePath) && $file != 'current') {
1849 $result[] = $file;
1850 }
1851 }
1852
1853 closedir($handle);
1854
1855 return $result;
1856 }

References $result.

Referenced by ActionSwitchVersion\__construct(), and getPathsToScan().

◆ getFopenHttpHeaders()

getFopenHttpHeaders ( $url)
static

Retrieves HTTP headers from a given URL using the fopen function.

This method creates a stream context to disable SSL peer and peer name verification, which allows self-signed certificates. It attempts to open the URL and read the HTTP response headers.

Parameters
string$urlThe URL from which to fetch the headers.
Returns
array An array of headers if successful, otherwise an empty array.

Definition at line 1444 of file class.util.php.

1445 {
1446 $result = array();
1447
1448 $context = stream_context_create(array(
1449 'ssl' => array(
1450 'verify_peer' => false,
1451 'verify_peer_name' => false,
1452 'allow_self_signed' => true,
1453 )
1454 ));
1455
1456 $fp = @fopen($url, 'r', false, $context);
1457 if ($fp) {
1458 $meta = stream_get_meta_data($fp);
1459 $result = isset($meta['wrapper_data']) ? $meta['wrapper_data'] : $result;
1460 fclose($fp);
1461 }
1462
1463 return $result;
1464 }

References $result.

Referenced by getHttpHeaders().

◆ getGithubRawUrl()

getGithubRawUrl ( $file)
static

Constructs a URL for raw content from a GitHub repository.

Parameters
string$fileThe file path to append to the base URL.
Returns
string The full URL to the raw content on GitHub.

Definition at line 1823 of file class.util.php.

1824 {
1825 $file = !empty($file) ? '/' . $file : null;
1826
1827 return 'https://raw.githubusercontent.com/' . APP_GITHUB_USER . '/' . APP_GITHUB_REPO . '/main' . $file;
1828 }
const APP_GITHUB_USER
Definition root.php:16
const APP_GITHUB_REPO
Definition root.php:17

References APP_GITHUB_REPO, and APP_GITHUB_USER.

◆ getGithubUrl()

getGithubUrl ( $part = null)
static

Constructs a GitHub repository URL with an optional path.

Parameters
string | null$partOptional path to append to the URL.
Returns
string The full GitHub repository URL.

Definition at line 1809 of file class.util.php.

1810 {
1811 $part = !empty($part) ? '/' . $part : null;
1812
1814 }
static getGithubUserUrl($part=null)

References APP_GITHUB_REPO, and getGithubUserUrl().

◆ getGithubUserUrl()

getGithubUserUrl ( $part = null)
static

Constructs a GitHub user URL with an optional path.

Parameters
string | null$partOptional path to append to the URL.
Returns
string The full GitHub user URL.

Definition at line 1795 of file class.util.php.

1796 {
1797 $part = !empty($part) ? '/' . $part : null;
1798
1799 return 'https://github.com/' . APP_GITHUB_USER . $part;
1800 }

References APP_GITHUB_USER.

Referenced by ActionAbout\__construct(), getGithubUrl(), and ActionAbout\processWindow().

◆ getHeaders()

getHeaders ( $host,
$port,
$ssl = false )
static

Retrieves the initial response line from a specified host and port using a socket connection.

This method optionally uses SSL and creates a stream context similar to getFopenHttpHeaders. It attempts to connect to the host and port, reads the first line of the response, and parses it. Detailed debug information is logged for each header line received.

Parameters
string$hostThe host name or IP address to connect to.
int$portThe port number to connect to.
bool$sslWhether to use SSL (defaults to false).
Returns
array An array containing the first line of the response, split into parts, or an empty array if unsuccessful.

Definition at line 1515 of file class.util.php.

1516 {
1517 $result = array();
1518 $context = stream_context_create(array(
1519 'ssl' => array(
1520 'verify_peer' => false,
1521 'verify_peer_name' => false,
1522 'allow_self_signed' => true,
1523 )
1524 ));
1525
1526 $fp = @stream_socket_client(($ssl ? 'ssl://' : '') . $host . ':' . $port, $errno, $errstr, 5, STREAM_CLIENT_CONNECT, $context);
1527 if ($fp) {
1528 $out = fgets($fp);
1529 $result = explode(PHP_EOL, $out);
1530 @fclose($fp);
1531 }
1532
1533 if (!empty($result)) {
1534 $rebuildResult = array();
1535 foreach ($result as $row) {
1536 $row = trim($row);
1537 if (!empty($row)) {
1538 $rebuildResult[] = $row;
1539 }
1540 }
1541 $result = $rebuildResult;
1542
1543 self::logDebug('getHeaders:');
1544 foreach ($result as $header) {
1545 self::logDebug('-> ' . $header);
1546 }
1547 }
1548
1549 return $result;
1550 }
$port

References $port, $result, and logDebug().

Referenced by BinMailpit\checkPort(), and BinXlight\checkPort().

◆ getHttpHeaders()

getHttpHeaders ( $pingUrl)
static

Retrieves HTTP headers from a given URL using either cURL or fopen, depending on availability.

Parameters
string$pingUrlThe URL to ping for headers.
Returns
array An array of HTTP headers.

Definition at line 1406 of file class.util.php.

1407 {
1408 if (function_exists('curl_version')) {
1410 } else {
1412 }
1413
1414 if (!empty($result)) {
1415 $rebuildResult = array();
1416 foreach ($result as $row) {
1417 $row = trim($row);
1418 if (!empty($row)) {
1419 $rebuildResult[] = $row;
1420 }
1421 }
1422 $result = $rebuildResult;
1423
1424 self::logDebug('getHttpHeaders:');
1425 foreach ($result as $header) {
1426 self::logDebug('-> ' . $header);
1427 }
1428 }
1429
1430 return $result;
1431 }
static getFopenHttpHeaders($url)
static getCurlHttpHeaders($url)

References $result, getCurlHttpHeaders(), getFopenHttpHeaders(), and logDebug().

Referenced by BinApache\checkPort().

◆ getLatestVersion()

getLatestVersion ( $url)
static

Fetches the latest version information from a given URL.

Parameters
string$urlThe URL to fetch version information from.
Returns
array|null Returns an array with 'version' and 'url' if successful, null otherwise.

Definition at line 1266 of file class.util.php.

1267 {
1268 $result = self::getApiJson($url);
1269 if (empty($result)) {
1270 self::logError('Cannot retrieve latest github info for: ' . $result . ' RESULT');
1271
1272 return null;
1273 }
1274
1275 $resultArray = json_decode($result, true);
1276 if (isset($resultArray['tag_name']) && isset($resultArray['assets'][0]['browser_download_url'])) {
1277 $tagName = $resultArray['tag_name'];
1278 $downloadUrl = $resultArray['assets'][0]['browser_download_url'];
1279 $name = $resultArray['name'];
1280 self::logDebug('Latest version tag name: ' . $tagName);
1281 self::logDebug('Download URL: ' . $downloadUrl);
1282 self::logDebug('Name: ' . $name);
1283
1284 return ['version' => $tagName, 'html_url' => $downloadUrl, 'name' => $name];
1285 } else {
1286 self::logError('Tag name, download URL, or name not found in the response: ' . $result);
1287
1288 return null;
1289 }
1290 }
static getApiJson($url)

References $result, getApiJson(), logDebug(), and logError().

Referenced by ActionCheckVersion\__construct(), and ActionCheckVersion\processWindow().

◆ getMicrotime()

getMicrotime ( )
static

Gets the current Unix timestamp with microseconds.

Returns
float Returns the current Unix timestamp combined with microseconds.

Definition at line 445 of file class.util.php.

446 {
447 list($usec, $sec) = explode(' ', microtime());
448
449 return ((float)$usec + (float)$sec);
450 }

Referenced by ActionStartup\__construct(), getFilesToScan(), ActionStartup\installServices(), and ActionStartup\processWindow().

◆ getNssmEnvPaths()

getNssmEnvPaths ( )
static

Retrieves and formats environment paths from a data file. Paths are verified to be directories and formatted to Unix style. Warnings are logged for paths that do not exist.

Returns
string A semicolon-separated string of formatted environment paths. @global object $bearsamppRoot Global object containing root path methods.

Definition at line 1866 of file class.util.php.

1867 {
1868 global $bearsamppRoot;
1869
1870 $result = '';
1871 $nssmEnvPathsFile = $bearsamppRoot->getRootPath() . '/nssmEnvPaths.dat';
1872
1873 if (is_file($nssmEnvPathsFile)) {
1874 $paths = explode(PHP_EOL, file_get_contents($nssmEnvPathsFile));
1875 foreach ($paths as $path) {
1876 $path = trim($path);
1877 if (stripos($path, ':') === false) {
1878 $path = $bearsamppRoot->getRootPath() . '/' . $path;
1879 }
1880 if (is_dir($path)) {
1881 $result .= self::formatUnixPath($path) . ';';
1882 } else {
1883 self::logWarning('Path not found in nssmEnvPaths.dat: ' . $path);
1884 }
1885 }
1886 }
1887
1888 return $result;
1889 }
static logWarning($data, $file=null)

References $bearsamppRoot, $result, formatUnixPath(), and logWarning().

Referenced by Win32Service\create().

◆ getPathsToScan()

getPathsToScan ( )
staticprivate

Retrieves a list of directories and file types to scan within the BEARSAMPP environment.

This method compiles an array of paths from various components of the BEARSAMPP stack, including Apache, PHP, MySQL, MariaDB, PostgreSQL, Node.js, Composer, ConsoleZ, Python and Ruby. Each path entry includes the directory path, file types to include in the scan, and whether the scan should be recursive.

The method uses global variables to access the root paths of each component. It then dynamically fetches specific subdirectories using the getFolderList method (which is assumed to be defined elsewhere in this class or in the global scope) and constructs an array of path specifications.

Each path specification is an associative array with the following keys:

  • 'path': The full directory path to scan.
  • 'includes': An array of file extensions or filenames to include in the scan.
  • 'recursive': A boolean indicating whether the scan should include subdirectories.

The method is designed to be used for setting up scans of configuration files and other important files within the BEARSAMPP environment, possibly for purposes like configuration management, backup, or security auditing.

Returns
array An array of associative arrays, each containing 'path', 'includes', and 'recursive' keys.

Definition at line 1003 of file class.util.php.

1004 {
1005 global $bearsamppRoot, $bearsamppCore, $bearsamppBins, $bearsamppApps, $bearsamppTools;
1006 $paths = array();
1007
1008 // Alias
1009 $paths[] = array(
1010 'path' => $bearsamppRoot->getAliasPath(),
1011 'includes' => array(''),
1012 'recursive' => false
1013 );
1014
1015 // Vhosts
1016 $paths[] = array(
1017 'path' => $bearsamppRoot->getVhostsPath(),
1018 'includes' => array(''),
1019 'recursive' => false
1020 );
1021
1022 // OpenSSL
1023 $paths[] = array(
1024 'path' => $bearsamppCore->getOpenSslPath(),
1025 'includes' => array('openssl.cfg'),
1026 'recursive' => false
1027 );
1028
1029 // Homepage
1030 $paths[] = array(
1031 'path' => $bearsamppCore->getResourcesPath() . '/homepage',
1032 'includes' => array('alias.conf'),
1033 'recursive' => false
1034 );
1035
1036 // Apache
1037 $folderList = self::getFolderList($bearsamppBins->getApache()->getRootPath());
1038 foreach ($folderList as $folder) {
1039 $paths[] = array(
1040 'path' => $bearsamppBins->getApache()->getRootPath() . '/' . $folder,
1041 'includes' => array('.ini', '.conf'),
1042 'recursive' => true
1043 );
1044 }
1045
1046 // PHP
1047 $folderList = self::getFolderList($bearsamppBins->getPhp()->getRootPath());
1048 foreach ($folderList as $folder) {
1049 $paths[] = array(
1050 'path' => $bearsamppBins->getPhp()->getRootPath() . '/' . $folder,
1051 'includes' => array('.php', '.bat', '.ini', '.reg', '.inc'),
1052 'recursive' => true
1053 );
1054 }
1055
1056 // MySQL
1057 $folderList = self::getFolderList($bearsamppBins->getMysql()->getRootPath());
1058 foreach ($folderList as $folder) {
1059 $paths[] = array(
1060 'path' => $bearsamppBins->getMysql()->getRootPath() . '/' . $folder,
1061 'includes' => array('my.ini'),
1062 'recursive' => false
1063 );
1064 }
1065
1066 // MariaDB
1067 $folderList = self::getFolderList($bearsamppBins->getMariadb()->getRootPath());
1068 foreach ($folderList as $folder) {
1069 $paths[] = array(
1070 'path' => $bearsamppBins->getMariadb()->getRootPath() . '/' . $folder,
1071 'includes' => array('my.ini'),
1072 'recursive' => false
1073 );
1074 }
1075
1076 // PostgreSQL
1077 $folderList = self::getFolderList($bearsamppBins->getPostgresql()->getRootPath());
1078 foreach ($folderList as $folder) {
1079 $paths[] = array(
1080 'path' => $bearsamppBins->getPostgresql()->getRootPath() . '/' . $folder,
1081 'includes' => array('.ber', '.conf', '.bat'),
1082 'recursive' => true
1083 );
1084 }
1085
1086 // Node.js
1087 $folderList = self::getFolderList($bearsamppBins->getNodejs()->getRootPath());
1088 foreach ($folderList as $folder) {
1089 $paths[] = array(
1090 'path' => $bearsamppBins->getNodejs()->getRootPath() . '/' . $folder . '/etc',
1091 'includes' => array('npmrc'),
1092 'recursive' => true
1093 );
1094 $paths[] = array(
1095 'path' => $bearsamppBins->getNodejs()->getRootPath() . '/' . $folder . '/node_modules/npm',
1096 'includes' => array('npmrc'),
1097 'recursive' => false
1098 );
1099 }
1100
1101 // Composer
1102 $folderList = self::getFolderList($bearsamppTools->getComposer()->getRootPath());
1103 foreach ($folderList as $folder) {
1104 $paths[] = array(
1105 'path' => $bearsamppTools->getComposer()->getRootPath() . '/' . $folder,
1106 'includes' => array('giscus.json'),
1107 'recursive' => false
1108 );
1109 }
1110
1111 // ConsoleZ
1112 $folderList = self::getFolderList($bearsamppTools->getConsoleZ()->getRootPath());
1113 foreach ($folderList as $folder) {
1114 $paths[] = array(
1115 'path' => $bearsamppTools->getConsoleZ()->getRootPath() . '/' . $folder,
1116 'includes' => array('console.xml', '.ini', '.btm'),
1117 'recursive' => true
1118 );
1119 }
1120
1121 // Python
1122 $folderList = self::getFolderList($bearsamppTools->getPython()->getRootPath());
1123 foreach ($folderList as $folder) {
1124 $paths[] = array(
1125 'path' => $bearsamppTools->getPython()->getRootPath() . '/' . $folder . '/bin',
1126 'includes' => array('.bat'),
1127 'recursive' => false
1128 );
1129 $paths[] = array(
1130 'path' => $bearsamppTools->getPython()->getRootPath() . '/' . $folder . '/settings',
1131 'includes' => array('winpython.ini'),
1132 'recursive' => false
1133 );
1134 }
1135
1136 // Ruby
1137 $folderList = self::getFolderList($bearsamppTools->getRuby()->getRootPath());
1138 foreach ($folderList as $folder) {
1139 $paths[] = array(
1140 'path' => $bearsamppTools->getRuby()->getRootPath() . '/' . $folder . '/bin',
1141 'includes' => array('!.dll', '!.exe'),
1142 'recursive' => false
1143 );
1144 }
1145
1146 return $paths;
1147 }
static getFolderList($path)

References $bearsamppBins, $bearsamppCore, $bearsamppRoot, and getFolderList().

Referenced by getFilesToScan().

◆ getPowerShellPath()

getPowerShellPath ( )
static

Finds the path to the PowerShell executable in the Windows System32 directory.

Returns
string|false Returns the path to powershell.exe if found, otherwise false.

Definition at line 821 of file class.util.php.

822 {
823 if (is_dir('C:\Windows\System32\WindowsPowerShell')) {
824 return self::findFile('C:\Windows\System32\WindowsPowerShell', 'powershell.exe');
825 }
826
827 return false;
828 }

References findFile().

Referenced by TplConsoleZ\getTabPowerShellSection().

◆ getProcessorRegKey()

getProcessorRegKey ( )
static

Retrieves the processor identifier from the registry.

Returns
mixed The value of the processor identifier registry key or false on error.

Definition at line 603 of file class.util.php.

604 {
605 global $bearsamppRegistry;
606
607 return $bearsamppRegistry->getValue(
611 );
612 }
const PROCESSOR_REG_SUBKEY
const PROCESSOR_REG_ENTRY

References Registry\HKEY_LOCAL_MACHINE, Registry\PROCESSOR_REG_ENTRY, and Registry\PROCESSOR_REG_SUBKEY.

Referenced by is32BitsOs().

◆ getRemoteFilesize()

getRemoteFilesize ( $url,
$humanFileSize = true )
static

Retrieves the file size of a remote file.

Parameters
string$urlThe URL of the remote file.
bool$humanFileSizeWhether to return the size in a human-readable format.
Returns
mixed The file size, either in bytes or as a formatted string.

Definition at line 1352 of file class.util.php.

1353 {
1354 $size = 0;
1355
1356 $data = get_headers($url, true);
1357 if (isset($data['Content-Length'])) {
1358 $size = intval($data['Content-Length']);
1359 }
1360
1361 return $humanFileSize ? self::humanFileSize($size) : $size;
1362 }
static humanFileSize($size, $unit='')

References humanFileSize().

◆ getStartupLnkPath()

getStartupLnkPath ( )
static

Retrieves the path for the startup link file.

Returns
string The full path to the startup link file.

Definition at line 619 of file class.util.php.

620 {
621 return Vbs::getStartupPath(APP_TITLE . '.lnk');
622 }
static getStartupPath($file=null)
const APP_TITLE
Definition root.php:13

References APP_TITLE, and Vbs\getStartupPath().

Referenced by disableLaunchStartup().

◆ getSysPathRegKey()

getSysPathRegKey ( )
static

Retrieves the system path from the registry.

Returns
mixed The value of the system path registry key or false on error.

Definition at line 568 of file class.util.php.

569 {
570 global $bearsamppRegistry;
571
572 return $bearsamppRegistry->getValue(
576 );
577 }
const SYSPATH_REG_ENTRY

References Registry\ENV_KEY, Registry\HKEY_LOCAL_MACHINE, and Registry\SYSPATH_REG_ENTRY.

Referenced by ActionStartup\checkSystemPathRegKey().

◆ getVersionList()

getVersionList ( $path)
static

Retrieves a list of version directories within a specified path.

Parameters
string$pathThe path to search for version directories.
Returns
array|false Returns a sorted array of version names, or false if the directory cannot be opened.

Definition at line 418 of file class.util.php.

419 {
420 $result = array();
421
422 $handle = @opendir($path);
423 if (!$handle) {
424 return false;
425 }
426
427 while (false !== ($file = readdir($handle))) {
428 $filePath = $path . '/' . $file;
429 if ($file != '.' && $file != '..' && is_dir($filePath) && $file != 'current') {
430 $result[] = str_replace(basename($path), '', $file);
431 }
432 }
433
434 closedir($handle);
435 natcasesort($result);
436
437 return $result;
438 }

References $result.

Referenced by Module\getVersionList().

◆ getWebsiteUrl()

getWebsiteUrl ( $path = '',
$fragment = '',
$utmSource = true )
static

Constructs a complete website URL with optional path, fragment, and UTM source parameters.

Parameters
string$pathOptional path to append to the base URL.
string$fragmentOptional fragment to append to the URL.
bool$utmSourceWhether to include UTM source parameters.
Returns
string The constructed URL.

Definition at line 1314 of file class.util.php.

1315 {
1316 global $bearsamppCore;
1317
1318 $url = APP_WEBSITE;
1319 if (!empty($path)) {
1320 $url .= '/' . ltrim($path, '/');
1321 }
1322 if ($utmSource) {
1323 $url = rtrim($url, '/') . '/?utm_source=bearsampp-' . $bearsamppCore->getAppVersion();
1324 }
1325 if (!empty($fragment)) {
1326 $url .= $fragment;
1327 }
1328
1329 return $url;
1330 }
const APP_WEBSITE
Definition root.php:14

References $bearsamppCore, and APP_WEBSITE.

Referenced by getChangelogUrl(), TplAppApache\getMenuApache(), TplAppMailpit\getMenuMailpit(), TplAppMariadb\getMenuMariadb(), TplAppMemcached\getMenuMemcached(), TplAppMysql\getMenuMysql(), TplAppNodejs\getMenuNodejs(), TplAppPhp\getMenuPhp(), TplAppPostgresql\getMenuPostgresql(), TplAppXlight\getMenuXlight(), QuickPick\getQuickpickMenu(), TplApp\getSectionMenuRight(), getWebsiteUrlNoUtm(), and ActionAbout\processWindow().

◆ getWebsiteUrlNoUtm()

getWebsiteUrlNoUtm ( $path = '',
$fragment = '' )
static

Constructs a website URL without UTM parameters.

Parameters
string$pathOptional path to append to the base URL.
string$fragmentOptional fragment to append to the URL.
Returns
string The constructed URL without UTM parameters.

Definition at line 1300 of file class.util.php.

1301 {
1302 return self::getWebsiteUrl($path, $fragment, false);
1303 }

References getWebsiteUrl().

Referenced by ActionAbout\__construct().

◆ humanFileSize()

humanFileSize ( $size,
$unit = '' )
static

Converts a file size in bytes to a human-readable format.

Parameters
int$sizeThe file size in bytes.
string$unitThe unit to convert to ('GB', 'MB', 'KB', or ''). If empty, auto-selects the unit.
Returns
string The formatted file size.

Definition at line 1372 of file class.util.php.

1373 {
1374 if ((!$unit && $size >= 1 << 30) || $unit == 'GB') {
1375 return number_format($size / (1 << 30), 2) . 'GB';
1376 }
1377 if ((!$unit && $size >= 1 << 20) || $unit == 'MB') {
1378 return number_format($size / (1 << 20), 2) . 'MB';
1379 }
1380 if ((!$unit && $size >= 1 << 10) || $unit == 'KB') {
1381 return number_format($size / (1 << 10), 2) . 'KB';
1382 }
1383
1384 return number_format($size) . ' bytes';
1385 }

Referenced by getRemoteFilesize().

◆ imgToBase64()

imgToBase64 ( $path)
static

Converts an image file to a base64 encoded string.

Parameters
string$pathThe path to the image file.
Returns
string Returns the base64 encoded string of the image.

Definition at line 900 of file class.util.php.

901 {
902 $type = pathinfo($path, PATHINFO_EXTENSION);
903 $data = file_get_contents($path);
904
905 return 'data:image/' . $type . ';base64,' . base64_encode($data);
906 }

◆ installService()

installService ( $bin,
$port,
$syntaxCheckCmd,
$showWindow = false )
static

Attempts to install and start a service on a specific port, with optional syntax checking and user notifications.

Parameters
object$binAn object containing the binary information and methods related to the service.
int$portThe port number on which the service should run.
string$syntaxCheckCmdThe command to execute for syntax checking of the service configuration.
bool$showWindowOptional. Whether to show message boxes for information, warnings, and errors. Defaults to false.
Returns
bool Returns true if the service is successfully installed and started, false otherwise.

Definition at line 1648 of file class.util.php.

1649 {
1650 global $bearsamppLang, $bearsamppWinbinder;
1651 $name = $bin->getName();
1652 $service = $bin->getService();
1653 $boxTitle = sprintf($bearsamppLang->getValue(Lang::INSTALL_SERVICE_TITLE), $name);
1654
1655 $isPortInUse = self::isPortInUse($port);
1656 if ($isPortInUse === false) {
1657 if (!$service->isInstalled()) {
1658 $service->create();
1659 if ($service->start()) {
1660 self::logInfo(sprintf('%s service successfully installed. (name: %s ; port: %s)', $name, $service->getName(), $port));
1661 if ($showWindow) {
1662 $bearsamppWinbinder->messageBoxInfo(
1663 sprintf($bearsamppLang->getValue(Lang::SERVICE_INSTALLED), $name, $service->getName(), $port),
1664 $boxTitle
1665 );
1666 }
1667
1668 return true;
1669 } else {
1670 $serviceError = sprintf($bearsamppLang->getValue(Lang::SERVICE_INSTALL_ERROR), $name);
1671 $serviceErrorLog = sprintf('Error during the installation of %s service', $name);
1672 if (!empty($syntaxCheckCmd)) {
1673 $cmdSyntaxCheck = $bin->getCmdLineOutput($syntaxCheckCmd);
1674 if (!$cmdSyntaxCheck['syntaxOk']) {
1675 $serviceError .= PHP_EOL . sprintf($bearsamppLang->getValue(Lang::STARTUP_SERVICE_SYNTAX_ERROR), $cmdSyntaxCheck['content']);
1676 $serviceErrorLog .= sprintf(' (conf errors detected : %s)', $cmdSyntaxCheck['content']);
1677 }
1678 }
1679 self::logError($serviceErrorLog);
1680 if ($showWindow) {
1681 $bearsamppWinbinder->messageBoxError($serviceError, $boxTitle);
1682 }
1683 }
1684 } else {
1685 self::logWarning(sprintf('%s service already installed', $name));
1686 if ($showWindow) {
1687 $bearsamppWinbinder->messageBoxWarning(
1688 sprintf($bearsamppLang->getValue(Lang::SERVICE_ALREADY_INSTALLED), $name),
1689 $boxTitle
1690 );
1691 }
1692
1693 return true;
1694 }
1695 } elseif ($service->isRunning()) {
1696 self::logWarning(sprintf('%s service already installed and running', $name));
1697 if ($showWindow) {
1698 $bearsamppWinbinder->messageBoxWarning(
1699 sprintf($bearsamppLang->getValue(Lang::SERVICE_ALREADY_INSTALLED), $name),
1700 $boxTitle
1701 );
1702 }
1703
1704 return true;
1705 } else {
1706 self::logError(sprintf('Port %s is used by an other application : %s', $name));
1707 if ($showWindow) {
1708 $bearsamppWinbinder->messageBoxError(
1709 sprintf($bearsamppLang->getValue(Lang::PORT_NOT_USED_BY), $port, $isPortInUse),
1710 $boxTitle
1711 );
1712 }
1713 }
1714
1715 return false;
1716 }
global $bearsamppLang
const SERVICE_INSTALLED
const INSTALL_SERVICE_TITLE
const STARTUP_SERVICE_SYNTAX_ERROR
const SERVICE_INSTALL_ERROR
const SERVICE_ALREADY_INSTALLED
const PORT_NOT_USED_BY
static logInfo($data, $file=null)
static isPortInUse($port)

References $bearsamppLang, $port, Lang\INSTALL_SERVICE_TITLE, isPortInUse(), logError(), logInfo(), logWarning(), Lang\PORT_NOT_USED_BY, Lang\SERVICE_ALREADY_INSTALLED, Lang\SERVICE_INSTALL_ERROR, Lang\SERVICE_INSTALLED, and Lang\STARTUP_SERVICE_SYNTAX_ERROR.

Referenced by ActionService\install(), BinApache\setEnable(), BinMailpit\setEnable(), BinMariadb\setEnable(), BinMemcached\setEnable(), BinMysql\setEnable(), BinPostgresql\setEnable(), and BinXlight\setEnable().

◆ is32BitsOs()

is32BitsOs ( )
static

Checks if the operating system is 32-bit.

Returns
bool True if the OS is 32-bit, false otherwise.

Definition at line 1392 of file class.util.php.

1393 {
1394 $processor = self::getProcessorRegKey();
1395
1396 return self::contains($processor, 'x86');
1397 }
static contains($string, $search)
static getProcessorRegKey()

References contains(), and getProcessorRegKey().

◆ isAlphanumeric()

isAlphanumeric ( $string)
static

Checks if a string is alphanumeric.

Parameters
string$stringThe string to check.
Returns
bool Returns true if the string is alphanumeric, false otherwise.

Definition at line 1633 of file class.util.php.

1634 {
1635 return ctype_alnum($string);
1636 }

◆ isLaunchStartup()

isLaunchStartup ( )
static

Checks if the application is set to launch at startup.

Returns
bool True if the startup link exists, false otherwise.

Definition at line 629 of file class.util.php.

630 {
631 return file_exists(self::getStartupLnkPath());
632 }

Referenced by ActionReload\__construct(), and TplAppLaunchStartup\process().

◆ isPortInUse()

isPortInUse ( $port)
static

Checks if a specific port is in use.

Parameters
int$portThe port number to check
Returns
mixed False if the port is not in use, otherwise returns the process using the port

Definition at line 1586 of file class.util.php.

1587 {
1588 // Set localIP statically
1589 $localIP = '127.0.0.1';
1590
1591 // Save current error reporting level
1592 $errorReporting = error_reporting();
1593
1594 // Disable error reporting temporarily
1595 error_reporting(0);
1596
1597 $connection = @fsockopen($localIP, $port);
1598
1599 // Restore original error reporting level
1600 error_reporting($errorReporting);
1601
1602 if (is_resource($connection)) {
1603 fclose($connection);
1605
1606 return $process != null ? $process : 'N/A';
1607 }
1608
1609 return false;
1610 }
static getProcessUsingPort($port)

References $port, and Batch\getProcessUsingPort().

Referenced by BinApache\changePort(), BinMailpit\changePort(), BinMariadb\changePort(), BinMemcached\changePort(), BinMysql\changePort(), BinPostgresql\changePort(), BinXlight\changePort(), BinPostgresql\handleNonPostgresUsage(), installService(), and ActionStartup\installServices().

◆ isValidDomainName()

isValidDomainName ( $domainName)
static

Validates a domain name based on specific criteria.

Parameters
string$domainNameThe domain name to validate.
Returns
bool Returns true if the domain name is valid, false otherwise.

Definition at line 1619 of file class.util.php.

1620 {
1621 return preg_match('/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i', $domainName)
1622 && preg_match('/^.{1,253}$/', $domainName)
1623 && preg_match('/^[^\.]{1,63}(\.[^\.]{1,63})*$/', $domainName);
1624 }

Referenced by ActionAddVhost\processWindow(), and ActionEditVhost\processWindow().

◆ isValidIp()

isValidIp ( $ip)
static

Validates an IP address.

Parameters
string$ipThe IP address to validate.
Returns
bool Returns true if the IP address is valid, otherwise false.

Definition at line 340 of file class.util.php.

341 {
342 return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
343 || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
344 }

◆ isValidPort()

isValidPort ( $port)
static

Validates a port number.

Parameters
int$portThe port number to validate.
Returns
bool Returns true if the port number is valid and within the range of 1 to 65535, otherwise false.

Definition at line 353 of file class.util.php.

354 {
355 return is_numeric($port) && ($port > 0 && $port <= 65535);
356 }

References $port.

Referenced by BinApache\changePort(), BinMailpit\changePort(), BinMariadb\changePort(), BinMemcached\changePort(), BinMysql\changePort(), BinPostgresql\changePort(), BinXlight\changePort(), BinApache\checkPort(), BinMailpit\checkPort(), BinMariadb\checkPort(), BinMemcached\checkPort(), BinMysql\checkPort(), BinPostgresql\checkPort(), and BinXlight\checkPort().

◆ log()

log ( $data,
$type,
$file = null )
staticprivate

Logs a message to a specified file or default log file based on the log type.

Parameters
string$dataThe message to log.
string$typeThe type of log message: 'ERROR', 'WARNING', 'INFO', 'DEBUG', or 'TRACE'.
string | null$fileThe file path to write the log message to. If null, uses default log file based on type.

Definition at line 669 of file class.util.php.

670 {
672 $file = $file == null ? ($type == self::LOG_ERROR ? $bearsamppRoot->getErrorLogFilePath() : $bearsamppRoot->getLogFilePath()) : $file;
673 if (!$bearsamppRoot->isRoot()) {
674 $file = $bearsamppRoot->getHomepageLogFilePath();
675 }
676
677 $verbose = array();
678 $verbose[Config::VERBOSE_SIMPLE] = $type == self::LOG_ERROR || $type == self::LOG_WARNING;
679 $verbose[Config::VERBOSE_REPORT] = $verbose[Config::VERBOSE_SIMPLE] || $type == self::LOG_INFO;
680 $verbose[Config::VERBOSE_DEBUG] = $verbose[Config::VERBOSE_REPORT] || $type == self::LOG_DEBUG;
681 $verbose[Config::VERBOSE_TRACE] = $verbose[Config::VERBOSE_DEBUG] || $type == self::LOG_TRACE;
682
683 $writeLog = false;
684 if ($bearsamppConfig->getLogsVerbose() == Config::VERBOSE_SIMPLE && $verbose[Config::VERBOSE_SIMPLE]) {
685 $writeLog = true;
686 } elseif ($bearsamppConfig->getLogsVerbose() == Config::VERBOSE_REPORT && $verbose[Config::VERBOSE_REPORT]) {
687 $writeLog = true;
688 } elseif ($bearsamppConfig->getLogsVerbose() == Config::VERBOSE_DEBUG && $verbose[Config::VERBOSE_DEBUG]) {
689 $writeLog = true;
690 } elseif ($bearsamppConfig->getLogsVerbose() == Config::VERBOSE_TRACE && $verbose[Config::VERBOSE_TRACE]) {
691 $writeLog = true;
692 }
693
694 if ($writeLog) {
695 file_put_contents(
696 $file,
697 '[' . date('Y-m-d H:i:s', time()) . '] # ' . APP_TITLE . ' ' . $bearsamppCore->getAppVersion() . ' # ' . $type . ': ' . $data . PHP_EOL,
698 FILE_APPEND
699 );
700 }
701 }
const VERBOSE_REPORT
const VERBOSE_SIMPLE
const VERBOSE_TRACE
const VERBOSE_DEBUG

References $bearsamppConfig, $bearsamppCore, $bearsamppRoot, APP_TITLE, Config\VERBOSE_DEBUG, Config\VERBOSE_REPORT, Config\VERBOSE_SIMPLE, and Config\VERBOSE_TRACE.

Referenced by logDebug(), logError(), logInfo(), logTrace(), and logWarning().

◆ logDebug()

logDebug ( $data,
$file = null )
static

Logs debug information. This function is a wrapper around the generic log function for debug-level messages.

Parameters
mixed$dataThe data to log.
string | null$fileOptional. The file path to log to. If not provided, a default path is used.

Definition at line 755 of file class.util.php.

756 {
757 self::log($data, self::LOG_DEBUG, $file);
758 }
static log($data, $type, $file=null)

References log().

Referenced by Action\call(), BinApache\changePort(), BinMailpit\changePort(), BinMariadb\changePort(), BinMemcached\changePort(), BinMysql\changePort(), BinPostgresql\changePort(), BinXlight\changePort(), QuickPick\checkDownloadId(), BinApache\checkPort(), BinMailpit\checkPort(), BinMariadb\checkPort(), BinMemcached\checkPort(), BinMysql\checkPort(), BinPostgresql\checkPort(), BinXlight\checkPort(), decryptFile(), Symlinks\deleteCurrentSymlinks(), QuickPick\fetchAndUnzipModule(), getAppBinsRegKey(), getFilesToScan(), getHeaders(), getHttpHeaders(), getLatestVersion(), QuickPick\getModuleUrl(), QuickPick\getVersions(), BinPostgresql\handleNonPostgresUsage(), QuickPick\installModule(), Vbs\killProc(), QuickPick\logHeaders(), Action\process(), QuickPick\rebuildQuickpickJson(), BinApache\refreshAlias(), BinApache\refreshConf(), BinApache\refreshVhosts(), BinApache\setEnable(), BinMailpit\setEnable(), BinMariadb\setEnable(), BinMemcached\setEnable(), BinMysql\setEnable(), BinNodejs\setEnable(), BinPhp\setEnable(), BinPostgresql\setEnable(), BinXlight\setEnable(), Win32Service\start(), BinApache\switchVersion(), BinMailpit\switchVersion(), BinMariadb\switchVersion(), BinMemcached\switchVersion(), BinMysql\switchVersion(), BinNodejs\switchVersion(), BinPhp\switchVersion(), BinPostgresql\switchVersion(), BinXlight\switchVersion(), Core\unzipFile(), AppPhpmyadmin\updateConfig(), AppPhppgadmin\updateConfig(), BinApache\updateConfig(), BinMailpit\updateConfig(), BinMariadb\updateConfig(), BinMemcached\updateConfig(), BinMysql\updateConfig(), BinNodejs\updateConfig(), BinPhp\updateConfig(), BinPostgresql\updateConfig(), BinXlight\updateConfig(), Module\updateConfig(), ToolGit\updateConfig(), ActionStartup\writeLog(), Batch\writeLog(), Nssm\writeLog(), Registry\writeLog(), Vbs\writeLog(), Win32Service\writeLog(), and WinBinder\writeLog().

◆ logError()

logError ( $data,
$file = null )
static

Logs error messages. This function is a wrapper around the generic log function for error-level messages.

Parameters
mixed$dataThe data to log.
string | null$fileOptional. The file path to log to. If not provided, a default path is used.

Definition at line 791 of file class.util.php.

792 {
793 self::log($data, self::LOG_ERROR, $file);
794 }

References log().

Referenced by BinApache\changePort(), BinMailpit\changePort(), BinMariadb\changePort(), BinMemcached\changePort(), BinMysql\changePort(), BinPostgresql\changePort(), BinXlight\changePort(), QuickPick\checkDownloadId(), BinApache\checkPort(), BinMailpit\checkPort(), BinMariadb\checkPort(), BinMemcached\checkPort(), BinMysql\checkPort(), BinPostgresql\checkPort(), BinXlight\checkPort(), Vbs\createShortcut(), Module\createSymlink(), Symlinks\deleteCurrentSymlinks(), QuickPick\fetchAndUnzipModule(), getApiJson(), Core\getAppVersion(), Core\getFileFromUrl(), getLatestVersion(), QuickPick\getModuleUrl(), QuickPick\getQuickpickJson(), QuickPick\getVersions(), QuickPick\installModule(), installService(), ActionCheckVersion\processWindow(), AppPhpmyadmin\reload(), AppPhppgadmin\reload(), BinApache\reload(), BinMailpit\reload(), BinMariadb\reload(), BinMemcached\reload(), BinMysql\reload(), BinNodejs\reload(), BinPhp\reload(), BinPostgresql\reload(), BinXlight\reload(), ToolBruno\reload(), ToolComposer\reload(), ToolConsoleZ\reload(), ToolGhostscript\reload(), ToolGit\reload(), ToolNgrok\reload(), ToolPerl\reload(), ToolPython\reload(), ToolRuby\reload(), removeService(), Win32Service\start(), startService(), TplAppReload\triggerReload(), Core\unzipFile(), AppPhpmyadmin\updateConfig(), AppPhppgadmin\updateConfig(), BinApache\updateConfig(), BinMailpit\updateConfig(), BinMariadb\updateConfig(), BinMemcached\updateConfig(), BinMysql\updateConfig(), BinNodejs\updateConfig(), BinPhp\updateConfig(), BinPostgresql\updateConfig(), BinXlight\updateConfig(), and Nssm\writeLogError().

◆ logInfo()

◆ logInitClass()

◆ logReloadClass()

logReloadClass ( $classInstance)
static

◆ logSeparator()

logSeparator ( )
static

Appends a separator line to multiple log files if they do not already end with it. This function ensures that each log file ends with a clear separator for better readability.

@global object $bearsamppRoot An object that provides paths to various log files.

Definition at line 709 of file class.util.php.

710 {
711 global $bearsamppRoot;
712
713 $logs = array(
714 $bearsamppRoot->getLogFilePath(),
715 $bearsamppRoot->getErrorLogFilePath(),
716 $bearsamppRoot->getServicesLogFilePath(),
717 $bearsamppRoot->getRegistryLogFilePath(),
718 $bearsamppRoot->getStartupLogFilePath(),
719 $bearsamppRoot->getBatchLogFilePath(),
720 $bearsamppRoot->getVbsLogFilePath(),
721 $bearsamppRoot->getWinbinderLogFilePath(),
722 );
723
724 $separator = '========================================================================================' . PHP_EOL;
725 foreach ($logs as $log) {
726 if (!file_exists($log)) {
727 continue; // Skip to the next iteration if the file does not exist
728 }
729 $logContent = @file_get_contents($log);
730 if ($logContent !== false && !self::endWith($logContent, $separator)) {
731 file_put_contents($log, $separator, FILE_APPEND);
732 }
733 }
734 }

References $bearsamppRoot.

Referenced by Root\register().

◆ logTrace()

logTrace ( $data,
$file = null )
static

Logs trace information. This function is a wrapper around the generic log function for trace-level messages.

Parameters
mixed$dataThe data to log.
string | null$fileOptional. The file path to log to. If not provided, a default path is used.

Definition at line 743 of file class.util.php.

744 {
745 self::log($data, self::LOG_TRACE, $file);
746 }

References log().

Referenced by ActionExec\__construct(), ActionManualRestart\__construct(), ActionRebuildini\__construct(), Win32Service\callWin32Service(), BinMysql\changeRootPassword(), ActionLoading\checkAllServicesStarted(), ActionStartup\checkApacheServiceWithTimeout(), ActionStartup\checkMySQLServiceWithTimeout(), BinMysql\checkPort(), BinMysql\checkRootPassword(), Win32Service\create(), OpenSsl\createCrt(), Win32Service\delete(), getCurlHttpHeaders(), Win32Service\infos(), BinMysql\initData(), ActionStartup\installServices(), Win32Service\isInstalled(), Win32Service\isPaused(), Win32Service\isPending(), Win32Service\isRunning(), Win32Service\isStopped(), logInitClass(), logReloadClass(), ActionLoading\processLoading(), ActionStartup\processWindow(), ActionSwitchVersion\processWindow(), BinMailpit\rebuildConf(), BinApache\refreshAlias(), BinApache\refreshConf(), BinApache\refreshVhosts(), Config\replaceAll(), replaceInFile(), ActionStartup\rotationLogs(), BinPhp\setVersion(), Win32Service\status(), Win32Service\stop(), ActionQuit\terminatePhpProcesses(), TplAppReload\triggerReload(), Core\unzipFile(), BinPhp\updateConfig(), and ActionSwitchVersion\updateConfigVersion().

◆ logWarning()

logWarning ( $data,
$file = null )
static

Logs warning messages. This function is a wrapper around the generic log function for warning-level messages.

Parameters
mixed$dataThe data to log.
string | null$fileOptional. The file path to log to. If not provided, a default path is used.

Definition at line 779 of file class.util.php.

780 {
781 self::log($data, self::LOG_WARNING, $file);
782 }

References log().

Referenced by getNssmEnvPaths(), Batch\initializeMysql(), Batch\initializePostgresql(), installService(), ToolGit\reload(), and removeService().

◆ openFileContent()

openFileContent ( $caption,
$content )
static

Opens a file with a given caption and content in the default text editor. The file is created in a temporary directory with a unique name.

Parameters
string$captionThe filename to use when saving the content.
string$contentThe content to write to the file.

@global object $bearsamppRoot Global object to access temporary path. @global object $bearsamppConfig Global configuration object. @global object $bearsamppWinbinder Global object to execute external programs.

Definition at line 1902 of file class.util.php.

1903 {
1904 global $bearsamppRoot, $bearsamppConfig, $bearsamppWinbinder;
1905
1906 $folderPath = $bearsamppRoot->getTmpPath() . '/openFileContent-' . self::random();
1907 if (!is_dir($folderPath)) {
1908 mkdir($folderPath, 0777, true);
1909 }
1910
1911 $filepath = self::formatWindowsPath($folderPath . '/' . $caption);
1912 file_put_contents($filepath, $content);
1913
1914 $bearsamppWinbinder->exec($bearsamppConfig->getNotepad(), '"' . $filepath . '"');
1915 }
static random($length=32, $withNumeric=true)

References $bearsamppConfig, $bearsamppRoot, formatWindowsPath(), and random().

Referenced by ActionDebugApache\__construct(), ActionDebugMariadb\__construct(), ActionDebugMysql\__construct(), and ActionDebugPostgresql\__construct().

◆ random()

random ( $length = 32,
$withNumeric = true )
static

Generates a random string of specified length and character set.

Parameters
int$lengthThe length of the random string to generate.
bool$withNumericWhether to include numeric characters in the random string.
Returns
string Returns the generated random string.

Definition at line 193 of file class.util.php.

194 {
195 $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
196 if ($withNumeric) {
197 $characters .= '0123456789';
198 }
199
200 $randomString = '';
201 for ($i = 0; $i < $length; $i++) {
202 $randomString .= $characters[rand(0, strlen($characters) - 1)];
203 }
204
205 return $randomString;
206 }

Referenced by OpenSsl\createCrt(), Batch\getTmpFile(), and openFileContent().

◆ removeService()

removeService ( $service,
$name )
static

Removes a service if it is installed.

Parameters
Win32Service$serviceThe service object to be removed.
string$nameThe name of the service.
Returns
bool Returns true if the service is successfully removed, false otherwise.

Definition at line 1726 of file class.util.php.

1727 {
1728 if (!($service instanceof Win32Service)) {
1729 self::logError('$service not an instance of Win32Service');
1730
1731 return false;
1732 }
1733
1734 if ($service->isInstalled()) {
1735 if ($service->delete()) {
1736 self::logInfo(sprintf('%s service successfully removed', $name));
1737
1738 return true;
1739 } else {
1740 self::logError(sprintf('Error during the uninstallation of %s service', $name));
1741
1742 return false;
1743 }
1744 } else {
1745 self::logWarning(sprintf('%s service does not exist', $name));
1746 }
1747
1748 return true;
1749 }

References logError(), logInfo(), and logWarning().

Referenced by ActionService\remove(), BinApache\setEnable(), BinMailpit\setEnable(), BinMariadb\setEnable(), BinMemcached\setEnable(), BinMysql\setEnable(), BinPostgresql\setEnable(), and BinXlight\setEnable().

◆ replaceDefine()

replaceDefine ( $path,
$var,
$value )
static

Replaces a defined constant in a file with a new value.

Parameters
string$pathThe file path where the constant is defined.
string$varThe name of the constant.
mixed$valueThe new value for the constant.

Definition at line 365 of file class.util.php.

366 {
367 self::replaceInFile($path, array(
368 '/^define\‍((.*?)' . $var . '(.*?),/' => 'define(\'' . $var . '\', ' . (is_int($value) ? $value : '\'' . $value . '\'') . ');'
369 ));
370 }
static replaceInFile($path, $replaceList)

References replaceInFile().

◆ replaceInFile()

replaceInFile ( $path,
$replaceList )
static

Performs replacements in a file based on a list of regular expression patterns.

Parameters
string$pathThe path to the file where replacements are to be made.
array$replaceListAn associative array where keys are regex patterns and values are replacement strings.

Definition at line 378 of file class.util.php.

379 {
380 if (file_exists($path)) {
381 $lines = file($path);
382 $fp = fopen($path, 'w');
383 foreach ($lines as $nb => $line) {
384 $replaceDone = false;
385 foreach ($replaceList as $regex => $replace) {
386 if (preg_match($regex, $line, $matches)) {
387 $countParams = preg_match_all('/{{(\d+)}}/', $replace, $paramsMatches);
388 if ($countParams > 0 && $countParams <= count($matches)) {
389 foreach ($paramsMatches[1] as $paramsMatch) {
390 $replace = str_replace('{{' . $paramsMatch . '}}', $matches[$paramsMatch], $replace);
391 }
392 }
393 self::logTrace('Replace in file ' . $path . ' :');
394 self::logTrace('## line_num: ' . trim($nb));
395 self::logTrace('## old: ' . trim($line));
396 self::logTrace('## new: ' . trim($replace));
397 fwrite($fp, $replace . PHP_EOL);
398
399 $replaceDone = true;
400 break;
401 }
402 }
403 if (!$replaceDone) {
404 fwrite($fp, $line);
405 }
406 }
407 fclose($fp);
408 }
409 }

References logTrace().

Referenced by BinPostgresql\rebuildConf(), Homepage\refreshCommonsJsContent(), replaceDefine(), ToolGit\setScanStartup(), AppPhpmyadmin\updateConfig(), AppPhppgadmin\updateConfig(), BinApache\updateConfig(), BinMariadb\updateConfig(), BinMysql\updateConfig(), BinPhp\updateConfig(), and BinPostgresql\updateConfig().

◆ setAppBinsRegKey()

setAppBinsRegKey ( $value)
static

Retrieves or generates the application binaries registry key.

Parameters
bool$fromRegistryDetermines whether to retrieve the key from the registry or generate it.
Returns
string Returns the application binaries registry key.

Definition at line 516 of file class.util.php.

517 {
518 global $bearsamppRegistry;
519
520 return $bearsamppRegistry->setStringValue(
524 $value
525 );
526 }

References Registry\APP_BINS_REG_ENTRY, Registry\ENV_KEY, and Registry\HKEY_LOCAL_MACHINE.

Referenced by ActionStartup\checkBinsRegKey(), and ActionSwitchVersion\processWindow().

◆ setAppPathRegKey()

setAppPathRegKey ( $value)
static

Sets the application path in the registry.

Parameters
string$valueThe new value for the application path.
Returns
bool True on success, false on failure.

Definition at line 551 of file class.util.php.

552 {
553 global $bearsamppRegistry;
554
555 return $bearsamppRegistry->setStringValue(
559 $value
560 );
561 }

References Registry\APP_PATH_REG_ENTRY, Registry\ENV_KEY, and Registry\HKEY_LOCAL_MACHINE.

Referenced by ActionStartup\checkPathRegKey().

◆ setSysPathRegKey()

setSysPathRegKey ( $value)
static

Sets the system path in the registry.

Parameters
string$valueThe new value for the system path.
Returns
bool True on success, false on failure.

Definition at line 586 of file class.util.php.

587 {
588 global $bearsamppRegistry;
589
590 return $bearsamppRegistry->setExpandStringValue(
594 $value
595 );
596 }

References Registry\ENV_KEY, Registry\HKEY_LOCAL_MACHINE, and Registry\SYSPATH_REG_ENTRY.

Referenced by ActionStartup\checkSystemPathRegKey().

◆ setupCurlHeaderWithToken()

setupCurlHeaderWithToken ( )
static

Sets up a cURL header array using a decrypted GitHub Personal Access Token.

Returns
array The header array for cURL with authorization and other necessary details.

Definition at line 1977 of file class.util.php.

1978 {
1979 // Usage
1981 $Token = self::decryptFile();
1982
1983 return [
1984 'Accept: application/vnd.github+json',
1985 'Authorization: Token ' . $Token,
1986 'User-Agent: ' . APP_GITHUB_USERAGENT,
1987 'X-GitHub-Api-Version: 2022-11-28'
1988 ];
1989 }
static decryptFile()
const APP_GITHUB_USERAGENT
Definition root.php:18

References $bearsamppConfig, $bearsamppCore, APP_GITHUB_USERAGENT, and decryptFile().

Referenced by getApiJson().

◆ startLoading()

startLoading ( )
static

◆ startService()

startService ( $bin,
$syntaxCheckCmd,
$showWindow = false )
static

Attempts to start a service and performs a syntax check if required.

Parameters
object$binAn object containing service details.
string$syntaxCheckCmdCommand to check syntax errors.
bool$showWindowWhether to show error messages in a window.
Returns
bool Returns true if the service starts successfully, false otherwise.

Definition at line 1760 of file class.util.php.

1761 {
1762 global $bearsamppLang, $bearsamppWinbinder;
1763 $name = $bin->getName();
1764 $service = $bin->getService();
1765 $boxTitle = sprintf($bearsamppLang->getValue(Lang::START_SERVICE_TITLE), $name);
1766
1767 if (!$service->start()) {
1768 $serviceError = sprintf($bearsamppLang->getValue(Lang::START_SERVICE_ERROR), $name);
1769 $serviceErrorLog = sprintf('Error while starting the %s service', $name);
1770 if (!empty($syntaxCheckCmd)) {
1771 $cmdSyntaxCheck = $bin->getCmdLineOutput($syntaxCheckCmd);
1772 if (!$cmdSyntaxCheck['syntaxOk']) {
1773 $serviceError .= PHP_EOL . sprintf($bearsamppLang->getValue(Lang::STARTUP_SERVICE_SYNTAX_ERROR), $cmdSyntaxCheck['content']);
1774 $serviceErrorLog .= sprintf(' (conf errors detected : %s)', $cmdSyntaxCheck['content']);
1775 }
1776 }
1777 self::logError($serviceErrorLog);
1778 if ($showWindow) {
1779 $bearsamppWinbinder->messageBoxError($serviceError, $boxTitle);
1780 }
1781
1782 return false;
1783 }
1784
1785 return true;
1786 }
const START_SERVICE_ERROR
const START_SERVICE_TITLE

References $bearsamppLang, logError(), Lang\START_SERVICE_ERROR, Lang\START_SERVICE_TITLE, and Lang\STARTUP_SERVICE_SYNTAX_ERROR.

Referenced by BinPhp\setEnable(), and ActionService\start().

◆ startWith()

startWith ( $string,
$search )
static

Checks if a string starts with a specified substring.

Parameters
string$stringThe string to check.
string$searchThe substring to look for at the start of the string.
Returns
bool Returns true if the string starts with the search substring, otherwise false.

Definition at line 154 of file class.util.php.

155 {
156 // Return false if string is NULL or empty
157 if ($string === null || $string === '') {
158 return false;
159 }
160
161 $length = strlen($search);
162
163 return (substr($string, 0, $length) === $search);
164 }

Referenced by BinApache\checkPort(), BinMariadb\checkPort(), BinMysql\checkPort(), BinApache\getModulesFromConf(), BinApache\getModulesFromFolder(), BinApache\getOfflineContent(), BinApache\getOnlineContent(), Batch\getOsInfo(), Batch\getPearVersion(), Batch\getProcessUsingPort(), Registry\getValue(), BinApache\getVhostsUrl(), Win32Ps\killBins(), Autoloader\load(), and Registry\setValue().

◆ stopLoading()

stopLoading ( )
static

Stops a previously started loading process and cleans up related resources.

Definition at line 944 of file class.util.php.

945 {
946 global $bearsamppCore;
947 if (file_exists($bearsamppCore->getLoadingPid())) {
948 $pids = file($bearsamppCore->getLoadingPid());
949 foreach ($pids as $pid) {
950 Win32Ps::kill($pid);
951 }
952 @unlink($bearsamppCore->getLoadingPid());
953 }
954 }
static kill($pid)

References $bearsamppCore, and Win32Ps\kill().

Referenced by ActionManualRestart\__construct(), ActionService\__construct(), ActionCheckVersion\showVersionOkMessageBox(), and ActionCheckVersion\showVersionUpdateWindow().

◆ utf8ToCp1252()

utf8ToCp1252 ( $data)
static

Converts UTF-8 encoded data to Windows-1252 encoding.

Parameters
string$dataThe UTF-8 encoded data.
Returns
string Returns the data encoded in Windows-1252.

Definition at line 915 of file class.util.php.

916 {
917 return iconv('UTF-8', 'WINDOWS-1252//IGNORE', $data);
918 }

Referenced by ActionReload\__construct().

Field Documentation

◆ LOG_DEBUG

const LOG_DEBUG = 'DEBUG'

Definition at line 42 of file class.util.php.

◆ LOG_ERROR

const LOG_ERROR = 'ERROR'

This code snippet defines constants for logging levels.

Definition at line 39 of file class.util.php.

◆ LOG_INFO

const LOG_INFO = 'INFO'

Definition at line 41 of file class.util.php.

◆ LOG_TRACE

const LOG_TRACE = 'TRACE'

Definition at line 43 of file class.util.php.

◆ LOG_WARNING

const LOG_WARNING = 'WARNING'

Definition at line 40 of file class.util.php.


The documentation for this class was generated from the following file: