### Docker Deployment (Bash) Source: https://context7.com/shadowss/travianz/llms.txt Provides commands for cloning the TravianZ repository, setting up environment variables via a .env file, and starting the Docker containers. Includes instructions for accessing the installation wizard and database connection details. ```bash # Clone and setup git clone https://github.com/Shadowss/TravianZ.git cd TravianZ # Configure environment cp .env.example .env # Edit .env with your database credentials: # MYSQL_ROOT_PASSWORD=yourStrongRootPassword # MYSQL_DATABASE=travian # MYSQL_USER=travianz # MYSQL_PASSWORD=yourStrongPassword # Start containers docker-compose up -d # Access installation wizard # http://localhost:8080/install # Database settings for installer: # Hostname: db ``` -------------------------------- ### Docker Deployment Source: https://context7.com/shadowss/travianz/llms.txt Instructions for deploying TravianZ using Docker, including cloning the repository, configuring environment variables, and starting the containers. ```APIDOC ## Docker Deployment ### Description This section provides the necessary commands to deploy and run the TravianZ game server using Docker. ### Steps 1. **Clone the repository**: ```bash git clone https://github.com/Shadowss/TravianZ.git cd TravianZ ``` 2. **Configure environment variables**: Copy the example environment file and edit it with your database credentials. ```bash cp .env.example .env # Edit .env file: # MYSQL_ROOT_PASSWORD=yourStrongRootPassword # MYSQL_DATABASE=travian # MYSQL_USER=travianz # MYSQL_PASSWORD=yourStrongPassword ``` 3. **Start the Docker containers**: This command downloads the necessary images and starts the services in detached mode. ```bash docker-compose up -d ``` 4. **Access the installation wizard**: Open your web browser and navigate to the following URL: `http://localhost:8080/install` **Database settings for the installer:** - Hostname: `db` ### Notes - Ensure Docker and Docker Compose are installed on your system. - The default port is 8080. If this port is in use, you may need to adjust the `docker-compose.yml` file or use port mapping. ``` -------------------------------- ### Apply Custom PHP Configuration (YAML) Source: https://github.com/shadowss/travianz/blob/master/DOCKER_README.md Applies custom PHP settings by mounting a configuration file into the web service container. This allows for fine-tuning PHP parameters like memory limits, upload sizes, and execution times. The custom configuration is specified in 'php-custom.ini' and mounted via volumes. ```yaml services: web: volumes: - ./php-custom.ini:/usr/local/etc/php/conf.d/custom.ini ``` -------------------------------- ### Tune MySQL Configuration (YAML) Source: https://github.com/shadowss/travianz/blob/master/DOCKER_README.md Optimizes MySQL performance by setting various configuration parameters. This includes default authentication plugin, SQL mode, maximum connections, and buffer/query cache sizes. The configuration is applied via the 'command' argument in the 'db' service definition. ```yaml services: db: command: > --default-authentication-plugin=mysql_native_password --sql_mode="" --max_connections=200 --innodb_buffer_pool_size=512M --query_cache_size=32M --query_cache_limit=2M ``` -------------------------------- ### Optimize Database Queries for Resource and Storage Checks Source: https://github.com/shadowss/travianz/blob/master/todo.txt These SQL queries are intended to be optimized for performance by executing them directly on the database rather than through PHP. They check for villages with resources exceeding storage capacity, villages with low storage or crop capacity, and villages with negative resource values. ```sql SELECT * FROM s1_vdata WHERE wood > maxstore OR clay > maxstore OR iron > maxstore OR crop > maxcrop ``` ```sql SELECT * FROM s1_odata WHERE maxstore < 800 OR maxcrop < 800 ``` ```sql SELECT * FROM s1_vdata WHERE wood < 0 OR clay < 0 OR iron < 0 OR crop < 0 ``` ```sql SELECT * FROM `s1_fdata` ``` -------------------------------- ### Building System Management in PHP Source: https://context7.com/shadowss/travianz/llms.txt Handles construction queues, building requirements, and upgrade processing. Validates resource availability and prerequisites. Requires GameEngine/Building.php. ```php canProcess($buildingTypeId, $slotId); // Check resource requirements (returns 4 if resources available) $result = $building->checkResource($buildingTypeId, $slotId); if ($result == 4) { echo "Resources available for construction"; } // Check if building is at max level $currentLevel = $village->resarray['f' . $slotId]; $inQueue = $building->isLoop($slotId) + $building->isCurrent($slotId); if ($building->isMax($buildingTypeId, $slotId, $inQueue)) { echo "Building is at maximum level"; } // Check building requirements if ($building->meetRequirement($buildingTypeId)) { echo "All prerequisites met"; } // Process build request from URL parameters // URL: build.php?a=25&c=abc123 (slot 25, checker token) $building->procBuild($_GET); // Access build queue foreach ($building->buildArray as $job) { echo "Building: " . $job['type']; echo "Level: " . $job['level']; echo "Finish Time: " . $job['timestamp']; } // Check World Wonder upgrade eligibility if ($building->allowWwUpgrade()) { echo "WW upgrade allowed"; } ?> ``` -------------------------------- ### Configure Container Resource Limits (YAML) Source: https://github.com/shadowss/travianz/blob/master/DOCKER_README.md Sets resource constraints (CPU and memory) for containers in a production environment. This helps manage resource allocation and prevent performance issues. It is configured within the 'deploy.resources.limits' section of a service definition. ```yaml services: web: deploy: resources: limits: cpus: '1.0' memory: 1G ``` -------------------------------- ### Implement 'Select All' Functionality via JavaScript Source: https://github.com/shadowss/travianz/blob/master/todo.txt This task involves implementing a JavaScript solution to enable the 'select all' button to select all checkboxes without requiring a page reload. This will improve the user interface and interaction efficiency. ```javascript // Example placeholder for JavaScript functionality // Actual implementation would involve DOM manipulation to select checkboxes. ``` -------------------------------- ### Battle System Simulation in PHP Source: https://context7.com/shadowss/travianz/llms.txt Simulates combat, including attack calculations, defense bonuses, and hero combat. Processes battle data via POST or real-time movement data. Requires GameEngine/Battle.php. ```php 1, // Attacker tribe: 1=Romans, 2=Teutons, 3=Gauls 'a1_1' => 100, 'a1_2' => 50, // Unit counts (type 1-10 per tribe) 'a2_v1' => true, // Defender tribe 1 present 'a2_1' => 200, 'a2_2' => 100, // Defender units 'wall1' => 10, // Wall level for tribe 1 'palast' => 5, // Palace/Residence level 'h_off_bonus' => 10, // Hero offensive bonus (0-20) 'h_def_bonus' => 5, // Hero defensive bonus (0-20) ]; // Process battle simulation $battle->procSim($postData); // Result available in $_POST['result'] // [0] = attacker losses, [1] = defender losses, [2-6] = additional data // [7] = new wall level, [8] = original wall level // Real battle processing uses movement and attack tables // Movement types: 3 = outgoing attack, 4 = returning attack $movements = $database->getMovement(3, $villageId, 0); foreach ($movements as $movement) { // Attack types: 1 = scout, 2 = reinforce, 3 = normal, 4 = raid $attackType = $movement['attack_type']; $targetVillage = $movement['to']; $arrivalTime = $movement['endtime']; } ?> ``` -------------------------------- ### Account Management API Source: https://context7.com/shadowss/travianz/llms.txt Handles user registration, email activation, login, and account deletion. All operations are typically triggered via POST requests with a specific 'ft' field. ```APIDOC ## Account Registration and Authentication ### Description This section details the API endpoints for managing player accounts, including registration, activation, login, and logout. ### Method POST ### Endpoint `/` (Root endpoint, operations determined by POST data) ### Parameters #### Request Body - **ft** (string) - Required - Operation type. Examples: - `a1`: Register new account - `a2`: Activate account - `a4`: Login - **name** (string) - Required for registration - Username. - **pw** (string) - Required for registration and login - Password. - **email** (string) - Required for registration - User's email address. - **vid** (integer) - Required for registration - Tribe ID (1: Romans, 2: Teutons, 3: Gauls). - **kid** (integer) - Required for registration - Starting tile ID. - **agb** (integer) - Required for registration - Indicates acceptance of terms (1 for accepted). - **invited** (string) - Optional for registration - Referral code. - **id** (string) - Required for activation (`ft=a2`) - Activation code. - **user** (string) - Required for login (`ft=a4`) - Username. ### Request Example (Registration) ```json { "ft": "a1", "name": "newplayer", "pw": "securepassword", "email": "player@example.com", "vid": 1, "kid": 12345, "agb": 1, "invited": "" } ``` ### Request Example (Login) ```json { "ft": "a4", "user": "playername", "pw": "password" } ``` ### Response #### Success Response (200) - **message** (string) - Success message (e.g., 'Account created successfully', 'Logged in successfully'). #### Error Response (400/401/409) - **error** (string) - Error message (e.g., 'Username already exists', 'Invalid credentials'). ### Notes - Passwords are hashed using bcrypt. - Account activation can also be triggered via URL parameter `?code=xxx`. ``` -------------------------------- ### Update TravianZ Project (Bash) Source: https://github.com/shadowss/travianz/blob/master/DOCKER_README.md Updates the TravianZ project to the latest version using Git and Docker Compose. This involves pulling the latest code, stopping existing containers, and then restarting them with the updated code and potentially rebuilt images. ```bash git pull origin main docker-compose down docker-compose up -d --build ``` -------------------------------- ### Admin Panel Functions API Source: https://context7.com/shadowss/travianz/llms.txt Provides server management capabilities including user management, resource manipulation, and server configuration. ```APIDOC ## Admin Panel Functions ### Description This section outlines the administrative API functions for managing users, resources, server settings, and medals. ### Method Various (primarily internal calls to the `database` object) ### Endpoint `/Admin/admin.php` (Access point for admin functionalities) ### Functions #### User Management - **Edit User Field** - **Description**: Updates a specific field for a given user. - **Method**: Internal function call. - **Usage**: `$database->updateUserField($userId, $fieldName, $value, $log = 1)` - **Example**: `$database->updateUserField(123, "gold", 1000, 1);` - **Example**: `$database->updateUserField(123, "access", 2, 1); // 2=admin - **Ban/Unban User** - **Description**: Changes the access level of a user to ban or unban. - **Method**: Internal function call. - **Usage**: `$database->updateUserField($userId, "access", $status, 1)` - **Example (Ban)**: `$database->updateUserField(123, "access", BANNED, 1);` - **Example (Unban)**: `$database->updateUserField(123, "access", PLAYER, 1);` #### Resource Management - **Add Resources to Village** - **Description**: Adds specified amounts of resources to a village. - **Method**: Internal function call. - **Usage**: `$database->updateResource($villageId, [$resource1, $resource2, ...], [$amount1, $amount2, ...])` - **Example**: `$database->updateResource(456, ["wood", "clay", "iron", "crop"], [10000, 10000, 10000, 10000]);` #### Server Configuration - **Description**: Server settings are defined as constants, typically in `GameEngine/config.php` after installation. - **Examples**: - `define('SERVER_NAME', 'My TravianZ Server');` - `define('WORLD_MAX', 400);` - `define('INCREASE_SPEED', 3);` - `define('AUTH_EMAIL', false);` #### Medal Management - **Add Alliance Medal** - **Description**: Awards medals to alliances. - **Method**: Internal function call. - **Usage**: `$database->addclimbalialiancemedal($allianceId, $week, $category, $points);` - **Usage**: `$database->addclialiancemedal($allianceId, $week, $category, $points, $rank);` #### Server Maintenance - **Reset Player Gold** - **Description**: Sets the gold of all users to zero. - **Method**: Direct SQL query. - **Usage**: `$database->query("UPDATE " . TB_PREFIX . "users SET gold=0");` - **Clear Build Queues** - **Description**: Removes expired build queue entries. - **Method**: Direct SQL query. - **Usage**: `$database->query("DELETE FROM " . TB_PREFIX . "bdata WHERE timestamp < " . time());` ### Notes - Access to `/Admin/admin.php` is restricted to users with administrator privileges. - Direct SQL queries should be used with extreme caution. ``` -------------------------------- ### Account Registration and Authentication (PHP) Source: https://context7.com/shadowss/travianz/llms.txt Handles user registration, email activation, login validation, and account deletion. Uses POST requests for operations like registration ('a1'), activation ('a2'), and login ('a4'). Passwords are securely hashed using bcrypt. ```php 'a1', 'name' => 'newplayer', 'pw' => 'securepassword', 'email' => 'player@example.com', 'vid' => 1, // Tribe: 1=Romans, 2=Teutons, 3=Gauls 'kid' => 12345, // Starting tile ID 'agb' => 1, // Terms accepted 'invited' => '', // Referral code (optional) ]; // Activation: ft=a2 or via URL parameter ?code=xxx $_POST = ['ft' => 'a2', 'id' => 'activationcode']; // Or: $_GET = ['code' => 'activationcode']; // Login: ft=a4 $_POST = [ 'ft' => 'a4', 'user' => 'playername', 'pw' => 'password', ]; // Logout is triggered when accessing logout.php while logged in // Password is hashed with bcrypt $hashedPassword = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]); // Validation example $isValid = password_verify($inputPassword, $storedHash); ?> ``` -------------------------------- ### Manage User Sessions in PHP Source: https://context7.com/shadowss/travianz/llms.txt Handles user authentication, login/logout, and maintains user state. It validates credentials, manages session tokens, and enforces access control. Requires including Session.php. ```php logged_in) { echo "Welcome, " . $session->username; echo "User ID: " . $session->uid; echo "Tribe: " . $session->tribe; // 1=Romans, 2=Teutons, 3=Gauls echo "Gold: " . $session->gold; echo "Alliance: " . $session->alliance; // Check user access level if ($session->isAdmin) { echo "User has admin privileges"; } // Check Plus account status if ($session->plus) { echo "Plus account is active"; } } // Login a user programmatically $session->Login("username"); // Logout current user $session->Logout(); ``` -------------------------------- ### Database Operations in PHP Source: https://context7.com/shadowss/travianz/llms.txt Manages all database interactions for user, village, troop, and alliance data. Implements caching for performance. Requires the Database.php include. ```php getUserArray("username", 0); // Get by username $userData = $database->getUserArray(123, 1); // Get by user ID // Get specific user fields $fields = $database->getUserFields("username", "id, email, tribe", 1, true); // Check if user exists if ($database->uExist("username")) { echo "User exists"; } // Village operations $villageData = $database->getVillage($villageId); $resourceLevels = $database->getResourceLevel($villageId); $coordinates = $database->getCoor($villageId); // Get all villages for a user $villageIds = $database->getVillagesID($userId); $villageProfiles = $database->getProfileVillages($userId, 5); // Troop operations $units = $database->getUnit($villageId); $reinforcements = $database->getEnforceVillage($villageId, 0); // Sent $reinforcements = $database->getEnforceVillage($villageId, 1); // Received // Alliance operations $allianceData = $database->getAlliance($allianceId); $members = $database->getAlliMembers($allianceId); $memberCount = $database->countAlliMembers($allianceId); // Update operations $database->updateUserField($userId, "gold", 100, 1); // By ID $database->updateUserField("username", "gold", 100, 0); // By username $database->updateResource($villageId, ["wood", "clay"], [1000, 1000]); ?> ``` -------------------------------- ### Admin Panel Functions (PHP) Source: https://context7.com/shadowss/travianz/llms.txt Provides server management capabilities including user management, server configuration, and maintenance tools. Uses the 'database' object for operations like updating user fields, adding resources, banning users, and executing custom SQL queries for maintenance. ```php updateUserField($userId, "gold", 1000, 1); $database->updateUserField($userId, "access", 2, 1); // 0=normal, 1=banned, 2=admin // Add resources to village $database->updateResource($villageId, ["wood", "clay", "iron", "crop"], [10000, 10000, 10000, 10000] ); // Ban/unban user $database->updateUserField($userId, "access", BANNED, 1); // Ban $database->updateUserField($userId, "access", PLAYER, 1); // Unban // Server configuration (in GameEngine/config.php after installation) define('SERVER_NAME', 'My TravianZ Server'); define('WORLD_MAX', 400); // Map size (-400 to +400) define('INCREASE_SPEED', 3); // Game speed multiplier define('BASIC_MAX', 1); // Base build queue slots define('PLUS_MAX', 1); // Additional slots with Plus define('AUTH_EMAIL', false); // Require email verification define('TRACK_USR', true); // Track user activity // Medal management $database->addclimbalialiancemedal($allianceId, $week, $category, $points); $database->addclialiancemedal($allianceId, $week, $category, $points, $rank); // Server maintenance // Reset specific player data $database->query("UPDATE " . TB_PREFIX . "users SET gold=0"); // Clear build queues $database->query("DELETE FROM " . TB_PREFIX . "bdata WHERE timestamp < " . time()); ?> ``` -------------------------------- ### Manage Village Data in PHP Source: https://context7.com/shadowss/travianz/llms.txt Manages village resources, buildings, troops, and production. It handles resource generation and enforces storage limits. Requires including Village.php. ```php vname; echo "Village ID (wref): " . $village->wid; echo "Is Capital: " . ($village->capital ? "Yes" : "No"); // Current resources echo "Wood: " . floor($village->awood); echo "Clay: " . floor($village->aclay); echo "Iron: " . floor($village->airon); echo "Crop: " . floor($village->acrop); echo "Total Resources: " . $village->atotal; // Storage limits echo "Max Warehouse: " . $village->maxstore; echo "Max Granary: " . $village->maxcrop; // Population and coordinates echo "Population: " . $village->pop; echo "Coordinates: (" . $village->coor['x'] . "|" . $village->coor['y'] . ")"; // Get production rates echo "Wood Production: " . $village->getProd('wood') . "/hr"; echo "Clay Production: " . $village->getProd('clay') . "/hr"; echo "Iron Production: " . $village->getProd('iron') . "/hr"; echo "Crop Production: " . $village->getProd('crop') . "/hr"; // Access building levels through resarray // f1-f18 are resource fields, f19-f40 are buildings $mainBuildingLevel = $village->resarray['f26']; // Main Building $warehouseLevel = $village->resarray['f19']; // First building slot // Get all units in village $allUnits = $village->getAllUnits($village->wid); ``` -------------------------------- ### Generator Utilities: ID Generation and Calculations in PHP Source: https://context7.com/shadowss/travianz/llms.txt The MyGenerator class in PHP provides essential utility functions for game operations, including generating random IDs and strings, encoding strings for validation, calculating travel time between coordinates, formatting time for display, and converting coordinates to base IDs. It also includes functions for map checksum generation and page load timing. It relies on a global generator instance. ```php generateRandID(); // Returns: "a1b2c3d4e5f6789..." // Generate random string of specified length $randomString = $generator->generateRandStr(10); // Returns: "aB3dE7fGh2" // Encode string to fixed length (for validation tokens) $encoded = $generator->encodeStr("mystring", 8); // Returns: first 8 chars of MD5 hash // Calculate travel time between coordinates $fromCoords = ['x' => 10, 'y' => -5]; $toCoords = ['x' => 25, 'y' => 15]; $unitSpeed = 12; // Fields per hour // Mode 0: Use predefined speed reference $travelTime = $generator->procDistanceTime($toCoords, $fromCoords, 1, 0); // Mode 1: Use actual unit speed with Tournament Square bonus $travelTime = $generator->procDistanceTime($toCoords, $fromCoords, $unitSpeed, 1, $villageId); // Returns: seconds for travel // Format time for display $formattedTime = $generator->getTimeFormat(3661); // Returns: "1:01:01" // Process timestamp for display $timeArray = $generator->procMtime(time(), 3); // Returns: ["today", "14:30:25"] or ["25.12.24", "14:30:25"] // Convert coordinates to base ID $baseId = $generator->getBaseID(10, -5); // Returns: world tile reference ID // Generate map validation checksum $checksum = $generator->getMapCheck($worldRef); // Returns: 2-char validation code // Page load timing $startTime = $generator->pageLoadTimeStart(); // ... page processing ... $endTime = $generator->pageLoadTimeEnd(); $loadTimeMs = round(($endTime - $startTime) * 1000); ``` -------------------------------- ### Market and Trading API Source: https://context7.com/shadowss/travianz/llms.txt Manages resource trading between villages, NPC trading, and trade route automation. Requires an active session and potentially Gold Club features. ```APIDOC ## Market and Trading ### Description This section covers the API endpoints for managing the in-game market, including sending resources, setting up trade routes, and performing NPC trades. ### Method POST ### Endpoint `/` (Root endpoint, operations determined by POST data) ### Parameters #### Request Body - **ft** (string) - Required - Action type. Examples: - `s3`: Send resources to another village. - `s4`: Perform NPC trade. - **r1** (integer) - Resources (Wood) for sending or NPC trade. - **r2** (integer) - Resources (Clay) for sending or NPC trade. - **r3** (integer) - Resources (Iron) for sending or NPC trade. - **r4** (integer) - Resources (Crop) for sending or NPC trade. - **x** (integer) - Required for `s3` - Target village X coordinate. - **y** (integer) - Required for `s3` - Target village Y coordinate. ### Request Example (Send Resources) ```json { "ft": "s3", "r1": 1000, // Wood "r2": 500, // Clay "r3": 500, // Iron "r4": 200, // Crop "x": 15, "y": -10 } ``` ### Request Example (NPC Trade) ```json { "ft": "s4", "r1": 2000, // Desired Wood "r2": 2000, // Desired Clay "r3": 2000, // Desired Iron "r4": 1000 // Desired Crop } ``` ### Trade Route Management (Gold Club Feature) - This functionality is typically accessed via a separate interface or specific POST data structure, not detailed here but involves parameters like `action`, `tvillage`, `r1-r4`, `start`, `deliveries`. ### Response #### Success Response (200) - **message** (string) - Confirmation message (e.g., 'Resources sent successfully', 'NPC trade processed'). #### Error Response (400/409) - **error** (string) - Error message (e.g., 'Not enough resources', 'Invalid target coordinates', 'Trade route limit reached'). ### Notes - Market capacity and merchant status can be retrieved via global variables `$market->maxMerchant`, `$market->onMerchant`, `$market->maxcarry`. - Incoming and outgoing trades can be accessed via `$market->out` and `$market->in` respectively. ``` -------------------------------- ### Fix Incomplete UPDATE Statement for Hero Units Source: https://github.com/shadowss/travianz/blob/master/todo.txt This SQL UPDATE statement is incomplete and likely causing errors. It needs to be corrected to specify the value for the 'hero' column before the WHERE clause. This is suspected to be related to an automation issue during new registrations or first logins. ```sql UPDATE s1_units set hero = hero - WHERE vref = 38801 ``` -------------------------------- ### Add Index to s1_ww_attacks Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Adds a single-column index named 'vid' to the 's1_ww_attacks' table. This index is likely to optimize lookups based on the 'vid' column. ```sql ALTER TABLE `s1_ww_attacks` ADD INDEX(`vid`); ``` -------------------------------- ### Market and Trading Operations (PHP) Source: https://context7.com/shadowss/travianz/llms.txt Manages resource trading between villages, NPC trading, and trade route automation. Utilizes the Market class for operations like sending resources, creating trade routes, and NPC trades. Provides access to incoming and outgoing trade data. ```php maxMerchant; // Total merchants available $usedMerchants = $market->onMerchant; // Merchants currently trading $merchantCapacity = $market->maxcarry; // Resources per merchant // Process market actions $market->procMarket($_POST); // Send resources to another village $postData = [ 'ft' => 's3', // Send resources action 'r1' => 1000, // Wood 'r2' => 500, // Clay 'r3' => 500, // Iron 'r4' => 200, // Crop 'x' => 15, // Target X coordinate 'y' => -10, // Target Y coordinate ]; // Create trade route (Gold Club feature) $postData = [ 'action' => 'addRoute', 'tvillage' => 12345, // Target village wref 'r1' => 500, 'r2' => 500, 'r3' => 500, 'r4' => 200, 'start' => 8, // Hour to start (0-23) 'deliveries' => 2, // Deliveries per day (1-3) ]; // NPC trading (exchange resources at marketplace) // Requires Gold and active Plus account $postData = [ 'ft' => 's4', // NPC trade action 'r1' => 2000, // Desired wood amount 'r2' => 2000, // Desired clay amount 'r3' => 2000, // Desired iron amount 'r4' => 1000, // Desired crop amount ]; // View incoming/outgoing trades $incomingTrades = $market->out; // Incoming resources $outgoingTrades = $market->in; // Outgoing trades ?> ``` -------------------------------- ### Alliance Class: Manage Alliance Operations in PHP Source: https://context7.com/shadowss/travianz/llms.txt The Alliance class in PHP manages various aspects of in-game alliances, including invitations, permissions, forum access, and diplomacy. It processes alliance actions from user input, checks for pending invitations, retrieves alliance data, and verifies user permissions and forum accessibility. Dependencies include the global session and database objects. ```php procAlliance($_GET); // Check if player has pending invitations if ($alliance->gotInvite) { foreach ($alliance->inviteArray as $invite) { echo "Invitation from alliance: " . $invite['alliance']; } } // Access alliance data (if player is in an alliance) if ($session->alliance > 0) { $allianceData = $alliance->allianceArray; echo "Alliance Name: " . $allianceData['name']; echo "Alliance Tag: " . $allianceData['tag']; echo "Alliance ID: " . $allianceData['id']; // Check user permissions $permissions = $alliance->userPermArray; // opt1-opt8 represent different permission flags if ($permissions['opt1']) { echo "User can invite members"; } } // Check forum accessibility $forumId = 5; if ($alliance->isForumAccessible($forumId)) { echo "Forum is accessible"; } // Create forum visibility (for sharing forums with other alliances) $sharedAlliances = [10, 15]; // Alliance IDs $sharedUsers = [100, 200]; // User IDs $visibility = $alliance->createForumVisiblity( $sharedAlliances, [], // Alliance names $sharedUsers, [] // User names ); ``` -------------------------------- ### Add Indexes to s1_forum_cat Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Adds three new indexes to the 's1_forum_cat' table: 'display_to_alliances' (first 11 characters), 'display_to_users' (first 11 characters), and 'sorting'. These are intended to speed up queries related to forum category display and sorting. ```sql ALTER TABLE `s1_forum_cat` ADD INDEX `display_to_alliances` (`display_to_alliances`(11)); ALTER TABLE `s1_forum_cat` ADD INDEX `display_to_users` (`display_to_users`(11)); ALTER TABLE `s1_forum_cat` ADD INDEX `sorting` (`sorting`); ``` -------------------------------- ### Optimize Alliance Permission and Medal Indexes Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Enhances alliance-related operations by adding and modifying indexes. Indexes are added for 'alliance' in 's1_ali_permission' and 'allyid' in 's1_ali_medal'. A unique index 'uid-alliance' is created on 's1_ali_permission' using BTREE. ```sql ALTER TABLE `s1_ali_permission` ADD INDEX(`alliance`); ALTER TABLE `s1_ali_medal` ADD INDEX(`allyid`); ALTER TABLE `s1_ali_permission` DROP INDEX `uid-alliance`, ADD UNIQUE `uid-alliance` (`uid`, `alliance`) USING BTREE; ``` -------------------------------- ### Add Index to s1_route Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Adds a composite index named 'uid-timestamp' to the 's1_route' table. This index is designed to optimize queries that filter or sort by both user ID and timestamp. ```sql ALTER TABLE `s1_route` ADD INDEX `uid-timestamp` (`uid`, `timestamp`); ``` -------------------------------- ### Drop Columns from s1_forum_topic and s1_forum_post Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Removes eight columns ('alliance0', 'player0', 'coor0', 'report0') from both the 's1_forum_topic' and 's1_forum_post' tables. This cleanup likely removes outdated or unused data fields. ```sql ALTER TABLE `s1_forum_topic` DROP `alliance0`, DROP `player0`, DROP `coor0`, DROP `report0`; ALTER TABLE `s1_forum_post` DROP `alliance0`, DROP `player0`, DROP `coor0`, DROP `report0`; ``` -------------------------------- ### Optimize Hero-Related Indexes Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Improves performance for hero-related queries by adding and modifying indexes. Indexes are added for 'lastupdate', 'inrevive', and 'intraining'. The 'uid' index is dropped and replaced with a composite index on 'uid' and 'dead' using BTREE. ```sql ALTER TABLE `s1_hero` ADD INDEX(`lastupdate`); ALTER TABLE `s1_hero` DROP INDEX `uid`, ADD INDEX `uid` (`uid`, `dead`) USING BTREE; ALTER TABLE `s1_hero` ADD INDEX(`inrevive`); ALTER TABLE `s1_hero` ADD INDEX(`intraining`); ``` -------------------------------- ### Add Text Columns to s1_forum_cat Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Adds two new text columns, 'display_to_alliances' and 'display_to_users', to the 's1_forum_cat' table. These columns are likely intended to store display preferences or settings. ```sql ALTER TABLE s1_forum_cat ADD (`display_to_alliances` text, `display_to_users` text) ``` -------------------------------- ### Optimize Indexes in s1_market and s1_mdata Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Enhances query performance by modifying and adding indexes. 's1_market' drops 'vref-accept' and adds 'vref-accept-merchant' with BTREE. 's1_mdata' adds a 'target-viewed' index. ```sql ALTER TABLE `s1_market` DROP INDEX `vref-accept`, ADD INDEX `vref-accept-merchant` (`vref`, `accept`, `merchant`) USING BTREE; ALTER TABLE `s1_mdata` ADD INDEX `target-viewed` (`target`, `viewed`); ``` -------------------------------- ### Add Indexes to s1_ndata Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Adds two new indexes to the 's1_ndata' table: 'uid-viewed' and 'toWref'. These indexes are intended to improve the speed of queries involving these specific columns. ```sql ALTER TABLE `s1_ndata` ADD INDEX `uid-viewed` (`uid`, `viewed`); ALTER TABLE `s1_ndata` ADD INDEX(`toWref`); ``` -------------------------------- ### Message Class: Handle In-Game Messaging in PHP Source: https://context7.com/shadowss/travianz/llms.txt The Message class in PHP manages the in-game messaging system, including inbox, sent messages, archives, and battle reports. It allows checking for unread messages, accessing message content, processing message actions like sending or deleting, loading specific messages, and filtering battle reports/notices by type. Dependencies include the global session and database objects. ```php unread) { echo "You have unread messages"; } if ($message->nunread) { echo "You have unread notices/reports"; } // Access inbox messages foreach ($message->inbox as $msg) { echo "From: " . $msg['owner']; echo "Subject: " . $msg['topic']; echo "Time: " . $msg['time']; echo "Read: " . ($msg['viewed'] ? "Yes" : "No"); } // Access sent messages foreach ($message->sent as $msg) { echo "To: " . $msg['target']; echo "Subject: " . $msg['topic']; } // Process message actions $postData = [ 'ft' => 'm2', // Action type (m1=quote, m2=send, m3-5=delete/archive) 'an' => 'recipient', // Recipient username 'be' => 'Subject Line', // Subject 'message' => 'Hello!', // Message body ]; $message->procMessage($postData); // Load a specific message $messageId = 123; $message->loadMessage($messageId); $readingMessage = $message->reading; // Process battle reports/notices $message->noticeType($_GET); // Filter by type: 1=trade, 2=reinforcements, 3=attacks, 4=other $notices = $message->noticearray; // Process notice actions (delete, archive) $message->procNotice($_POST); ``` -------------------------------- ### Create s1_artefacts_chrono Table Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Creates a new table named 's1_artefacts_chrono' to store historical data related to artefacts. It includes columns for ID, artefact ID, user ID, village reference, and conquest time, along with primary and secondary indexes. ```sql CREATE TABLE IF NOT EXISTS `s1_artefacts_chrono` ( `id` int(11) NOT NULL AUTO_INCREMENT, `artefactid` int(11) NULL, `uid` int(11) NULL, `vref` int(11) NULL, `conqueredtime` int(11) NULL, PRIMARY KEY (`id`), KEY `artefactid-conqueredtime` (`artefactid`,`conqueredtime`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; ``` -------------------------------- ### Add Indexes to s1_active, s1_odata, s1_vdata, s1_deleting, s1_movement, s1_artefacts Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Applies various index additions to tables related to active users, game data, village data, deletions, movements, and artefacts. These indexes are designed to speed up common data retrieval operations. ```sql ALTER TABLE `s1_active` ADD INDEX(`timestamp`); ALTER TABLE `s1_odata` ADD INDEX(`clay`); ALTER TABLE `s1_odata` ADD INDEX(`crop`); ALTER TABLE `s1_odata` ADD INDEX(`iron`); ALTER TABLE `s1_odata` ADD INDEX(`wood`); ALTER TABLE `s1_vdata` ADD INDEX(`crop`); ALTER TABLE `s1_vdata` ADD INDEX(`iron`); ALTER TABLE `s1_vdata` ADD INDEX(`clay`); ALTER TABLE `s1_vdata` ADD INDEX(`wood`); ALTER TABLE `s1_deleting` ADD INDEX(`timestamp`); ALTER TABLE `s1_movement` ADD INDEX `proc-sort_type-endtime` (`proc`, `sort_type`, `endtime`); ALTER TABLE `s1_vdata` ADD INDEX(`starv`); ALTER TABLE `s1_vdata` ADD INDEX(`loyalty`); ALTER TABLE `s1_odata` ADD INDEX(`loyalty`); ALTER TABLE `s1_artefacts` ADD INDEX `active-type-lastupdate` (`active`, `type`, `lastupdate`); ``` -------------------------------- ### Add Indexes to s1_vdata Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Adds three new indexes ('exp1', 'exp2', 'exp3') to the 's1_vdata' table. These indexes are likely intended to optimize queries that filter or sort by these specific columns. ```sql ALTER TABLE `s1_vdata` ADD INDEX(`exp1`); ALTER TABLE `s1_vdata` ADD INDEX(`exp2`); ALTER TABLE `s1_vdata` ADD INDEX(`exp3`); ``` -------------------------------- ### Add Sorting Column to s1_forum_cat Source: https://github.com/shadowss/travianz/blob/master/sql_updates.txt Adds an integer column named 'sorting' to the 's1_forum_cat' table. This column is marked as NOT NULL and is placed after the 'id' column, suggesting it will be used for ordering forum categories. ```sql ALTER TABLE s1_forum_cat ADD `sorting` int(11) NOT NULL AFTER `id` ```