Bearsampp 2026.3.26
API documentation
Loading...
Searching...
No Matches
Batch Class Reference

Public Member Functions

 __construct ()

Static Public Member Functions

static createSymlink ($src, $dest)
static exec ($basename, $content, $timeout=true, $catchOutput=true, $standalone=false, $silent=true, $rebuild=true)
static execStandalone ($basename, $content, $silent=true)
static exitApp ($restart=false)
static findExeByPid ($pid)
static getOsInfo ()
static getPearVersion ()
static getProcessUsingPort ($port)
static initializeMariadb ($path)
static initializeMysql ($path)
static initializePostgresql ($path)
static installPostgresqlService ()
static refreshEnvVars ()
static removeSymlink ($link)
static restartApp ()
static setServiceDescription ($serviceName, $desc)
static setServiceDisplayName ($serviceName, $displayName)
static setServiceStartType ($serviceName, $startType)
static uninstallPostgresqlService ()

Data Fields

const CATCH_OUTPUT_FALSE = 'bearsamppCatchOutputFalse'
const END_PROCESS_STR = 'FINISHED!'

Static Private Member Functions

static getTmpFile ($ext, $customName=null)
static writeLog ($log)

Detailed Description

Class Batch

This class provides various utility functions for managing processes, services, and environment variables within the Bearsampp application. It includes methods for finding executables by process ID, checking which process is using a specific port, exiting and restarting the application, managing services, and executing batch scripts.

Key functionalities include:

  • Finding executables by process ID.
  • Checking which process is using a specific port.
  • Exiting and restarting the application.
  • Managing services (installing, uninstalling, setting descriptions, etc.).
  • Executing batch scripts with optional output capture and timeout.
  • Refreshing environment variables.
  • Creating and removing symbolic links.
  • Retrieving operating system information.

The class utilizes global variables to access application settings and paths, and logs operations for debugging purposes.

Definition at line 30 of file class.batch.php.

Constructor & Destructor Documentation

◆ __construct()

__construct ( )

Constructor for the Batch class.

Definition at line 38 of file class.batch.php.

39 {
40 }

Member Function Documentation

◆ createSymlink()

createSymlink ( $src,
$dest )
static

Creates a symbolic link.

Parameters
string$srcThe source path.
string$destThe destination path.

Definition at line 268 of file class.batch.php.

269 {
270 global $bearsamppCore;
271 $src = Util::formatWindowsPath($src);
272 $dest = Util::formatWindowsPath($dest);
273 self::exec('createSymlink', '"' . $bearsamppCore->getLnExe() . '" --absolute --symbolic --traditional --1023safe "' . $src . '" ' . '"' . $dest . '"', true, false);
274 }
global $bearsamppCore
static exec($basename, $content, $timeout=true, $catchOutput=true, $standalone=false, $silent=true, $rebuild=true)
static formatWindowsPath($path)

References $bearsamppCore, exec(), and Util\formatWindowsPath().

Referenced by Module\createSymlink().

◆ exec()

exec ( $basename,
$content,
$timeout = true,
$catchOutput = true,
$standalone = false,
$silent = true,
$rebuild = true )
static

Executes a batch script.

Parameters
string$basenameThe base name for the script and result files.
string$contentThe content of the batch script.
int | bool$timeoutThe timeout for the script execution in seconds, or true for default timeout, or false for no timeout.
bool$catchOutputWhether to capture the output of the script.
bool$standaloneWhether the script is standalone.
bool$silentWhether to execute the script silently.
bool$rebuildWhether to rebuild the result array.
Returns
array|false The result of the execution, or false on failure.

Definition at line 432 of file class.batch.php.

433 {
434 global $bearsamppConfig, $bearsamppWinbinder;
435 $result = false;
436
437 $resultFile = self::getTmpFile('.tmp', $basename);
438 $scriptPath = self::getTmpFile('.bat', $basename);
439 $checkFile = self::getTmpFile('.tmp', $basename);
440
441 // Redirect output
442 if ($catchOutput) {
443 $content .= '> "' . $resultFile . '"' . (!Util::endWith($content, '2') ? ' 2>&1' : '');
444 }
445
446 // Header
447 $header = '@ECHO OFF' . PHP_EOL . PHP_EOL;
448
449 // Footer
450 $footer = PHP_EOL . (!$standalone ? PHP_EOL . 'ECHO ' . self::END_PROCESS_STR . ' > "' . $checkFile . '"' : '');
451
452 // Process
453 file_put_contents($scriptPath, $header . $content . $footer);
454 $bearsamppWinbinder->exec($scriptPath, null, $silent);
455
456 if (!$standalone) {
457 $timeout = is_numeric($timeout) ? $timeout : ($timeout === true ? $bearsamppConfig->getScriptsTimeout() : false);
458 $maxtime = time() + $timeout;
459 $noTimeout = $timeout === false;
460 while ($result === false || empty($result)) {
461 if (file_exists($checkFile)) {
462 $check = file($checkFile);
463 if (!empty($check) && trim($check[0]) == self::END_PROCESS_STR) {
464 if ($catchOutput && file_exists($resultFile)) {
465 $result = file($resultFile);
466 } else {
467 $result = self::CATCH_OUTPUT_FALSE;
468 }
469 }
470 }
471 if ($maxtime < time() && !$noTimeout) {
472 break;
473 }
474 }
475 }
476
477 self::writeLog('Exec:');
478 self::writeLog('-> basename: ' . $basename);
479 self::writeLog('-> content: ' . str_replace(PHP_EOL, ' \\\\ ', $content));
480 self::writeLog('-> checkFile: ' . $checkFile);
481 self::writeLog('-> resultFile: ' . $resultFile);
482 self::writeLog('-> scriptPath: ' . $scriptPath);
483
484 if ($result !== false && !empty($result) && is_array($result)) {
485 if ($rebuild) {
486 $rebuildResult = array();
487 foreach ($result as $row) {
488 $row = trim($row);
489 if (!empty($row)) {
490 $rebuildResult[] = $row;
491 }
492 }
493 $result = $rebuildResult;
494 }
495 self::writeLog('-> result: ' . substr(implode(' \\\\ ', $result), 0, 2048));
496 } else {
497 self::writeLog('-> result: N/A');
498 }
499
500 return $result;
501 }
$result
static writeLog($log)
static getTmpFile($ext, $customName=null)
static endWith($string, $search)
global $bearsamppConfig
Definition homepage.php:41

References $bearsamppConfig, $result, Util\endWith(), getTmpFile(), and writeLog().

Referenced by OpenSsl\createCrt(), createSymlink(), Nssm\exec(), execStandalone(), findExeByPid(), BinApache\getCmdLineOutput(), BinMariadb\getCmdLineOutput(), BinMysql\getCmdLineOutput(), BinPostgresql\getCmdLineOutput(), getOsInfo(), getPearVersion(), getProcessUsingPort(), BinMariadb\initData(), initializeMariadb(), initializeMysql(), initializePostgresql(), installPostgresqlService(), removeSymlink(), setServiceDescription(), setServiceDisplayName(), setServiceStartType(), and uninstallPostgresqlService().

◆ execStandalone()

execStandalone ( $basename,
$content,
$silent = true )
static

Executes a standalone batch script.

Parameters
string$basenameThe base name for the script and result files.
string$contentThe content of the batch script.
bool$silentWhether to execute the script silently.
Returns
array|false The result of the execution, or false on failure.

Definition at line 415 of file class.batch.php.

416 {
417 return self::exec($basename, $content, false, false, true, $silent);
418 }

References exec().

Referenced by exitApp(), and refreshEnvVars().

◆ exitApp()

exitApp ( $restart = false)
static

Exits the application, optionally restarting it.

Parameters
bool$restartWhether to restart the application after exiting.

Definition at line 120 of file class.batch.php.

121 {
123
124 $content = 'PING 1.1.1.1 -n 1 -w 2000 > nul' . PHP_EOL;
125 $content .= '"' . $bearsamppRoot->getExeFilePath() . '" -quit -id={bearsampp}' . PHP_EOL;
126 if ($restart) {
127 $basename = 'restartApp';
128 Util::logInfo('Restart App');
129 $content .= '"' . $bearsamppCore->getPhpExe() . '" "' . Core::isRoot_FILE . '" "' . Action::RESTART . '"' . PHP_EOL;
130 } else {
131 $basename = 'exitApp';
132 Util::logInfo('Exit App');
133 }
134
136 self::execStandalone($basename, $content);
137 }
global $bearsamppRoot
const RESTART
static execStandalone($basename, $content, $silent=true)
const isRoot_FILE
static logInfo($data, $file=null)
static killBins($refreshProcs=false)

References $bearsamppCore, $bearsamppRoot, execStandalone(), Core\isRoot_FILE, Win32Ps\killBins(), Util\logInfo(), and Action\RESTART.

Referenced by ActionExec\__construct(), and restartApp().

◆ findExeByPid()

findExeByPid ( $pid)
static

Finds the executable name by its process ID (PID).

Parameters
int$pidThe process ID to search for.
Returns
string|false The executable name if found, false otherwise.

Definition at line 59 of file class.batch.php.

60 {
61 // Sanitize PID to prevent command injection
62 $sanitizedPid = Util::sanitizePID($pid);
63 if ($sanitizedPid === false) {
64 self::writeLog('Invalid PID provided to findExeByPid: ' . var_export($pid, true));
65 return false;
66 }
67
68 $result = self::exec('findExeByPid', 'TASKLIST /FO CSV /NH /FI "PID eq ' . $sanitizedPid . '"', 5);
69 if ($result !== false) {
70 $expResult = explode('","', $result[0]);
71 if (is_array($expResult) && count($expResult) > 2 && isset($expResult[0]) && !empty($expResult[0])) {
72 return substr($expResult[0], 1);
73 }
74 }
75
76 return false;
77 }
static sanitizePID($pid)

References $result, exec(), Util\sanitizePID(), and writeLog().

Referenced by getProcessUsingPort().

◆ getOsInfo()

getOsInfo ( )
static

Gets the operating system information.

Returns
string The operating system information.

Definition at line 322 of file class.batch.php.

323 {
324 $result = self::exec('getOsInfo', 'ver', 5);
325 if (is_array($result)) {
326 foreach ($result as $row) {
327 if (Util::startWith($row, 'Microsoft')) {
328 return trim($row);
329 }
330 }
331 }
332 return '';
333 }
static startWith($string, $search)

References $result, exec(), and Util\startWith().

Referenced by ActionStartup\sysInfos().

◆ getPearVersion()

getPearVersion ( )
static

Gets the version of PEAR installed.

Returns
string|null The PEAR version if found, null otherwise.

Definition at line 152 of file class.batch.php.

153 {
154 global $bearsamppBins;
155
156 $result = self::exec('getPearVersion', 'CMD /C "' . $bearsamppBins->getPhp()->getPearExe() . '" -V', 5);
157 if (is_array($result)) {
158 foreach ($result as $row) {
159 if (Util::startWith($row, 'PEAR Version:')) {
160 $expResult = explode(' ', $row);
161 if (count($expResult) == 3) {
162 return trim($expResult[2]);
163 }
164 }
165 }
166 }
167
168 return null;
169 }
global $bearsamppBins

References $bearsamppBins, $result, exec(), and Util\startWith().

Referenced by BinPhp\getPearVersion().

◆ getProcessUsingPort()

getProcessUsingPort ( $port)
static

Gets the process using a specific port.

Parameters
int$portThe port number to check.
Returns
string|int|null The executable name and PID if found, the PID if executable not found, or null if no process is using the port.

Definition at line 85 of file class.batch.php.

86 {
87 // Sanitize port to prevent command injection
88 $sanitizedPort = Util::sanitizePort($port);
89 if ($sanitizedPort === false) {
90 self::writeLog('Invalid port provided to getProcessUsingPort: ' . var_export($port, true));
91 return null;
92 }
93
94 $result = self::exec('getProcessUsingPort', 'NETSTAT -aon', 4);
95 if ($result !== false) {
96 foreach ($result as $row) {
97 if (!Util::startWith($row, 'TCP')) {
98 continue;
99 }
100 $rowExp = explode(' ', preg_replace('/\s+/', ' ', $row));
101 if (count($rowExp) == 5 && Util::endWith($rowExp[1], ':' . $sanitizedPort) && $rowExp[3] == 'LISTENING') {
102 $pid = intval($rowExp[4]);
103 $exe = self::findExeByPid($pid);
104 if ($exe !== false) {
105 return $exe . ' (' . $pid . ')';
106 }
107 return $pid;
108 }
109 }
110 }
111
112 return null;
113 }
$port
static findExeByPid($pid)
static sanitizePort($port)

References $port, $result, Util\endWith(), exec(), findExeByPid(), Util\sanitizePort(), Util\startWith(), and writeLog().

Referenced by Util\isPortInUse().

◆ getTmpFile()

getTmpFile ( $ext,
$customName = null )
staticprivate

Gets a temporary file path with a specified extension and optional custom name.

Parameters
string$extThe file extension.
string | null$customNameAn optional custom name for the file.
Returns
string The temporary file path.

Definition at line 510 of file class.batch.php.

511 {
512 global $bearsamppCore;
513 return Util::formatWindowsPath($bearsamppCore->getTmpPath() . '/' . (!empty($customName) ? $customName . '-' : '') . Util::random() . $ext);
514 }
static random($length=32, $withNumeric=true)

References $bearsamppCore, Util\formatWindowsPath(), and Util\random().

Referenced by exec().

◆ initializeMariadb()

initializeMariadb ( $path)
static

Initializes MariaDB using a specified path.

Parameters
string$pathThe path to the MariaDB initialization script.

Definition at line 253 of file class.batch.php.

254 {
255 if (!file_exists($path . '/init.bat')) {
256 Util::logWarning($path . '/init.bat does not exist');
257 return;
258 }
259 self::exec('initializeMariadb', 'CMD /C "' . $path . '/init.bat"', 60);
260 }
static logWarning($data, $file=null)

References exec(), and Util\logWarning().

Referenced by BinMariadb\initData().

◆ initializeMysql()

initializeMysql ( $path)
static

Initializes MySQL using a specified path.

Parameters
string$pathThe path to the MySQL initialization script.

Definition at line 185 of file class.batch.php.

186 {
187 if (!file_exists($path . '/init.bat')) {
188 Util::logWarning($path . '/init.bat does not exist');
189 return;
190 }
191 self::exec('initializeMysql', 'CMD /C "' . $path . '/init.bat"', 60);
192 }

References exec(), and Util\logWarning().

Referenced by BinMysql\initData().

◆ initializePostgresql()

initializePostgresql ( $path)
static

Initializes PostgreSQL using a specified path.

Parameters
string$pathThe path to the PostgreSQL initialization script.

Definition at line 239 of file class.batch.php.

240 {
241 if (!file_exists($path . '/init.bat')) {
242 Util::logWarning($path . '/init.bat does not exist');
243 return;
244 }
245 self::exec('initializePostgresql', 'CMD /C "' . $path . '/init.bat"', 15);
246 }

References exec(), and Util\logWarning().

Referenced by BinPostgresql\initData().

◆ installPostgresqlService()

installPostgresqlService ( )
static

Installs the PostgreSQL service.

Returns
bool True if the service was installed successfully, false otherwise.

Definition at line 199 of file class.batch.php.

200 {
201 global $bearsamppBins;
202
203 $cmd = '"' . Util::formatWindowsPath($bearsamppBins->getPostgresql()->getCtlExe()) . '" register -N "' . BinPostgresql::SERVICE_NAME . '"';
204 $cmd .= ' -U "LocalSystem" -D "' . Util::formatWindowsPath($bearsamppBins->getPostgresql()->getSymlinkPath()) . '\\data"';
205 $cmd .= ' -l "' . Util::formatWindowsPath($bearsamppBins->getPostgresql()->getErrorLog()) . '" -w';
206 self::exec('installPostgresqlService', $cmd, true, false);
207
208 if (!$bearsamppBins->getPostgresql()->getService()->isInstalled()) {
209 return false;
210 }
211
212 self::setServiceDisplayName(BinPostgresql::SERVICE_NAME, $bearsamppBins->getPostgresql()->getService()->getDisplayName());
213 self::setServiceDescription(BinPostgresql::SERVICE_NAME, $bearsamppBins->getPostgresql()->getService()->getDisplayName());
215
216 return true;
217 }
static setServiceDisplayName($serviceName, $displayName)
static setServiceStartType($serviceName, $startType)
static setServiceDescription($serviceName, $desc)

References $bearsamppBins, exec(), Util\formatWindowsPath(), BinPostgresql\SERVICE_NAME, setServiceDescription(), setServiceDisplayName(), and setServiceStartType().

Referenced by Win32Service\create().

◆ refreshEnvVars()

refreshEnvVars ( )
static

Refreshes the environment variables.

Definition at line 174 of file class.batch.php.

175 {
177 self::execStandalone('refreshEnvVars', '"' . $bearsamppCore->getSetEnvExe() . '" -a ' . Registry::APP_PATH_REG_ENTRY . ' "' . Util::formatWindowsPath($bearsamppRoot->getRootPath()) . '"');
178 }
const APP_PATH_REG_ENTRY

References $bearsamppCore, $bearsamppRoot, Registry\APP_PATH_REG_ENTRY, execStandalone(), and Util\formatWindowsPath().

Referenced by Registry\setValue().

◆ removeSymlink()

removeSymlink ( $link)
static

Removes a symbolic link.

Parameters
string$linkThe path to the symbolic link.
Returns
bool True if the symlink was removed successfully, false otherwise.

Definition at line 282 of file class.batch.php.

283 {
284 if (!file_exists($link)) {
285 self::writeLog('-> removeSymlink: Link does not exist: ' . $link);
286 return true; // If the link doesn't exist, nothing to do
287 }
288
289 // Check if it's a directory symlink
290 $isDirectory = is_dir($link);
291 $formattedLink = Util::formatWindowsPath($link);
292
293 try {
294 // Use different commands based on whether it's a directory or file symlink
295 if ($isDirectory) {
296 // For directory symlinks
297 self::exec('removeSymlink', 'rmdir /Q "' . $formattedLink . '"', true, false);
298 } else {
299 // For file symlinks
300 self::exec('removeSymlink', 'del /F /Q "' . $formattedLink . '"', true, false);
301 }
302
303 // Check if removal was successful
304 if (file_exists($link)) {
305 self::writeLog('-> removeSymlink: Failed to remove symlink: ' . $link);
306 return false;
307 }
308
309 self::writeLog('-> removeSymlink: Successfully removed symlink: ' . $link);
310 return true;
311 } catch (Exception $e) {
312 self::writeLog('-> removeSymlink: Exception: ' . $e->getMessage());
313 return false;
314 }
315 }

References exec(), Util\formatWindowsPath(), and writeLog().

Referenced by Module\createSymlink().

◆ restartApp()

restartApp ( )
static

Restarts the application.

Definition at line 142 of file class.batch.php.

143 {
144 self::exitApp(true);
145 }
static exitApp($restart=false)

References exitApp().

Referenced by ActionExec\__construct().

◆ setServiceDescription()

setServiceDescription ( $serviceName,
$desc )
static

Sets the description of a service.

Parameters
string$serviceNameThe name of the service.
string$descThe description to set.

Definition at line 364 of file class.batch.php.

365 {
366 // Sanitize service name to prevent command injection
367 $sanitizedName = Util::sanitizeServiceName($serviceName);
368 if ($sanitizedName === false) {
369 self::writeLog('Invalid service name provided to setServiceDescription: ' . $serviceName);
370 return;
371 }
372
373 // Remove quotes and dangerous characters from description
374 $sanitizedDesc = str_replace('"', '', $desc);
375 $sanitizedDesc = preg_replace('/[<>|&^]/', '', $sanitizedDesc);
376
377 $cmd = 'sc description ' . $sanitizedName . ' "' . $sanitizedDesc . '"';
378 self::exec('setServiceDescription', $cmd, true, false);
379 }
static sanitizeServiceName($serviceName)

References exec(), Util\sanitizeServiceName(), and writeLog().

Referenced by installPostgresqlService().

◆ setServiceDisplayName()

setServiceDisplayName ( $serviceName,
$displayName )
static

Sets the display name of a service.

Parameters
string$serviceNameThe name of the service.
string$displayNameThe display name to set.

Definition at line 341 of file class.batch.php.

342 {
343 // Sanitize service name to prevent command injection
344 $sanitizedName = Util::sanitizeServiceName($serviceName);
345 if ($sanitizedName === false) {
346 self::writeLog('Invalid service name provided to setServiceDisplayName: ' . $serviceName);
347 return;
348 }
349
350 // Remove quotes and dangerous characters from display name
351 $sanitizedDisplayName = str_replace('"', '', $displayName);
352 $sanitizedDisplayName = preg_replace('/[<>|&^]/', '', $sanitizedDisplayName);
353
354 $cmd = 'sc config ' . $sanitizedName . ' DisplayName= "' . $sanitizedDisplayName . '"';
355 self::exec('setServiceDisplayName', $cmd, true, false);
356 }

References exec(), Util\sanitizeServiceName(), and writeLog().

Referenced by installPostgresqlService().

◆ setServiceStartType()

setServiceStartType ( $serviceName,
$startType )
static

Sets the start type of a service.

Parameters
string$serviceNameThe name of the service.
string$startTypeThe start type to set (e.g., "auto", "demand").

Definition at line 387 of file class.batch.php.

388 {
389 // Sanitize service name to prevent command injection
390 $sanitizedName = Util::sanitizeServiceName($serviceName);
391 if ($sanitizedName === false) {
392 self::writeLog('Invalid service name provided to setServiceStartType: ' . $serviceName);
393 return;
394 }
395
396 // Validate start type (only allow known values)
397 $allowedStartTypes = ['auto', 'demand', 'disabled', 'delayed-auto'];
398 if (!in_array(strtolower($startType), $allowedStartTypes, true)) {
399 self::writeLog('Invalid start type provided: ' . $startType);
400 return;
401 }
402
403 $cmd = 'sc config ' . $sanitizedName . ' start= ' . strtolower($startType);
404 self::exec('setServiceStartType', $cmd, true, false);
405 }

References exec(), Util\sanitizeServiceName(), and writeLog().

Referenced by installPostgresqlService().

◆ uninstallPostgresqlService()

uninstallPostgresqlService ( )
static

Uninstalls the PostgreSQL service.

Returns
bool True if the service was uninstalled successfully, false otherwise.

Definition at line 224 of file class.batch.php.

225 {
226 global $bearsamppBins;
227
228 $cmd = '"' . Util::formatWindowsPath($bearsamppBins->getPostgresql()->getCtlExe()) . '" unregister -N "' . BinPostgresql::SERVICE_NAME . '"';
229 $cmd .= ' -l "' . Util::formatWindowsPath($bearsamppBins->getPostgresql()->getErrorLog()) . '" -w';
230 self::exec('uninstallPostgresqlService', $cmd, true, false);
231 return !$bearsamppBins->getPostgresql()->getService()->isInstalled();
232 }

References $bearsamppBins, exec(), Util\formatWindowsPath(), and BinPostgresql\SERVICE_NAME.

Referenced by Win32Service\delete().

◆ writeLog()

writeLog ( $log)
staticprivate

Writes a log entry to the batch log file.

Parameters
string$logThe log message to write.

Definition at line 47 of file class.batch.php.

48 {
49 global $bearsamppRoot;
50 Util::logDebug($log, $bearsamppRoot->getBatchLogFilePath());
51 }
static logDebug($data, $file=null)

References $bearsamppRoot, and Util\logDebug().

Referenced by exec(), findExeByPid(), getProcessUsingPort(), removeSymlink(), setServiceDescription(), setServiceDisplayName(), and setServiceStartType().

Field Documentation

◆ CATCH_OUTPUT_FALSE

const CATCH_OUTPUT_FALSE = 'bearsamppCatchOutputFalse'

Definition at line 33 of file class.batch.php.

◆ END_PROCESS_STR

const END_PROCESS_STR = 'FINISHED!'

Definition at line 32 of file class.batch.php.


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