Bearsampp 2025.8.29
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 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 240 of file class.batch.php.

241 {
242 global $bearsamppCore;
243 $src = Util::formatWindowsPath($src);
244 $dest = Util::formatWindowsPath($dest);
245 self::exec('createSymlink', '"' . $bearsamppCore->getLnExe() . '" --absolute --symbolic --traditional --1023safe "' . $src . '" ' . '"' . $dest . '"', true, false);
246 }
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 368 of file class.batch.php.

369 {
370 global $bearsamppConfig, $bearsamppWinbinder;
371 $result = false;
372
373 $resultFile = self::getTmpFile('.tmp', $basename);
374 $scriptPath = self::getTmpFile('.bat', $basename);
375 $checkFile = self::getTmpFile('.tmp', $basename);
376
377 // Redirect output
378 if ($catchOutput) {
379 $content .= '> "' . $resultFile . '"' . (!Util::endWith($content, '2') ? ' 2>&1' : '');
380 }
381
382 // Header
383 $header = '@ECHO OFF' . PHP_EOL . PHP_EOL;
384
385 // Footer
386 $footer = PHP_EOL . (!$standalone ? PHP_EOL . 'ECHO ' . self::END_PROCESS_STR . ' > "' . $checkFile . '"' : '');
387
388 // Process
389 file_put_contents($scriptPath, $header . $content . $footer);
390 $bearsamppWinbinder->exec($scriptPath, null, $silent);
391
392 if (!$standalone) {
393 $timeout = is_numeric($timeout) ? $timeout : ($timeout === true ? $bearsamppConfig->getScriptsTimeout() : false);
394 $maxtime = time() + $timeout;
395 $noTimeout = $timeout === false;
396 while ($result === false || empty($result)) {
397 if (file_exists($checkFile)) {
398 $check = file($checkFile);
399 if (!empty($check) && trim($check[0]) == self::END_PROCESS_STR) {
400 if ($catchOutput && file_exists($resultFile)) {
401 $result = file($resultFile);
402 } else {
403 $result = self::CATCH_OUTPUT_FALSE;
404 }
405 }
406 }
407 if ($maxtime < time() && !$noTimeout) {
408 break;
409 }
410 }
411 }
412
413 self::writeLog('Exec:');
414 self::writeLog('-> basename: ' . $basename);
415 self::writeLog('-> content: ' . str_replace(PHP_EOL, ' \\\\ ', $content));
416 self::writeLog('-> checkFile: ' . $checkFile);
417 self::writeLog('-> resultFile: ' . $resultFile);
418 self::writeLog('-> scriptPath: ' . $scriptPath);
419
420 if ($result !== false && !empty($result) && is_array($result)) {
421 if ($rebuild) {
422 $rebuildResult = array();
423 foreach ($result as $row) {
424 $row = trim($row);
425 if (!empty($row)) {
426 $rebuildResult[] = $row;
427 }
428 }
429 $result = $rebuildResult;
430 }
431 self::writeLog('-> result: ' . substr(implode(' \\\\ ', $result), 0, 2048));
432 } else {
433 self::writeLog('-> result: N/A');
434 }
435
436 return $result;
437 }
$result
static writeLog($log)
static getTmpFile($ext, $customName=null)
static endWith($string, $search)
global $bearsamppConfig
Definition homepage.php:27

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(), 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 351 of file class.batch.php.

352 {
353 return self::exec($basename, $content, false, false, true, $silent);
354 }

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 106 of file class.batch.php.

107 {
109
110 $content = 'PING 1.1.1.1 -n 1 -w 2000 > nul' . PHP_EOL;
111 $content .= '"' . $bearsamppRoot->getExeFilePath() . '" -quit -id={bearsampp}' . PHP_EOL;
112 if ($restart) {
113 $basename = 'restartApp';
114 Util::logInfo('Restart App');
115 $content .= '"' . $bearsamppCore->getPhpExe() . '" "' . Core::isRoot_FILE . '" "' . Action::RESTART . '"' . PHP_EOL;
116 } else {
117 $basename = 'exitApp';
118 Util::logInfo('Exit App');
119 }
120
122 self::execStandalone($basename, $content);
123 }
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 $result = self::exec('findExeByPid', 'TASKLIST /FO CSV /NH /FI "PID eq ' . $pid . '"', 5);
62 if ($result !== false) {
63 $expResult = explode('","', $result[0]);
64 if (is_array($expResult) && count($expResult) > 2 && isset($expResult[0]) && !empty($expResult[0])) {
65 return substr($expResult[0], 1);
66 }
67 }
68
69 return false;
70 }

References $result, and exec().

Referenced by getProcessUsingPort().

◆ getOsInfo()

getOsInfo ( )
static

Gets the operating system information.

Returns
string The operating system information.

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

295 {
296 $result = self::exec('getOsInfo', 'ver', 5);
297 if (is_array($result)) {
298 foreach ($result as $row) {
299 if (Util::startWith($row, 'Microsoft')) {
300 return trim($row);
301 }
302 }
303 }
304 return '';
305 }
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 138 of file class.batch.php.

139 {
140 global $bearsamppBins;
141
142 $result = self::exec('getPearVersion', 'CMD /C "' . $bearsamppBins->getPhp()->getPearExe() . '" -V', 5);
143 if (is_array($result)) {
144 foreach ($result as $row) {
145 if (Util::startWith($row, 'PEAR Version:')) {
146 $expResult = explode(' ', $row);
147 if (count($expResult) == 3) {
148 return trim($expResult[2]);
149 }
150 }
151 }
152 }
153
154 return null;
155 }
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 78 of file class.batch.php.

79 {
80 $result = self::exec('getProcessUsingPort', 'NETSTAT -aon', 4);
81 if ($result !== false) {
82 foreach ($result as $row) {
83 if (!Util::startWith($row, 'TCP')) {
84 continue;
85 }
86 $rowExp = explode(' ', preg_replace('/\s+/', ' ', $row));
87 if (count($rowExp) == 5 && Util::endWith($rowExp[1], ':' . $port) && $rowExp[3] == 'LISTENING') {
88 $pid = intval($rowExp[4]);
89 $exe = self::findExeByPid($pid);
90 if ($exe !== false) {
91 return $exe . ' (' . $pid . ')';
92 }
93 return $pid;
94 }
95 }
96 }
97
98 return null;
99 }
$port
static findExeByPid($pid)

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

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 446 of file class.batch.php.

447 {
448 global $bearsamppCore;
449 return Util::formatWindowsPath($bearsamppCore->getTmpPath() . '/' . (!empty($customName) ? $customName . '-' : '') . Util::random() . $ext);
450 }
static random($length=32, $withNumeric=true)

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

Referenced by exec().

◆ initializeMysql()

initializeMysql ( $path)
static

Initializes MySQL using a specified path.

Parameters
string$pathThe path to the MySQL initialization script.

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

172 {
173 if (!file_exists($path . '/init.bat')) {
174 Util::logWarning($path . '/init.bat does not exist');
175 return;
176 }
177 self::exec('initializeMysql', 'CMD /C "' . $path . '/init.bat"', 60);
178 }
static logWarning($data, $file=null)

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 225 of file class.batch.php.

226 {
227 if (!file_exists($path . '/init.bat')) {
228 Util::logWarning($path . '/init.bat does not exist');
229 return;
230 }
231 self::exec('initializePostgresql', 'CMD /C "' . $path . '/init.bat"', 15);
232 }

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 185 of file class.batch.php.

186 {
187 global $bearsamppBins;
188
189 $cmd = '"' . Util::formatWindowsPath($bearsamppBins->getPostgresql()->getCtlExe()) . '" register -N "' . BinPostgresql::SERVICE_NAME . '"';
190 $cmd .= ' -U "LocalSystem" -D "' . Util::formatWindowsPath($bearsamppBins->getPostgresql()->getSymlinkPath()) . '\\data"';
191 $cmd .= ' -l "' . Util::formatWindowsPath($bearsamppBins->getPostgresql()->getErrorLog()) . '" -w';
192 self::exec('installPostgresqlService', $cmd, true, false);
193
194 if (!$bearsamppBins->getPostgresql()->getService()->isInstalled()) {
195 return false;
196 }
197
198 self::setServiceDisplayName(BinPostgresql::SERVICE_NAME, $bearsamppBins->getPostgresql()->getService()->getDisplayName());
199 self::setServiceDescription(BinPostgresql::SERVICE_NAME, $bearsamppBins->getPostgresql()->getService()->getDisplayName());
201
202 return true;
203 }
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 160 of file class.batch.php.

161 {
163 self::execStandalone('refreshEnvVars', '"' . $bearsamppCore->getSetEnvExe() . '" -a ' . Registry::APP_PATH_REG_ENTRY . ' "' . Util::formatWindowsPath($bearsamppRoot->getRootPath()) . '"');
164 }
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 254 of file class.batch.php.

255 {
256 if (!file_exists($link)) {
257 self::writeLog('-> removeSymlink: Link does not exist: ' . $link);
258 return true; // If the link doesn't exist, nothing to do
259 }
260
261 // Check if it's a directory symlink
262 $isDirectory = is_dir($link);
263 $formattedLink = Util::formatWindowsPath($link);
264
265 try {
266 // Use different commands based on whether it's a directory or file symlink
267 if ($isDirectory) {
268 // For directory symlinks
269 self::exec('removeSymlink', 'rmdir /Q "' . $formattedLink . '"', true, false);
270 } else {
271 // For file symlinks
272 self::exec('removeSymlink', 'del /F /Q "' . $formattedLink . '"', true, false);
273 }
274
275 // Check if removal was successful
276 if (file_exists($link)) {
277 self::writeLog('-> removeSymlink: Failed to remove symlink: ' . $link);
278 return false;
279 }
280
281 self::writeLog('-> removeSymlink: Successfully removed symlink: ' . $link);
282 return true;
283 } catch (Exception $e) {
284 self::writeLog('-> removeSymlink: Exception: ' . $e->getMessage());
285 return false;
286 }
287 }

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

Referenced by Module\createSymlink().

◆ restartApp()

restartApp ( )
static

Restarts the application.

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

129 {
130 self::exitApp(true);
131 }
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 325 of file class.batch.php.

326 {
327 $cmd = 'sc description ' . $serviceName . ' "' . $desc . '"';
328 self::exec('setServiceDescription', $cmd, true, false);
329 }

References exec().

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 313 of file class.batch.php.

314 {
315 $cmd = 'sc config ' . $serviceName . ' DisplayName= "' . $displayName . '"';
316 self::exec('setServiceDisplayName', $cmd, true, false);
317 }

References exec().

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 337 of file class.batch.php.

338 {
339 $cmd = 'sc config ' . $serviceName . ' start= ' . $startType;
340 self::exec('setServiceStartType', $cmd, true, false);
341 }

References exec().

Referenced by installPostgresqlService().

◆ uninstallPostgresqlService()

uninstallPostgresqlService ( )
static

Uninstalls the PostgreSQL service.

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

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

211 {
212 global $bearsamppBins;
213
214 $cmd = '"' . Util::formatWindowsPath($bearsamppBins->getPostgresql()->getCtlExe()) . '" unregister -N "' . BinPostgresql::SERVICE_NAME . '"';
215 $cmd .= ' -l "' . Util::formatWindowsPath($bearsamppBins->getPostgresql()->getErrorLog()) . '" -w';
216 self::exec('uninstallPostgresqlService', $cmd, true, false);
217 return !$bearsamppBins->getPostgresql()->getService()->isInstalled();
218 }

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(), and removeSymlink().

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: