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

Static Public Member Functions

static clearFolder ($path, $exclude=array())
static clearFolders ($paths, $exclude=array())
static clearLoadingText ()
static convertEncoding ($data, $direction='to_cp1252')
static cp1252ToUtf8 ($data)
static deleteFolder ($path)
static disableLaunchStartup ()
static enableLaunchStartup ()
static findFile ($startPath, $findFile)
static findRepos ($initPath, $startPath, $checkFile, $maxDepth=1)
static getFilesToScan ($path=null, $useCache=true, $forceRefresh=false)
static getFolderList ($path)
static getLatestVersion ($url)
static getMicrotime ()
static getVersionList ($path)
static humanFileSize (int $size, string $unit='')
static imgToBase64 ($path)
static is32BitsOs ()
static isAdmin ()
static isLaunchStartup ()
static isValidDomainName ($domainName)
static isValidIp ($ip)
static isValidPort ($port)
static openFileContent ($caption, $content)
static replaceDefine ($path, $var, $value)
static replaceInFile ($path, $replaceList)
static startLoading ()
static stopLoading ()
static updateLoadingText ($text)
static utf8ToCp1252 ($data)

Static Private Member Functions

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

Detailed Description

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

  • Input cleaning and sanitization have been moved to UtilInput.
    See also
    UtilInput
  • String manipulation methods have been moved to UtilString.
    See also
    UtilString
  • File and directory management functions for deleting, clearing, or finding files and directories.
  • System utilities for handling registry operations, managing environment variables, and executing system commands.
  • Helper functions for encoding, decoding, and file operations.

Path formatting (formatWindowsPath / formatUnixPath) has been moved to Path.

See also
Path Logging is handled by the Log class.
Log

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 = UtilInput::cleanGetVar('data', 'text');
$isAvailable = Util::isValidIp('192.168.1.1');
static isValidIp($ip)
static cleanGetVar($name, $type='text')

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

◆ 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 63 of file class.util.php.

64 {
65 $result = array();
66 $result['return'] = true;
67 $result['nb_files'] = 0;
68
69 $handle = @opendir($path);
70 if (!$handle) {
71 return null;
72 }
73
74 while (false !== ($file = readdir($handle))) {
75 if ($file == '.' || $file == '..' || in_array($file, $exclude)) {
76 continue;
77 }
78 if (is_dir($path . '/' . $file)) {
79 $r = self::clearFolder($path . '/' . $file);
80 if (!$r) {
81 $result['return'] = false;
82
83 return $result;
84 }
85 } else {
86 $r = @unlink($path . '/' . $file);
87 if ($r) {
88 $result['nb_files']++;
89 } else {
90 $result['return'] = false;
91
92 return $result;
93 }
94 }
95 }
96
97 closedir($handle);
98
99 return $result;
100 }
$result
static clearFolder($path, $exclude=array())

References $result, and clearFolder().

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

Here is the call graph for this function:
Here is the caller graph for this function:

◆ clearFolders()

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

Clears multiple directories by delegating each one to clearFolder.

Parameters
array$pathsThe paths of the directories to clear.
array$excludeAn array of filenames to exclude from deletion.
Returns
array Returns an associative array keyed by path, containing the clearFolder result for each directory.

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

46 {
47 $result = array();
48 foreach ($paths as $path) {
49 $result[$path] = self::clearFolder($path, $exclude);
50 }
51
52 return $result;
53 }

References $result, and clearFolder().

Here is the call graph for this function:

◆ clearLoadingText()

clearLoadingText ( )
static

Clears the loading status file

Returns
void

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

599 {
600 global $bearsamppCore;
601
602 $statusFile = Path::getTmpPath() . '/loading_status.txt';
603 if (file_exists($statusFile)) {
604 @unlink($statusFile);
605 }
606 }
global $bearsamppCore
static getTmpPath($aetrayPath=false)

References $bearsamppCore, and Path\getTmpPath().

Referenced by stopLoading().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ convertEncoding()

convertEncoding ( $data,
$direction = 'to_cp1252' )
static

Converts data between UTF-8 and Windows-1252 encodings.

Parameters
string$dataThe data to convert.
string$directionThe conversion direction: 'to_cp1252' or 'to_utf8'. Defaults to 'to_cp1252'.
Returns
string The converted data.

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

503 {
504 if ($direction === 'to_utf8') {
505 return self::cp1252ToUtf8($data);
506 } else {
507 return self::utf8ToCp1252($data);
508 }
509 }
static cp1252ToUtf8($data)
static utf8ToCp1252($data)

References cp1252ToUtf8(), and utf8ToCp1252().

Here is the call graph for this function:

◆ 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 530 of file class.util.php.

531 {
532 return iconv('WINDOWS-1252', 'UTF-8//IGNORE', $data);
533 }

Referenced by convertEncoding().

Here is the caller graph for this function:

◆ deleteFolder()

deleteFolder ( $path)
static

Recursively deletes a directory and all its contents.

Parameters
string$pathThe path of the directory to delete.
Returns
void

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

110 {
111 if (is_dir($path)) {
112 $path = rtrim($path, '/\\') . '/';
113 $files = glob($path . '*', GLOB_MARK);
114
115 if ($files === false) {
116 Log::error("deleteFolder(): Failed to glob path: " . $path);
117
118 return;
119 }
120
121 foreach ($files as $file) {
122 $normalizedFile = rtrim($file, '/\\');
123
124 if (is_link($normalizedFile)) {
125 if (!@unlink($normalizedFile) && !@rmdir($normalizedFile)) {
126 Log::error("deleteFolder(): Failed to unlink symlink: " . $normalizedFile);
127 }
128 } elseif (is_dir($file)) {
129 self::deleteFolder($file);
130 } else {
131 if (!@unlink($normalizedFile)) {
132 Log::error("deleteFolder(): Failed to unlink file: " . $normalizedFile);
133 }
134 }
135 }
136
137 if (!@rmdir($path)) {
138 // Only log error if directory still exists (might have been deleted by recursion)
139 if (is_dir($path)) {
140 Log::error("deleteFolder(): Failed to remove directory: " . $path);
141 }
142 }
143 }
144 }
static error($data, $file=null)
static deleteFolder($path)

References deleteFolder(), and Log\error().

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

Here is the call graph for this function:
Here is the caller graph for this function:

◆ 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 426 of file class.util.php.

427 {
428 $startupLnkPath = Path::getStartupLnkPath();
429
430 // Check if file exists before attempting to delete
431 if (file_exists($startupLnkPath)) {
432 return @unlink($startupLnkPath);
433 }
434
435 // Return true if the file doesn't exist (already disabled)
436 return true;
437 }
static getStartupLnkPath()

References Path\getStartupLnkPath().

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

Here is the call graph for this function:
Here is the caller graph for this function:

◆ 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 404 of file class.util.php.

405 {
407
408 $shortcutPath = Path::getStartupLnkPath();
409 if (!$shortcutPath) {
410 return false;
411 }
412
413 $targetPath = Path::getExeFilePath();
414 $workingDir = Path::getRootPath();
415 $description = APP_TITLE . ' ' . $bearsamppCore->getAppVersion();
416 $iconPath = Path::getIconsPath() . '/app.ico';
417
418 return Win32Native::createShortcut($shortcutPath, $targetPath, $workingDir, $description, $iconPath);
419 }
global $bearsamppRoot
static getExeFilePath($aetrayPath=false)
static getRootPath($aetrayPath=false)
static getIconsPath($aetrayPath=false)
static createShortcut($shortcutPath, $targetPath, $workingDir='', $description='', $iconPath='')
const APP_TITLE
Definition root.php:19

References $bearsamppCore, $bearsamppRoot, APP_TITLE, Win32Native\createShortcut(), Path\getExeFilePath(), Path\getIconsPath(), Path\getRootPath(), and Path\getStartupLnkPath().

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

Here is the call graph for this function:
Here is the caller graph for this function:

◆ findFile()

findFile ( $startPath,
$findFile )
static

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 154 of file class.util.php.

155 {
156 $result = false;
157
158 $handle = @opendir($startPath);
159 if (!$handle) {
160 return false;
161 }
162
163 while (false !== ($file = readdir($handle))) {
164 if ($file == '.' || $file == '..') {
165 continue;
166 }
167 if (is_dir($startPath . '/' . $file)) {
168 $result = self::findFile($startPath . '/' . $file, $findFile);
169 if ($result !== false) {
170 break;
171 }
172 } elseif ($file == $findFile) {
173 $result = Path::formatUnixPath($startPath . '/' . $file);
174 break;
175 }
176 }
177
178 closedir($handle);
179
180 return $result;
181 }
static formatUnixPath($path)
static findFile($startPath, $findFile)

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

Referenced by findFile(), and Path\getPowerShellPath().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ 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 851 of file class.util.php.

852 {
853 $result = array();
854
855 $handle = @opendir($startPath);
856 if (!$handle) {
857 return $result;
858 }
859
860 while (false !== ($file = readdir($handle))) {
861 if ($file == '.' || $file == '..') {
862 continue;
863 }
864 if (is_dir($startPath . '/' . $file) && $recursive) {
865 $tmpResults = self::findFiles($startPath . '/' . $file, $includes);
866 foreach ($tmpResults as $tmpResult) {
867 $result[] = $tmpResult;
868 }
869 } elseif (is_file($startPath . '/' . $file)) {
870 foreach ($includes as $include) {
871 if (UtilString::startWith($include, '!')) {
872 $include = ltrim($include, '!');
873 if (UtilString::startWith($file, '.') && !UtilString::endWith($file, $include)) {
874 $result[] = Path::formatUnixPath($startPath . '/' . $file);
875 } elseif ($file != $include) {
876 $result[] = Path::formatUnixPath($startPath . '/' . $file);
877 }
878 } elseif (UtilString::endWith($file, $include) || $file == $include || empty($include)) {
879 $result[] = Path::formatUnixPath($startPath . '/' . $file);
880 }
881 }
882 }
883 }
884
885 closedir($handle);
886
887 return $result;
888 }
static findFiles($startPath, $includes=array(''), $recursive=true)
static startWith($string, $search)
static endWith($string, $search)

References $result, UtilString\endWith(), findFiles(), Path\formatUnixPath(), and UtilString\startWith().

Referenced by findFiles(), and getFilesToScan().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ 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 450 of file class.util.php.

451 {
452 $depth = substr_count(str_replace($initPath, '', $startPath), '/');
453 $result = array();
454
455 $handle = @opendir($startPath);
456 if (!$handle) {
457 return $result;
458 }
459
460 while (false !== ($file = readdir($handle))) {
461 if ($file == '.' || $file == '..') {
462 continue;
463 }
464 if (is_dir($startPath . '/' . $file) && ($initPath == $startPath || $depth <= $maxDepth)) {
465 $tmpResults = self::findRepos($initPath, $startPath . '/' . $file, $checkFile, $maxDepth);
466 foreach ($tmpResults as $tmpResult) {
467 $result[] = $tmpResult;
468 }
469 } elseif (is_file($startPath . '/' . $checkFile) && !in_array($startPath, $result)) {
470 $result[] = Path::formatUnixPath($startPath);
471 }
472 }
473
474 closedir($handle);
475
476 return $result;
477 }
static findRepos($initPath, $startPath, $checkFile, $maxDepth=1)

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

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

Here is the call graph for this function:
Here is the caller graph for this function:

◆ getFilesToScan()

getFilesToScan ( $path = null,
$useCache = true,
$forceRefresh = false )
static

Retrieves a list of files to scan from specified paths or default paths. Implements caching to avoid repeated expensive file system scans.

Parameters
string | null$pathOptional. The path to start scanning from. If null, uses default paths.
bool$useCacheWhether to use cached results (default: true).
bool$forceRefreshForce refresh the cache even if valid (default: false).
Returns
array Returns an array of files found during the scan.

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

619 {
620 // Generate cache key based on path parameter
621 $cacheKey = md5(serialize($path));
622
623 // Try to get from cache if enabled and not forcing refresh
624 if ($useCache && !$forceRefresh) {
625 $cachedResult = Cache::get($cacheKey);
626 if ($cachedResult !== false) {
628 Log::debug('File scan cache HIT (saved expensive scan operation)');
629
630 return $cachedResult;
631 }
632 }
633
635 Log::debug('File scan cache MISS (performing full scan)');
636
637 // Perform the actual scan
638 $startTime = self::getMicrotime();
639 $result = array();
640 $pathsToScan = !empty($path) ? $path : self::getPathsToScan();
641
642 foreach ($pathsToScan as $pathToScan) {
643 $pathStartTime = self::getMicrotime();
644 $findFiles = self::findFiles($pathToScan['path'], $pathToScan['includes'], $pathToScan['recursive']);
645 foreach ($findFiles as $findFile) {
646 $result[] = $findFile;
647 }
648 Log::debug($pathToScan['path'] . ' scanned in ' . round(self::getMicrotime() - $pathStartTime, 3) . 's');
649 }
650
651 $totalTime = round(self::getMicrotime() - $startTime, 3);
652 Log::info('Full file scan completed in ' . $totalTime . 's (' . count($result) . ' files found)');
653
654 // Store in cache if enabled
655 if ($useCache) {
656 Cache::set($cacheKey, $result);
657 }
658
659 return $result;
660 }
static recordHit()
static set($cacheKey, $data)
static recordMiss()
static get($cacheKey)
static info($data, $file=null)
static debug($data, $file=null)
static getMicrotime()
static getPathsToScan()

References $result, Log\debug(), findFiles(), Cache\get(), getMicrotime(), getPathsToScan(), Log\info(), Cache\recordHit(), Cache\recordMiss(), and Cache\set().

Referenced by ActionReload\__construct(), BinPostgresql\initData(), ActionSwitchVersion\processWindow(), and ActionStartup\scanFolders().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ getFolderList()

getFolderList ( $path)
static

Gets the list of folders in the specified path.

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

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

999 {
1000 $result = array();
1001
1002 $handle = @opendir($path);
1003 if (!$handle) {
1004 return false;
1005 }
1006
1007 while (false !== ($file = readdir($handle))) {
1008 $filePath = $path . '/' . $file;
1009 if ($file != '.' && $file != '..' && is_dir($filePath) && $file != 'current') {
1010 $result[] = $file;
1011 }
1012 }
1013
1014 closedir($handle);
1015 natcasesort($result);
1016
1017 return $result;
1018 }

References $result.

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

Here is the caller graph for this function:

◆ 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 898 of file class.util.php.

899 {
900 Log::trace('[VCHK-3] getLatestVersion() START - fetching latest version from: ' . $url);
901
903 if (empty($result)) {
904 Log::error('Cannot retrieve latest github info for: ' . $result . ' RESULT');
905 Log::trace('[VCHK-3] getLatestVersion() EXIT - empty response received');
906
907 return null;
908 }
909
910 $resultArray = json_decode($result, true);
911 if (isset($resultArray['tag_name']) && isset($resultArray['assets'][0]['browser_download_url'])) {
912 $tagName = $resultArray['tag_name'];
913 $downloadUrl = $resultArray['assets'][0]['browser_download_url'];
914 $name = $resultArray['name'];
915 Log::trace('Latest version tag name: ' . $tagName);
916 Log::trace('Download URL: ' . $downloadUrl);
917 Log::trace('Name: ' . $name);
918 Log::trace('[VCHK-3] getLatestVersion() SUCCESS - version found: ' . $tagName);
919
920 return ['version' => $tagName, 'html_url' => $downloadUrl, 'name' => $name];
921 } else {
922 Log::error('Tag name, download URL, or name not found in the response: ' . $result);
923 Log::trace('[VCHK-3] getLatestVersion() EXIT - tag_name/download_url missing in JSON response');
924
925 return null;
926 }
927 }
static getApiJson($url, $verify=true)
static trace($data, $file=null)

References $result, Log\error(), HttpClient\getApiJson(), and Log\trace().

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

Here is the call graph for this function:
Here is the caller graph for this function:

◆ getMicrotime()

getMicrotime ( )
static

Gets the current Unix timestamp with microseconds.

Returns
float Returns the current Unix timestamp combined with microseconds.

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

380 {
381 list($usec, $sec) = explode(' ', microtime());
382
383 return ((float)$usec + (float)$sec);
384 }

Referenced by ActionStartup\__construct(), getFilesToScan(), ActionStartup\installServicesSequential(), ActionStartup\prepareService(), ActionStartup\processWindow(), and ActionStartup\scanFolders().

Here is the caller graph for this function:

◆ 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, PowerShell, 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 687 of file class.util.php.

688 {
689 global $bearsamppRoot, $bearsamppCore, $bearsamppBins, $bearsamppApps, $bearsamppTools;
690 $paths = array();
691
692 // Alias
693 $paths[] = array(
694 'path' => Path::getAliasPath(),
695 'includes' => array(''),
696 'recursive' => false
697 );
698
699 // Vhosts
700 $paths[] = array(
701 'path' => Path::getVhostsPath(),
702 'includes' => array(''),
703 'recursive' => false
704 );
705
706 // OpenSSL
707 $paths[] = array(
708 'path' => Path::getOpenSslPath(),
709 'includes' => array('openssl.cfg'),
710 'recursive' => false
711 );
712
713 // Homepage
714 $paths[] = array(
715 'path' => Path::getResourcesPath() . '/homepage',
716 'includes' => array('alias.conf'),
717 'recursive' => false
718 );
719
720 // Apache
722 foreach ($folderList as $folder) {
723 $paths[] = array(
724 'path' => Path::getModuleRootPath($bearsamppBins->getApache()) . '/' . $folder,
725 'includes' => array('.ini', '.conf'),
726 'recursive' => true
727 );
728 }
729
730 // PHP
732 foreach ($folderList as $folder) {
733 $paths[] = array(
734 'path' => Path::getModuleRootPath($bearsamppBins->getPhp()) . '/' . $folder,
735 'includes' => array('.php', '.bat', '.ini', '.reg', '.inc'),
736 'recursive' => true
737 );
738 }
739
740 // MySQL
742 foreach ($folderList as $folder) {
743 $paths[] = array(
744 'path' => Path::getModuleRootPath($bearsamppBins->getMysql()) . '/' . $folder,
745 'includes' => array('my.ini'),
746 'recursive' => false
747 );
748 }
749
750 // MariaDB
751 $folderList = self::getFolderList(Path::getModuleRootPath($bearsamppBins->getMariadb()));
752 foreach ($folderList as $folder) {
753 $paths[] = array(
754 'path' => Path::getModuleRootPath($bearsamppBins->getMariadb()) . '/' . $folder,
755 'includes' => array('my.ini'),
756 'recursive' => false
757 );
758 // Also scan data directory for my.ini (created during initialization)
759 $dataPath = Path::getModuleRootPath($bearsamppBins->getMariadb()) . '/' . $folder . '/data';
760 if (is_dir($dataPath)) {
761 $paths[] = array(
762 'path' => $dataPath,
763 'includes' => array('my.ini'),
764 'recursive' => false
765 );
766 }
767 }
768
769 // PostgreSQL
770 $folderList = self::getFolderList(Path::getModuleRootPath($bearsamppBins->getPostgresql()));
771 foreach ($folderList as $folder) {
772 $paths[] = array(
773 'path' => Path::getModuleRootPath($bearsamppBins->getPostgresql()) . '/' . $folder,
774 'includes' => array('.conf', '.bat', '.ber'),
775 'recursive' => true
776 );
777 }
778
779 // Node.js
781 foreach ($folderList as $folder) {
782 $paths[] = array(
783 'path' => Path::getModuleRootPath($bearsamppBins->getNodejs()) . '/' . $folder . '/etc',
784 'includes' => array('npmrc'),
785 'recursive' => true
786 );
787 $paths[] = array(
788 'path' => Path::getModuleRootPath($bearsamppBins->getNodejs()) . '/' . $folder . '/node_modules/npm',
789 'includes' => array('npmrc'),
790 'recursive' => false
791 );
792 }
793
794 // Composer
795 $folderList = self::getFolderList(Path::getModuleRootPath($bearsamppTools->getComposer()));
796 foreach ($folderList as $folder) {
797 $paths[] = array(
798 'path' => Path::getModuleRootPath($bearsamppTools->getComposer()) . '/' . $folder,
799 'includes' => array('giscus.json'),
800 'recursive' => false
801 );
802 }
803
804 // PowerShell
805 $folderList = self::getFolderList(Path::getModuleRootPath($bearsamppTools->getPowerShell()));
806 foreach ($folderList as $folder) {
807 $paths[] = array(
808 'path' => Path::getModuleRootPath($bearsamppTools->getPowerShell()) . '/' . $folder,
809 'includes' => array('console.xml', '.ini', '.btm'),
810 'recursive' => true
811 );
812 }
813
814 // Python
815 $folderList = self::getFolderList(Path::getModuleRootPath($bearsamppTools->getPython()));
816 foreach ($folderList as $folder) {
817 $paths[] = array(
818 'path' => Path::getModuleRootPath($bearsamppTools->getPython()) . '/' . $folder . '/bin',
819 'includes' => array('.bat'),
820 'recursive' => false
821 );
822 $paths[] = array(
823 'path' => Path::getModuleRootPath($bearsamppTools->getPython()) . '/' . $folder . '/settings',
824 'includes' => array('winpython.ini'),
825 'recursive' => false
826 );
827 }
828
829 // Ruby
830 $folderList = self::getFolderList(Path::getModuleRootPath($bearsamppTools->getRuby()));
831 foreach ($folderList as $folder) {
832 $paths[] = array(
833 'path' => Path::getModuleRootPath($bearsamppTools->getRuby()) . '/' . $folder . '/bin',
834 'includes' => array('!.dll', '!.exe'),
835 'recursive' => false
836 );
837 }
838
839 return $paths;
840 }
global $bearsamppBins
static getAliasPath($aetrayPath=false)
static getResourcesPath($aetrayPath=false)
static getVhostsPath($aetrayPath=false)
static getOpenSslPath($aetrayPath=false)
static getModuleRootPath($module)
static getFolderList($path)

References $bearsamppBins, $bearsamppCore, $bearsamppRoot, Path\getAliasPath(), getFolderList(), Path\getModuleRootPath(), Path\getOpenSslPath(), Path\getResourcesPath(), and Path\getVhostsPath().

Referenced by getFilesToScan().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ getVersionList()

getVersionList ( $path)
static

Gets the list of version directories in the specified path. Returns version suffixes by stripping the common prefix (basename of path) if present.

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

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

346 {
347 $result = array();
348
349 $handle = @opendir($path);
350 if (!$handle) {
351 return false;
352 }
353
354 $prefix = basename($path);
355
356 while (false !== ($file = readdir($handle))) {
357 $filePath = $path . '/' . $file;
358 if ($file != '.' && $file != '..' && is_dir($filePath) && $file != 'current') {
359 if (strpos($file, $prefix) === 0) {
360 $version = substr($file, strlen($prefix));
361 } else {
362 $version = $file;
363 }
364 $result[] = $version;
365 }
366 }
367
368 closedir($handle);
369 natcasesort($result);
370
371 return $result;
372 }

References $result.

Referenced by Module\getVersionList().

Here is the caller graph for this function:

◆ humanFileSize()

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

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

Uses PHP's native human_readable_size() when available. Falls back to manual conversion when a specific unit is requested or when the native function is unavailable.

Parameters
int$sizeThe file size in bytes.
string$unitOptional forced unit ('GB', 'MB', 'KB', or '').
Returns
string The formatted file size.

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

941 : string
942 {
943 // Forced unit mode
944 if ($unit !== '') {
945 return match ($unit) {
946 'GB' => number_format($size / (1 << 30), 2) . 'GB',
947 'MB' => number_format($size / (1 << 20), 2) . 'MB',
948 'KB' => number_format($size / (1 << 10), 2) . 'KB',
949 default => number_format($size) . ' bytes',
950 };
951 }
952
953 // Native PHP auto-selection when the function is available
954 if (function_exists('human_readable_size')) {
955 return human_readable_size($size, precision: 2);
956 }
957
958 // Manual fallback
959 $units = array('B', 'KB', 'MB', 'GB', 'TB');
960 $power = $size > 0 ? (int)floor(log($size, 1024)) : 0;
961 $power = min($power, count($units) - 1);
962
963 return number_format($size / (1024 ** $power), 2) . $units[$power];
964 }

◆ 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 486 of file class.util.php.

487 {
488 $type = pathinfo($path, PATHINFO_EXTENSION);
489 $data = file_get_contents($path);
490
491 return 'data:image/' . $type . ';base64,' . base64_encode($data);
492 }

◆ 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 971 of file class.util.php.

972 {
973 global $bearsamppRegistry;
974 $processor = $bearsamppRegistry->getProcessorRegKey();
975
976 return UtilString::contains($processor, 'x86');
977 }
static contains($string, $search)

References UtilString\contains().

Here is the call graph for this function:

◆ isAdmin()

isAdmin ( )
static

Checks if the current process is running with administrator/elevated privileges. This is essential for operations that require admin rights, such as installing Windows services.

Returns
bool True if running as administrator, false otherwise.

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

215 {
216 // Only applicable on Windows
217 if (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN') {
218 // On non-Windows systems, check if running as root
219 if (function_exists('posix_geteuid')) {
220 return posix_geteuid() === 0;
221 }
222
223 // If we can't determine on non-Windows, assume true to avoid blocking
224 return true;
225 }
226
227 // Method 1: Try using shell_exec with 'net session' command
228 // This command only succeeds when run with admin privileges
229 $output = CommandRunner::shellExec('net session 2>&1');
230 if ($output !== null) {
231 // Check for access denied errors
232 if (stripos($output, 'Access is denied') !== false ||
233 stripos($output, 'System error 5') !== false ||
234 stripos($output, 'Zugriff verweigert') !== false) { // German
235 // Explicitly denied - not admin
236 return false;
237 }
238
239 // If we got output without errors, we likely have admin rights
240 if (stripos($output, 'There are no entries') !== false ||
241 stripos($output, 'These workstations') !== false ||
242 preg_match('/\\\\\\\\/', $output)) {
243 return true;
244 }
245 }
246
247 // Method 2: Check using whoami command (Windows Vista and later)
248 $output = CommandRunner::shellExec('whoami /groups 2>&1');
249 if ($output !== null && !empty($output)) {
250 // Look for the Administrators group or High Mandatory Level
251 if (stripos($output, 'S-1-16-12288') !== false || // High Mandatory Level
252 stripos($output, 'S-1-5-32-544') !== false) { // Administrators group
253 return true;
254 }
255
256 // If we got output but no admin indicators, we're not admin
257 if (stripos($output, 'S-1-16-8192') !== false) { // Medium Mandatory Level (not admin)
258 return false;
259 }
260 }
261
262 // Method 3: Try to write to a system directory
263 // This is a fallback method that checks if we can write to Windows directory
264 $testFile = getenv('SystemRoot') . '\\Temp\\bearsampp_admin_test_' . uniqid() . '.tmp';
265 $result = @file_put_contents($testFile, 'test');
266 if ($result !== false) {
267 @unlink($testFile);
268
269 return true;
270 }
271
272 // If all methods fail or indicate no admin, return false
273 return false;
274 }
static shellExec(string $command)

References $result, and CommandRunner\shellExec().

Here is the call graph for this function:

◆ 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 392 of file class.util.php.

393 {
395
396 return $lnk ? file_exists($lnk) : false;
397 }

References Path\getStartupLnkPath().

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

Here is the call graph for this function:
Here is the caller graph for this function:

◆ 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 986 of file class.util.php.

987 {
988 return filter_var($domainName, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) !== false;
989 }

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

Here is the caller graph for this function:

◆ 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 190 of file class.util.php.

191 {
192 return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)
193 || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
194 }

◆ 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 203 of file class.util.php.

204 {
205 return is_numeric($port) && ($port > 0 && $port <= 65535);
206 }
$port

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().

Here is the caller graph for this function:

◆ openFileContent()

openFileContent ( $caption,
$content )
static

Opens the given content in a temporary file using the editor configured in bearsampp.conf.

Parameters
string$captionThe caption/title for the temporary file.
string$contentThe content to write to the temporary file.
Returns
void

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

1030 {
1031 global $bearsamppWinbinder, $bearsamppConfig;
1032
1033 $caption = preg_replace('/[<>:"\/\\\\|?*\x00-\x1F]|\.$/', '', trim($caption));
1034 $tmpFile = Path::getTmpPath() . '/' . $caption . '.txt';
1035 file_put_contents($tmpFile, $content);
1036
1037 // Open the file with the editor configured in bearsampp.conf
1038 $editor = $bearsamppConfig->getNotepad();
1039 if ($editor == null || trim($editor) == '') {
1040 $editor = 'notepad.exe';
1041 }
1042
1043 $editor = Path::findExecutable($editor);
1044 if ($editor === false) {
1045 $editor = getenv('SystemRoot') . '\System32\notepad.exe';
1046 }
1047
1048 $bearsamppWinbinder->exec($editor, '"' . $tmpFile . '"', false, true, true);
1049 }
static findExecutable($name)
global $bearsamppConfig
Definition homepage.php:46

References $bearsamppConfig, Path\findExecutable(), and Path\getTmpPath().

Referenced by ActionDebugBase\__construct().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ 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.
Returns
void

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

286 {
287 self::replaceInFile($path, array(
288 '/^define\‍((.*?)' . $var . '(.*?),/' => 'define(\'' . $var . '\', ' . (is_int($value) ? $value : '\'' . $value . '\'') . ');'
289 ));
290 }
static replaceInFile($path, $replaceList)

References replaceInFile().

Here is the call graph for this function:

◆ 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.
Returns
void

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

301 {
302 if (file_exists($path)) {
303 $lines = file($path);
304 $fp = fopen($path, 'w');
305 foreach ($lines as $nb => $line) {
306 $replaceDone = false;
307 foreach ($replaceList as $regex => $replace) {
308 if (preg_match($regex, $line, $matches)) {
309 $currentReplace = $replace;
310 $countParams = preg_match_all('/{{(\d+)}}/', $currentReplace, $paramsMatches);
311 if ($countParams > 0 && $countParams <= count($matches)) {
312 foreach ($paramsMatches[1] as $paramsMatch) {
313 $currentReplace = str_replace('{{' . $paramsMatch . '}}', $matches[$paramsMatch], $currentReplace);
314 }
315 }
316 Log::trace('Replace in file ' . $path . ' :');
317 Log::trace('## line_num: ' . trim($nb));
318 Log::trace('## old: ' . trim($line));
319 Log::trace('## new: ' . trim($currentReplace));
320
321 // Preserve original line ending if present in $line
322 $ending = (preg_match("/\r\n$/", $line)) ? "\r\n" : (preg_match("/\n$/", $line) ? "\n" : "");
323 fwrite($fp, rtrim($currentReplace) . $ending);
324
325 $replaceDone = true;
326 break;
327 }
328 }
329 if (!$replaceDone) {
330 fwrite($fp, $line);
331 }
332 }
333 fclose($fp);
334 }
335 }

References Log\trace().

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

Here is the call graph for this function:
Here is the caller graph for this function:

◆ startLoading()

startLoading ( )
static

Initiates a loading process using external components.

Returns
void

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

541 {
542 global $bearsamppCore, $bearsamppWinbinder;
543
544 Log::trace('startLoading() called');
545 Log::trace('PHP executable: ' . Path::getPhpExe());
546 Log::trace('Root file: ' . Core::isRoot_FILE);
547 Log::trace('Action: ' . Action::LOADING);
548
549 Log::trace('Executing command: ' . Path::getPhpExe() . ' ' . Core::isRoot_FILE . ' ' . Action::LOADING);
550
551 $result = $bearsamppWinbinder->exec(Path::getPhpExe(), [Core::isRoot_FILE, Action::LOADING], true, false);
552 Log::trace('exec() returned: ' . var_export($result, true));
553
554 Log::trace('startLoading() completed');
555 }
const LOADING
const isRoot_FILE
static getPhpExe($aetrayPath=false)

References $bearsamppCore, $result, Path\getPhpExe(), Core\isRoot_FILE, Action\LOADING, and Log\trace().

Referenced by ActionCheckVersion\__construct(), ActionEnable\__construct(), ActionLaunchStartup\__construct(), ActionManualRestart\__construct(), ActionRefreshRepos\__construct(), ActionReload\__construct(), ActionService\__construct(), ActionSwitchOnline\__construct(), and ActionStartup\processWindow().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ stopLoading()

stopLoading ( )
static

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

Returns
void

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

563 {
564 global $bearsamppCore;
565 if (file_exists($bearsamppCore->getLoadingPid())) {
566 $pids = file($bearsamppCore->getLoadingPid());
567 foreach ($pids as $pid) {
568 Win32Ps::kill($pid);
569 }
570 @unlink($bearsamppCore->getLoadingPid());
571 }
572
573 // Clean up status file
575 }
static clearLoadingText()
static kill($pid)

References $bearsamppCore, clearLoadingText(), and Win32Ps\kill().

Referenced by ActionCheckVersion\__construct(), ActionEnable\__construct(), ActionLaunchStartup\__construct(), ActionManualRestart\__construct(), ActionRefreshRepos\__construct(), ActionReload\__construct(), ActionService\__construct(), ActionSwitchOnline\__construct(), ActionCheckVersion\showVersionOkMessageBox(), and ActionCheckVersion\showVersionUpdateWindow().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ updateLoadingText()

updateLoadingText ( $text)
static

Updates the loading screen text (if loading screen is active) This allows dynamic updates to show which service is being processed

Parameters
string$textThe text to display on the loading screen
Returns
void

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

586 {
587 global $bearsamppCore;
588
589 $statusFile = Path::getTmpPath() . '/loading_status.txt';
590 file_put_contents($statusFile, json_encode(['text' => $text]));
591 }

References $bearsamppCore, and Path\getTmpPath().

Referenced by ActionChangePort\processWindow(), ActionService\restart(), ActionService\start(), and ActionService\stop().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ 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 518 of file class.util.php.

519 {
520 return iconv('UTF-8', 'WINDOWS-1252//IGNORE', $data);
521 }

Referenced by ActionReload\__construct(), convertEncoding(), and ActionChangePort\processWindow().

Here is the caller graph for this function:

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