OTS Restarter script

restart.sh with console logs with timestamp and binary file copy (for GDB)

#!/bin/bash
ulimit -c unlimited
while true; do

 cp kasteria bins/kasteria_`date '+%Y-%m-%d_%H-%M'`_`crc32 kasteria`
 stdbuf -o 0 ./kasteria 2>&1 | ts '%Y-%m-%d_%H-%M-%.S' | tee -a 'console/console_'`date '+%Y-%m-%d'`'.log';

 echo START SLEEP FOR 3 SECONDS, PRESS CTRL+C TO TURN OFF RESTARTER
 sleep 3
 echo END SLEEP

done

Simple PHP router

Apache .htaccess (redirect all requests to not existing files/directories to index.php):

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]

PHP router file. Check if route is on list of available routes and include file by name of route. Some parts of route can be variables: ‘user/$name’. Variables can have default values: ‘users/$order=id’, default value can be empty string: ‘user/$name=’

<?php
var_dump((string)$_SERVER['REDIRECT_URL']);
$urlParts = explode('/', trim((string)$_SERVER['REDIRECT_URL'], '/'));

$routes = [
    'login',
    'logout',
    'user/$name',
    'users/list/$type=level/$page=2/$vocation=all',
];

function openRoute($pathParts, $vars)
{
    $file = 'pages/' . implode('_', $pathParts) . '.php';

    ob_start();
    extract($vars);
    $main_content = '';
    include($file);
    $main_content .= ob_get_clean();

    return $main_content;
}

$routeFound = false;

foreach ($routes as $route) {
    $routeParts = explode('/', $route);
    $vars = [];
    $pathParts = [];

    if (count($routeParts) >= count($urlParts)) {
        foreach ($routeParts as $partId => $routePart) {
            if ($routePart[0] === '$') {
                $optionalVar = strpos($routePart, '=') !== false;

                if ($optionalVar) {
                    list($varName, $defaultValue) = explode('=', $routePart);
                    $varName = substr($varName, 1);
                } else {
                    $varName = substr($routePart, 1);
                }

                if (isset($urlParts[$partId])) {
                    $vars[$varName] = $urlParts[$partId];
                } elseif ($optionalVar) {
                    $vars[$varName] = $defaultValue;
                } else {
                    continue 2;
                }
            } elseif (isset($urlParts[$partId]) && $routePart === $urlParts[$partId]) {
                $pathParts[] = $routePart;
            } else {
                continue 2;
            }
        }

        var_dump('found: ', $route, $vars, $pathParts);
        $main_content = openRoute($pathParts, $vars);
        $routeFound = true;

        break;
    }
}

if (!$routeFound) {
    http_response_code(404);
    echo '404 Not found';
    exit;
}

Autowalk/cavebot for OTClient

Someone asked me about script that will make character run to given position and after reaching it run to another. I made it for free, so I decided to publish it as it may be interesting for others.

It’s not ready-to-run module, but I think it’s very close. For tests I pasted parts of it to ‘battle’ module and it worked.

This code requires ‘BOT_PROTECTION’ disabled in OTClient.

local walkEvent = nil
local positionsList = {
    { x = 32608, y = 32131, z = 7 },
    { x = 32601, y = 32131, z = 7 },
    { x = 32601, y = 32138, z = 7 },
    { x = 32608, y = 32138, z = 7 },
}

local isAttacking = 0
local isFollowing = 0
local currentTargetPositionId = 1

local autowalkTargetPosition = positionsList[currentTargetPositionId]

function init()
    connect(LocalPlayer, {
        onPositionChange = onCreaturePositionChange
    })

    connect(g_game, {
        onAttackingCreatureChange = onAttack,
        onFollowingCreatureChange = onFollow,
        onDisappear = onCreatureDisappear
    })
end

function terminate()
    disconnect(LocalPlayer, {
        onPositionChange = onCreaturePositionChange
    })

    disconnect(g_game, {
        onAttackingCreatureChange = onAttack,
        onFollowingCreatureChange = onFollow,
        onDisappear = onCreatureDisappear
    })
end

function walkToTarget()
    if not g_game.isOnline() then
        walkEvent = scheduleEvent(walkToTarget, 500)
        return
    end

    if g_game.getLocalPlayer():getStepTicksLeft() > 0 then
        -- wait until walk animation finish
        walkEvent = scheduleEvent(walkToTarget, g_game.getLocalPlayer():getStepTicksLeft())
        return
    end

    if isAttacking or isFollowing or not autowalkTargetPosition then
        -- do not walk with selected attack/follow target or when there is no target position
        walkEvent = scheduleEvent(walkToTarget, 100)
        return
    end

    -- fast search path on minimap (known tiles)
    steps, result = g_map.findPath(g_game.getLocalPlayer():getPosition(), autowalkTargetPosition, 5000, 0)
    if result == PathFindResults.Ok then
        g_game.walk(steps[1], true)
    elseif result == PathFindResults.Position then
        -- on target position
        currentTargetPositionId = currentTargetPositionId + 1
        autowalkTargetPosition = positionsList[(currentTargetPositionId % #positionsList) + 1]
    else
        -- slow search path on minimap, if not found, start 'scanning' map
        steps, result = g_map.findPath(g_game.getLocalPlayer():getPosition(), autowalkTargetPosition, 25000, 1)
        if result == PathFindResults.Ok then
            g_game.walk(steps[1], true)
        end
    end

    -- limit steps to 10 per second (100 ms between steps)
    walkEvent = scheduleEvent(walkToTarget, math.max(100, g_game.getLocalPlayer():getStepTicksLeft()))
end

function onCreaturePositionChange(creature, newPos, oldPos)
    if not walkEvent then
        -- start automoving 1 second after logging into game
        walkEvent = scheduleEvent(walkToTarget, 1000)
    end
end

function onAttack(creature)
    isAttacking = creature and creature:getId() or 0
end

function onFollow(creature)
    isFollowing = creature and creature:getId() or 0
end

function onCreatureDisappear(creature)
    if isAttacking == creature:getId() then
        isAttacking = 0
    end
    if isFollowing == creature:getId() then
        isFollowing = 0
    end
end

Fast configure multiple PHP versions php.ini

Script to configure PHP variables for development environment.

<?php

$phpDir = '/etc/php';

$backupPath = __DIR__ . DIRECTORY_SEPARATOR . 'config_backup.' . date('Y-m-d_H-i-s') . '.zip';
echo 'Backup config file: ' . $backupPath . PHP_EOL;
system('zip -r ' . $backupPath . ' ' . $phpDir . ' > /dev/null');
chmod($backupPath, 0777);

$values = [
	'upload_max_filesize' => '256M',
	'post_max_size' => '256M',
	'max_file_uploads' => 100,
	'memory_limit' => '1024M',
	'max_execution_time' => 15,
	'error_reporting' => 'E_ALL & ~E_DEPRECATED & ~E_STRICT',
	'display_errors' => 'Off',
	'log_errors' => 'On',
	'xdebug.remote_enable' => '1',
];
setPhpConfigValues($values, $phpDir, ['5.6', '7.0', '7.1', '7.2', '7.3'], ['apache2', 'fpm']);

$values = [
	'memory_limit' => -1,
	'max_execution_time' => 0,
	'error_reporting' => 'E_ALL & ~E_DEPRECATED & ~E_STRICT',
	'display_errors' => 'On',
	'log_errors' => 'Off',
];
setPhpConfigValues($values, $phpDir, ['5.6', '7.0', '7.1', '7.2', '7.3'], ['cli']);

system('systemctl restart apache2');
foreach(['5.6', '7.0', '7.1', '7.2', '7.3'] as $version) {
	system('systemctl restart php' . $version . '-fpm');
}

function setPhpConfigValues($values, $phpDir, $phpVersions, $phpTypes)
{
	foreach($phpVersions as $phpVersion) {
		foreach($phpTypes as $phpType) {
			$filePath = $phpDir . DIRECTORY_SEPARATOR . $phpVersion . DIRECTORY_SEPARATOR . $phpType . DIRECTORY_SEPARATOR . 'php.ini';
			if (file_exists($filePath)) {
				if (is_readable($filePath)) {
					if (is_writable($filePath)) {
						$lines = file($filePath);
						echo 'FILE: ' . $filePath . PHP_EOL;
						foreach($values as $searchKey => $newValue) {
							foreach($lines as $line => $text) {
								if (substr_count($text, '=') > 0) {
									list($lineKey, $lineValue) = explode('=', $text, 2);

									if (strpos($lineKey, $searchKey) !== false) {
										if (trim($lineValue) != $newValue) {
											echo 'Change key "' . $searchKey . '" value from "' . trim($lineValue) . '" to "' . $newValue . '"' . PHP_EOL;
											$lines[$line] = $searchKey . ' = ' . $newValue . PHP_EOL;
										}
										continue 2;
									}
								}
							}

							echo 'Add key "' . $searchKey . '" with value"' . $newValue . '"' . PHP_EOL;
							$lines[] = $searchKey . ' = ' . $newValue . PHP_EOL;
						}
						file_put_contents($filePath, implode('', $lines));
						echo 'SAVE FILE: ' . $filePath . PHP_EOL;
					} else {
						echo 'Config file not writable: ' . $filePath . PHP_EOL;
					}
				} else {
					echo 'Config file not readable: ' . $filePath . PHP_EOL;
				}
			} else {
				echo 'Config file not found: ' . $filePath . PHP_EOL;
			}
		}
	}
}

PHP function isIpInRanges($ip, $ranges)

Function that checks if given IP is within one of given IP ranges.

<?php
/**
 * Checks if given IP is in one of IP ranges
 * @param string|int $ip in format x.x.x.x or unsigned int
 * @param string[] $ranges in format IP/NETMASK
 * @return bool
 */
function isIpInRanges($ip, $ranges)
{
    if (is_numeric($ip))
        $ip_dec = $ip;
    else
        $ip_dec = ip2long($ip);

    foreach ($ranges as $range) {
        if (strpos($range, '/') === false)
            $range .= '/32';

        list($range, $netmask) = explode('/', $range, 2);
        $x = explode('.', $range);
        while (count($x) < 4) $x[] = '0';
        $range = sprintf("%u.%u.%u.%u", $x[0], $x[1], $x[2], $x[3]);
        $range_dec = ip2long($range);

        $wildcard_dec = pow(2, (32 - $netmask)) - 1;
        $netmask_dec = ~$wildcard_dec;

        if (($ip_dec & $netmask_dec) == ($range_dec & $netmask_dec))
            return true;
    }

    return false;
}

// TESTS
var_dump(isIpInRanges('127.0.0.1', [])); // false
var_dump(isIpInRanges('127.0.0.1', ['127.0.0.1'])); // true
var_dump(isIpInRanges('127.0.0.1', ['127.0.0.0/32'])); // false
var_dump(isIpInRanges('127.0.0.1', ['127.0.0.0/24'])); // true
var_dump(isIpInRanges('1.1.1.1', ['1.0.0.0/16', '1.1.0.0/16'])); // true
var_dump(isIpInRanges('192.168.11.11', ['192.168.11/24'])); // true
var_dump(isIpInRanges('192.168.11.11', ['192.168.11/22'])); // true
var_dump(isIpInRanges('192.168.11.11', ['192.168/29'])); // false

var_dump(isIpInRanges(3000000000, ['178.208.94.0'])); // true
var_dump(isIpInRanges(3000000000, ['178/8'])); // true