Repository: aternosorg/mclogs Branch: main Commit: 5269341d2bad Files: 98 Total size: 217.8 KB Directory structure: gitextract_kqffgv0b/ ├── .dockerignore ├── .github/ │ └── workflows/ │ └── publish.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── build.php ├── composer.json ├── dev/ │ ├── compose.yaml │ └── dev.ini ├── docker/ │ ├── Caddyfile │ ├── compose.production.yaml │ └── mclogs.ini ├── example.config.json ├── src/ │ ├── Api/ │ │ ├── Action/ │ │ │ ├── AnalyseLogAction.php │ │ │ ├── ApiAction.php │ │ │ ├── BulkDeleteLogsAction.php │ │ │ ├── CreateLogAction.php │ │ │ ├── DeleteLogAction.php │ │ │ ├── EmptyAction.php │ │ │ ├── EndpointNotFoundAction.php │ │ │ ├── GetFiltersAction.php │ │ │ ├── GetLimitsAction.php │ │ │ ├── LogInfoAction.php │ │ │ ├── LogInsightsAction.php │ │ │ ├── RateLimitErrorAction.php │ │ │ └── RawLogAction.php │ │ ├── ApiRouter.php │ │ ├── ContentParser.php │ │ ├── LogContentParser.php │ │ └── Response/ │ │ ├── ApiError.php │ │ ├── ApiResponse.php │ │ ├── CodexLogResponse.php │ │ ├── FiltersResponse.php │ │ ├── LimitsResponse.php │ │ ├── LogResponse.php │ │ ├── MultiResponse.php │ │ └── RawLogResponse.php │ ├── Cache/ │ │ └── CacheEntry.php │ ├── Config/ │ │ ├── Config.php │ │ └── ConfigKey.php │ ├── Data/ │ │ ├── Deobfuscator.php │ │ ├── MetadataEntry.php │ │ └── Token.php │ ├── Detective.php │ ├── Filter/ │ │ ├── AccessTokenFilter.php │ │ ├── Filter.php │ │ ├── FilterType.php │ │ ├── IPv4Filter.php │ │ ├── IPv6Filter.php │ │ ├── LimitBytesFilter.php │ │ ├── LimitLinesFilter.php │ │ ├── Pattern/ │ │ │ ├── Modifier.php │ │ │ ├── Pattern.php │ │ │ └── PatternWithReplacement.php │ │ ├── RegexFilter.php │ │ ├── TrimFilter.php │ │ └── UsernameFilter.php │ ├── Frontend/ │ │ ├── Action/ │ │ │ ├── ApiDocsAction.php │ │ │ ├── CreateLogAction.php │ │ │ ├── DeleteLogAction.php │ │ │ ├── FaviconAction.php │ │ │ ├── NotFoundAction.php │ │ │ ├── StartAction.php │ │ │ └── ViewLogAction.php │ │ ├── Assets/ │ │ │ ├── Asset.php │ │ │ ├── AssetLoader.php │ │ │ └── AssetType.php │ │ ├── Cookie/ │ │ │ ├── Cookie.php │ │ │ ├── SettingsCookie.php │ │ │ └── TokenCookie.php │ │ ├── FrontendRouter.php │ │ └── Settings/ │ │ ├── Setting.php │ │ └── Settings.php │ ├── Id.php │ ├── Log.php │ ├── Printer/ │ │ ├── FormatModification.php │ │ └── Printer.php │ ├── Router/ │ │ ├── Action.php │ │ ├── Method.php │ │ ├── Route.php │ │ └── Router.php │ ├── Storage/ │ │ └── MongoDBClient.php │ └── Util/ │ ├── Singleton.php │ ├── TimeInterval.php │ └── URL.php ├── web/ │ ├── frontend/ │ │ ├── 404.php │ │ ├── api-docs.php │ │ ├── log.php │ │ ├── parts/ │ │ │ ├── favicon.php │ │ │ ├── footer.php │ │ │ ├── head.php │ │ │ └── header.php │ │ └── start.php │ └── public/ │ ├── css/ │ │ └── mclogs.css │ └── js/ │ ├── log.js │ └── start.js └── worker.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ vendor/ .git/ .github/ Dockerfile ================================================ FILE: .github/workflows/publish.yml ================================================ name: Publish Docker Image on: push: branches: - 'main' tags: - 'v*' env: REGISTRY: ghcr.io IMAGE_NAME: ${{ github.repository }} jobs: build-and-push: runs-on: ubuntu-latest permissions: contents: read packages: write steps: - name: Checkout repository uses: actions/checkout@v4 - name: Set up QEMU uses: docker/setup-qemu-action@v3 - name: Log in to the Container registry uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Extract metadata (tags, labels) id: meta uses: docker/metadata-action@v5 with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} tags: | # Branch Name (e.g. 'two', 'main') type=ref,event=branch # Full Version (e.g. '1.2.3') type=semver,pattern={{version}} # Major Version (e.g. '1') type=semver,pattern={{major}} # Major.Minor (e.g. '1.2') type=semver,pattern={{major}}.{{minor}} # Latest (Only on release tags) type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') }} - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - name: Build and push Docker image uses: docker/build-push-action@v5 with: context: . push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} platforms: linux/amd64,linux/arm64 cache-from: | type=gha type=gha,scope=refs/heads/main cache-to: type=gha,mode=max ================================================ FILE: .gitignore ================================================ *.log *.cache .idea /vendor/ config.json ================================================ FILE: Dockerfile ================================================ FROM dunglas/frankenphp:1-php8.5 # System Setup RUN install-php-extensions mongodb zip ARG USER=mclogs RUN useradd ${USER} && \ setcap CAP_NET_BIND_SERVICE=+eip /usr/local/bin/frankenphp COPY --from=composer/composer:2-bin /composer /usr/bin/composer WORKDIR /app # Dependencies (Cached) COPY composer.json composer.lock ./ RUN --mount=type=cache,target=/tmp/cache/composer \ COMPOSER_CACHE_DIR=/tmp/cache/composer \ composer install --no-dev --no-interaction --no-scripts --no-autoloader --prefer-dist --ignore-platform-req=ext-frankenphp # Application Setup COPY docker/Caddyfile /etc/frankenphp/Caddyfile COPY docker/mclogs.ini /usr/local/etc/php/conf.d/mclogs.ini COPY . . RUN composer dump-autoload --optimize --no-dev --classmap-authoritative RUN php build.php # Permissions & Runtime RUN chown -R ${USER}:${USER} /config/caddy /data/caddy /app USER ${USER} EXPOSE 80 EXPOSE 443 EXPOSE 443/udp VOLUME ["/data"] ================================================ FILE: LICENSE ================================================ Copyright (c) 2018-2024 Aternos GmbH Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================

Paste, share & analyse your logs
Built for Minecraft & Hytale

## Features * Share logs by pasting or uploading files * Automatic removal of sensitive information (e.g. IP addresses) * Short URLs for easy sharing * Syntax highlighting * Line numbers * Direct links to specific lines * Analysis and parsing using [codex](https://github.com/aternosorg/codex-minecraft) ### For developers * Upload your logs using the API * Add metadata to shared logs, e.g. version numbers, server ids, etc. * Retrieve logs and their metadata from the API * Open source and self-hostable ## Self-hosting You can self-host mclogs using Docker. A [docker image](https://github.com/aternosorg/mclogs/pkgs/container/mclogs) is available in the GitHub Container Registry: `ghcr.io/aternosorg/mclogs`. A MongoDB instance is also required to run mclogs. An example docker compose files for self-hosting can be found here: [docker/compose.production.yaml](docker/compose.production.yaml). ### Config You can configure mclogs by creating a `config.json` file in the root directory, see [example.config.json](example.config.json) or by setting environment variables. Environment variables override settings in the config file. Here is a list of all available config options: | Variable / JSON Path | Default | Description | |:--------------------------------------------------------------------|:--------------------|:--------------------------------------------| | `MCLOGS_STORAGE_TTL`
`storage.ttl` | `7776000` (90d) | Time until logs are deleted after last view | | `MCLOGS_STORAGE_LIMIT_BYTES`
`storage.limit.bytes` | `10485760` (10 MiB) | Maximum size of a log in bytes | | `MCLOGS_STORAGE_LIMIT_LINES`
`storage.limit.lines` | `25000` | Maximum number of lines in a log | | `MCLOGS_MONGODB_URL`
`mongodb.url` | `"mongodb://mongo"` | MongoDB connection URL | | `MCLOGS_MONGODB_DATABASE`
`mongodb.database` | `"mclogs"` | Name of the MongoDB database | | `MCLOGS_ID_LENGTH`
`id.length` | `7` | The default length for new IDs | | `MCLOGS_LEGAL_ABUSE`
`legal.abuse` | `null` | Public email address to report abuse | | `MCLOGS_LEGAL_IMPRINT`
`legal.imprint` | `null` | The imprint URL | | `MCLOGS_LEGAL_PRIVACY`
`legal.privacy` | `null` | The privacy policy URL | | `MCLOGS_FRONTEND_NAME`
`frontend.name` | `null` | Instance name (defaults to domain) | | `MCLOGS_FRONTEND_COLOR_ACCENT`
`frontend.color.accent` | `#5cb85c` | The accent/primary color | | `MCLOGS_FRONTEND_COLOR_BACKGROUND`
`frontend.color.background` | `#1a1a1a` | The background color | | `MCLOGS_FRONTEND_COLOR_TEXT`
`frontend.color.text` | `#e8e8e8` | The text color | | `MCLOGS_FRONTEND_COLOR_ERROR`
`frontend.color.error` | `#f62451` | The error color | | `MCLOGS_WORKER_REQUESTS`
`worker.requests` | `500` | Max requests per single worker | There are a few more environment variables that can be set to modify the FrankenPHP/Caddy setup directly: | Variable | Default | Description | |----------------------|--------------------|--------------------------------------------------------------------------------------------------------------------------------------------| | `SERVER_NAME` | `":80"` | Set the Caddy server name, set this to your domain for [automatic SSL](https://caddyserver.com/docs/automatic-https#hostname-requirements) | | `TRUSTED_PROXIES` | `"private_ranges"` | Set [trusted proxy](https://caddyserver.com/docs/caddyfile/options#trusted-proxies) address ranges | | `FRANKENPHP_WORKERS` | `16` | The number of [FrankenPHP workers](https://frankenphp.dev/docs/worker/) | | ## Development setup ### Prerequisites * [Docker](https://www.docker.com/get-started/) and [Docker Compose](https://docs.docker.com/compose/install/) * [PHP 8.5+](https://www.php.net/downloads) * [Composer](https://getcomposer.org/download/) ### Installation ```bash # clone repository git clone git@github.com:aternosorg/mclogs.git # install composer dependencies cd mclogs composer install # start development environment cd dev docker compose up ``` Open http://localhost in browser and enjoy. ================================================ FILE: build.php ================================================ writeCache(); ================================================ FILE: composer.json ================================================ { "name": "aternos/mclogs", "description": "Paste, share and analyse Minecraft logs", "authors": [ { "name": "Matthias Neid", "email": "matthias@aternos.org" } ], "require": { "php": ">=8.5", "ext-frankenphp": "*", "ext-json": "*", "ext-mbstring": "*", "ext-mongodb": "*", "ext-uri": "*", "ext-zlib": "*", "aternos/codex-hytale": "^2.0", "aternos/codex-minecraft": "^5.0.1", "aternos/sherlock": "^1.0.2", "mongodb/mongodb": "2.1.2" }, "autoload": { "psr-4": { "Aternos\\Mclogs\\": "src/" } } } ================================================ FILE: dev/compose.yaml ================================================ name: "mclogs" services: web: build: context: .. dockerfile: ./Dockerfile environment: - MCLOGS_WORKER_REQUESTS=1 - FRANKENPHP_WORKERS=4 ports: - "80:80" volumes: - ../:/app - ./dev.ini:/usr/local/etc/php/conf.d/dev.ini user: root depends_on: mongo: condition: service_healthy mongo: image: mongo volumes: - mongo:/data/db healthcheck: test: [ "CMD", "mongosh", "--eval", "db.adminCommand('ping')" ] interval: 5s timeout: 5s retries: 5 start_period: 10s volumes: mongo: ================================================ FILE: dev/dev.ini ================================================ opcache.enable=1 opcache.enable_cli=1 opcache.validate_timestamps=1 opcache.revalidate_freq=0 opcache.jit=off ================================================ FILE: docker/Caddyfile ================================================ { servers { trusted_proxies static {$TRUSTED_PROXIES:private_ranges} trusted_proxies_strict } frankenphp { worker /app/worker.php { num {$FRANKENPHP_WORKERS:16} } } } {$SERVER_NAME::80} { root * /app/web/public encode zstd br gzip @static file handle @static { file_server } handle { root * /app rewrite * /worker.php php_server } } ================================================ FILE: docker/compose.production.yaml ================================================ services: web: image: ghcr.io/aternosorg/mclogs:2 restart: always ports: # Expose HTTP (80) and HTTPS (443) # Port 443/udp is required for HTTP/3 (QUIC) - "80:80" - "443:443" - "443:443/udp" environment: # Set this to your domain (e.g., mclogs.example.com) to enable Auto-SSL. # If running behind a proxy (Cloudflare/Nginx), set to ":80" to disable Auto-SSL. SERVER_NAME: :80 MCLOGS_MONGODB_URL: mongodb://mongo:27017 MCLOGS_MONGODB_DATABASE: mclogs # Optional MCLOGS configuration # See README.md for full list of available options # MCLOGS_FRONTEND_NAME: "mclogs" volumes: # For caddy cache (SSL certificates) - web-data:/data depends_on: mongo: condition: service_healthy mongo: image: mongo restart: always volumes: - mongo-data:/data/db healthcheck: test: echo 'db.runCommand("ping").ok' | mongosh localhost:27017/test --quiet interval: 10s timeout: 5s retries: 5 start_period: 5s volumes: web-data: mongo-data: ================================================ FILE: docker/mclogs.ini ================================================ post_max_size = 50M error_reporting = E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED display_errors = Off display_startup_errors = Off log_errors = On error_log = /dev/stderr ================================================ FILE: example.config.json ================================================ { "storage": { "ttl": 7776000, "limit": { "bytes": 10485760, "lines": 25000 } }, "mongodb": { "url": "mongodb://127.0.0.1:27017", "database": "mclogs" }, "id": { "length": 7 }, "legal": { "abuse": "abuse@aternos.org", "imprint": "https://aternos.gmbh/imprint/", "privacy": "https://aternos.gmbh/en/mclogs/privacy" }, "frontend": { "name": "mclo.gs", "assets": { "integrity": true }, "color": { "background": "#1a1a1a", "text": "#e8e8e8", "accent": "#5cb85c", "error": "#f62451" } }, "worker": { "requests": 500 } } ================================================ FILE: src/Api/Action/AnalyseLogAction.php ================================================ getContent(); if ($data instanceof ApiError) { return $data; } $content = $data['content']; $log = new Log()->setContent($content); return new CodexLogResponse($log->getCodexLog()); } } ================================================ FILE: src/Api/Action/ApiAction.php ================================================ getAllowedOrigin()); header('Access-Control-Allow-Headers: *'); if ($this->shouldAllowCredentials()) { header('Access-Control-Allow-Credentials: true'); } header("Accept-Encoding: " . implode(",", ContentParser::getSupportedEncodings())); $response = $this->runApi(); $response->output(); return true; } } ================================================ FILE: src/Api/Action/BulkDeleteLogsAction.php ================================================ getContent(); if ($data instanceof ApiError) { return $data; } if (count($data) === 0) { return new ApiError(400, "No logs provided."); } if (count($data) > static::MAX_IDS) { return new ApiError(400, "Too many logs. Maximum is " . static::MAX_IDS . "."); } $ids = []; foreach ($data as $log) { if (!is_array($log)) { return new ApiError(400, "Each entry must be an object with 'id' and 'token' fields."); } if (!isset($log["id"]) || !is_string($log["id"]) || !preg_match("/^" . Id::PATTERN . "$/", $log["id"])) { return new ApiError(400, "Each log must have a valid 'id' field."); } if (!isset($log["token"]) || !is_string($log["token"])) { return new ApiError(400, "Each log must have a valid 'token' field."); } $ids[] = $log["id"]; } $logs = Log::findAll($ids, false); $deleteIds = []; $response = new MultiResponse(); foreach ($data as $log) { $id = $log["id"]; $token = $log["token"]; $log = $logs[$id] ?? null; if (!$log) { $response->addResponse($id, new ApiError(404, "Log not found.")); continue; } $logToken = $log->getToken(); if (!$logToken || !$logToken->matches($token)) { $response->addResponse($id, new ApiError(403, "Invalid token.")); continue; } $deleteIds[] = $id; $response->addResponse($id, new ApiResponse()); } MongoDBClient::getInstance()->deleteLogs($deleteIds); return $response; } } ================================================ FILE: src/Api/Action/CreateLogAction.php ================================================ getContent(); if ($data instanceof ApiError) { return $data; } $content = $data['content']; $metadata = []; if (isset($data['metadata']) && is_array($data['metadata'])) { $metadata = MetadataEntry::allFromArray($data['metadata']); } $source = null; if (isset($data['source']) && is_string($data['source'])) { $source = $data['source']; } $log = Log::create($content, $metadata, $source); if ($this->includeCookie) { $log->setTokenCookie(); } return new LogResponse($log, $this->includeToken); } } ================================================ FILE: src/Api/Action/DeleteLogAction.php ================================================ getRequestToken(); if (!$requestToken) { return new ApiError(400, "Missing token."); } $id = new Id(URL::getLastPathPart()); $log = Log::find($id); if (!$log) { return new ApiError(404, "Log not found."); } $token = $log->getToken(); if (!$token || !$token->matches($requestToken)) { return new ApiError(403, "Invalid token."); } $deleted = $log->delete(); if (!$deleted) { return new ApiError(500, "Failed to delete log."); } $this->handleDeletedLog($log); return new ApiResponse(); } protected function handleDeletedLog(Log $log): void { } } ================================================ FILE: src/Api/Action/EmptyAction.php ================================================ getCodexLog(); $codexLog->setIncludeEntries(false); return new CodexLogResponse($codexLog); } } ================================================ FILE: src/Api/Action/RateLimitErrorAction.php ================================================ register(Method::GET, "#^/$#", new Frontend\Action\ApiDocsAction()) ->register(Method::OPTIONS, "#^/.*$#", new Action\EmptyAction()) ->register(Method::POST, "#^/1/log/?$#", new Action\CreateLogAction()) ->register(Method::GET, "#^/1/log/" . Id::PATTERN . "$#", new Action\LogInfoAction()) ->register(Method::DELETE, "#^/1/log/" . Id::PATTERN . "$#", new Action\DeleteLogAction()) ->register(Method::POST, "#^/1/bulk/log/delete/?$#", new Action\BulkDeleteLogsAction()) ->register(Method::GET, "#^/1/insights/" . Id::PATTERN . "$#", new Action\LogInsightsAction()) ->register(Method::GET, "#^/1/raw/" . Id::PATTERN . "$#", new Action\RawLogAction()) ->register(Method::POST, "#^/1/analyse/?$#", new Action\AnalyseLogAction()) ->register(Method::GET, "#^/1/errors/rate$#", new Action\RateLimitErrorAction()) ->register(Method::GET, "#^/1/limits$#", new Action\GetLimitsAction()) ->register(Method::GET, "#^/1/filters#", new Action\GetFiltersAction()) ->setDefaultAction(new Action\EndpointNotFoundAction()); } } ================================================ FILE: src/Api/ContentParser.php ================================================ get(ConfigKey::STORAGE_LIMIT_BYTES) * 2; $body = file_get_contents('php://input', length: $limit + 1); if ($body === false) { return new ApiError(500, "Failed to read request body."); } if (strlen($body) > $limit) { return new ApiError(413, "Request body exceeds maximum allowed size."); } $encodingHeader = $_SERVER['HTTP_CONTENT_ENCODING'] ?? ''; if ($encodingHeader) { $encodingSteps = explode(',', $encodingHeader); if (count($encodingSteps) > static::MAX_ENCODING_STEPS) { return new ApiError(400, "Too many Content-Encoding steps."); } foreach (array_reverse($encodingSteps) as $step) { switch (trim(strtolower($step))) { case "deflate": $body = @gzinflate($body, $limit); break; case "x-gzip": case "gzip": $body = @gzdecode($body, $limit); break; default: return new ApiError(415, "Unsupported Content-Encoding: " . htmlspecialchars($step)); } if ($body === false) { return new ApiError(400, "Failed to decode request body with encoding: " . htmlspecialchars($step)); } } } $contentTypeHeader = $_SERVER['CONTENT_TYPE'] ?? ''; if ($pos = strpos($contentTypeHeader, ';')) { $contentTypeHeader = substr($contentTypeHeader, 0, $pos); } switch ($contentTypeHeader) { case "application/x-www-form-urlencoded": parse_str($body, $data); break; case "application/json": $data = @json_decode($body, true); if (!is_array($data)) { return new ApiError(400, "Failed to parse JSON body."); } break; default: return new ApiError(415, "Unsupported Content-Type: " . htmlspecialchars($contentTypeHeader)); } return $data; } } ================================================ FILE: src/Api/LogContentParser.php ================================================ setHttpCode($httpCode); } public function jsonSerialize(): array { $data = parent::jsonSerialize(); $data['error'] = $this->message; return $data; } } ================================================ FILE: src/Api/Response/ApiResponse.php ================================================ $this->success, ]; } /** * @param int $httpCode * @return $this */ public function setHttpCode(int $httpCode): static { $this->httpCode = $httpCode; return $this; } /** * @return int */ public function getHttpCode(): int { return $this->httpCode; } /** * @param bool $success * @return $this */ public function setSuccess(bool $success): static { $this->success = $success; return $this; } /** * @return bool */ public function isSuccess(): bool { return $this->success; } /** * @return $this */ public function output(): static { header('Content-Type: application/json'); http_response_code($this->httpCode); echo json_encode($this, JSON_UNESCAPED_SLASHES); return $this; } } ================================================ FILE: src/Api/Response/CodexLogResponse.php ================================================ codexLog->jsonSerialize()); } } ================================================ FILE: src/Api/Response/FiltersResponse.php ================================================ get(ConfigKey::STORAGE_TTL); $data['maxLength'] = $config->get(ConfigKey::STORAGE_LIMIT_BYTES); $data['maxLines'] = $config->get(ConfigKey::STORAGE_LIMIT_LINES); return $data; } } ================================================ FILE: src/Api/Response/LogResponse.php ================================================ loadFromGet(); } public function loadFromGet(): static { $url = URL::getCurrent(); $query = $url->getQuery(); if (empty($query)) { return $this; } parse_str($url->getQuery(), $get); $this->withInsights = isset($get['insights']); $this->withRaw = isset($get['raw']); $this->withParsed = isset($get['parsed']); return $this; } public function jsonSerialize(): array { $data = parent::jsonSerialize(); $data['id'] = $this->log->getId(); $data['source'] = $this->log->getSource(); $data['created'] = $this->log->getCreated()?->toDateTime()->getTimestamp(); $data['expires'] = $this->log->getExpires()?->toDateTime()->getTimestamp(); $data['size'] = $this->log->getSize(); $data['lines'] = $this->log->getLinesCount(); $data['errors'] = $this->log->getErrorsCount(); $data['url'] = $this->log->getUrl()->toString(); $data['raw'] = $this->log->getRawURL()->toString(); if ($this->withToken) { $data['token'] = $this->log->getToken(); } $data['metadata'] = $this->log->getMetadata(); if ($this->withInsights || $this->withRaw || $this->withParsed) { $data['content'] = []; } if ($this->withInsights) { $data['content']['insights'] = $this->log->getCodexLog()->setIncludeEntries(false); } if ($this->withRaw) { $data['content']['raw'] = $this->log->getContent(); } if ($this->withParsed) { $data['content']['parsed'] = $this->log->getCodexLog()->getEntries(); } return $data; } } ================================================ FILE: src/Api/Response/MultiResponse.php ================================================ responses[$id] = $response; return $this; } public function jsonSerialize(): array { $response = parent::jsonSerialize(); $results = []; foreach ($this->responses as $id => $apiResponse) { $result = $apiResponse->jsonSerialize(); $result["id"] = $id; $result["status"] = $apiResponse->getHttpCode(); $results[] = $result; } $response["results"] = $results; return $response; } } ================================================ FILE: src/Api/Response/RawLogResponse.php ================================================ log->getContent(); return $this; } } ================================================ FILE: src/Cache/CacheEntry.php ================================================ getCacheCollection()->findOne([ "_id" => $this->key ]); return $result?->data; } /** * @param string $data * @param int $ttl * @return $this */ public function set(string $data, int $ttl = 24 * 60 * 60): static { MongoDBClient::getInstance()->getCacheCollection()->updateOne( ["_id" => $this->key], ['$set' => [ 'data' => $data, 'expires' => new UTCDateTime((time() + $ttl) * 1000) ]], ['upsert' => true] ); return $this; } } ================================================ FILE: src/Config/Config.php ================================================ jsonData = $data; } } } /** * Get config value by checking environment variable, then config file, then default value * * @param ConfigKey $key * @return mixed */ public function get(ConfigKey $key): mixed { $env = getenv($key->getEnvironmentVariable()); if ($env !== false) { if ($env === "true") { return true; } else if ($env === "false") { return false; } return $env; } $json = $this->getJsonValue($key->getJSONPath()); if ($json !== null) { return $json; } return $key->getDefaultValue(); } /** * @return string */ public function getName(): string { return $this->get(ConfigKey::FRONTEND_NAME) ?? URL::getBase()->getHost(); } /** * Recursively get a value from the json data by path * * @param array $path * @param array|null $data * @return mixed */ protected function getJsonValue(array $path, ?array $data = null): mixed { if ($data === null) { $data = $this->jsonData; } $nextKey = array_shift($path); if (!isset($data[$nextKey])) { return null; } $nextData = $data[$nextKey]; if (count($path) === 0) { return $nextData; } if (!is_array($nextData)) { return null; } return $this->getJsonValue($path, $nextData); } } ================================================ FILE: src/Config/ConfigKey.php ================================================ 90 * 24 * 60 * 60, ConfigKey::STORAGE_LIMIT_BYTES => 10 * 1024 * 1024, ConfigKey::STORAGE_LIMIT_LINES => 25000, ConfigKey::MONGODB_URL => 'mongodb://mongo:27017', ConfigKey::MONGODB_DATABASE => 'mclogs', ConfigKey::ID_LENGTH => 7, ConfigKey::FRONTEND_ANALYTICS => false, ConfigKey::FRONTEND_ASSETS_INTEGRITY => true, ConfigKey::FRONTEND_COLOR_BACKGROUND => "#1a1a1a", ConfigKey::FRONTEND_COLOR_TEXT => "#e8e8e8", ConfigKey::FRONTEND_COLOR_ACCENT => "#5cb85c", ConfigKey::FRONTEND_COLOR_ERROR => "#f62451", ConfigKey::WORKER_REQUESTS => 500, default => null }; } /** * Get environment variable name * * @return string */ public function getEnvironmentVariable(): string { return "MCLOGS_" . $this->name; } /** * @return array */ public function getJSONPath(): array { $parts = explode("_", $this->name); return array_map(fn($part) => strtolower($part), $parts); } } ================================================ FILE: src/Data/Deobfuscator.php ================================================ codexLog instanceof AnalysableLog) { return null; } if (!$this->codexLog instanceof VanillaLog) { return null; } $analysis = $this->codexLog->analyse(); /** * @var ?Information $version */ $version = $analysis->getFilteredInsights(VanillaVersionInformation::class)[0] ?? null; if (!$version) { return null; } $version = $version->getValue(); try { $map = $this->getObfuscationMap($version); } catch (Exception) { $map = null; } if ($map === null) { return null; } $obfuscatedContent = new ObfuscatedString($this->codexLog->getLogFile()->getContent(), $map); if ($content = $obfuscatedContent->getMappedContent()) { return $content; } return null; } /** * Get the obfuscation map matching this log * * @param $version * @return ObfuscationMap|null * @throws Exception */ protected function getObfuscationMap($version): ?ObfuscationMap { if (in_array(get_class($this->codexLog), [ VanillaServerLog::class, VanillaClientLog::class, VanillaCrashReportLog::class, VanillaNetworkProtocolErrorReportLog::class ])) { $urlCache = new CacheEntry("sherlock:vanilla:$version:client"); $mapURL = $urlCache->get(); if (!$mapURL) { $mapURL = new LauncherMetaMapLocator($version, "client")->findMappingURL(); if (!$mapURL) { return null; } $urlCache->set($mapURL, 30 * 24 * 60 * 60); } try { $mapCache = new CacheEntry("sherlock:$mapURL"); if ($mapContent = $mapCache->get()) { $map = new VanillaObfuscationMap($mapContent); } else { $map = new URLVanillaObfuscationMap($mapURL); $mapCache->set($map->getContent()); } } catch (Exception) { } return $map ?? null; } if ($this->codexLog instanceof FabricLog) { $urlCache = new CacheEntry("sherlock:yarn:$version:server"); $mapURL = $urlCache->get(); if (!$mapURL) { $mapURL = new FabricMavenMapLocator($version)->findMappingURL(); if (!$mapURL) { return null; } $urlCache->set($mapURL, 24 * 60 * 60); } try { $mapCache = new CacheEntry("sherlock:$mapURL"); if ($mapContent = $mapCache->get()) { $map = new YarnMap($mapContent); } else { $map = new GZURLYarnMap($mapURL); $mapCache->set($map->getContent()); } } catch (Exception) { } return $map ?? null; } return null; } } ================================================ FILE: src/Data/MetadataEntry.php ================================================ = static::MAX_ENTRIES) { break; } } return $entries; } /** * @param array $data * @return MetadataEntry|null */ public static function fromArray(array $data): ?MetadataEntry { $entry = new MetadataEntry()->setFromArray($data); if (!$entry->isValid()) { return null; } return $entry; } /** * @param object $data * @return MetadataEntry|null */ public static function fromObject(object $data): ?MetadataEntry { if ($data instanceof BSONDocument) { $arrayData = $data->getArrayCopy(); } else { $arrayData = get_object_vars($data); } return static::fromArray($arrayData); } public function jsonSerialize(): array { return [ "key" => $this->key, "value" => $this->value, "label" => $this->label, "visible" => $this->visible, ]; } public function bsonSerialize(): array { return $this->jsonSerialize(); } public function getKey(): ?string { return $this->key; } public function setKey(?string $key): static { if (is_string($key) && strlen($key) > static::MAX_KEY_LENGTH) { $key = substr($key, 0, static::MAX_KEY_LENGTH); } $this->key = $key; return $this; } public function getValue(): mixed { return $this->value; } /** * @param mixed $value * @return $this */ public function setValue(mixed $value): static { if (is_string($value)) { if (strlen($value) > static::MAX_VALUE_LENGTH) { $value = substr($value, 0, static::MAX_VALUE_LENGTH); } $this->value = $value; return $this; } if (is_int($value) || is_float($value) || is_bool($value) || is_null($value)) { $this->value = $value; return $this; } $encodedValue = @json_encode($value); if ($encodedValue === false) { $this->value = null; return $this; } if (strlen($encodedValue) > static::MAX_VALUE_LENGTH) { $encodedValue = substr($encodedValue, 0, static::MAX_VALUE_LENGTH); } $this->value = $encodedValue; return $this; } public function getLabel(): ?string { return $this->label; } public function getDisplayLabel(): ?string { return $this->label ?? $this->key; } public function getDisplayValue(): string { return $this->value; } public function setLabel(?string $label): static { if (is_string($label) && strlen($label) > static::MAX_LABEL_LENGTH) { $label = substr($label, 0, static::MAX_LABEL_LENGTH); } $this->label = $label; return $this; } public function isVisible(): bool { return $this->visible; } public function setVisible(bool $visible): static { $this->visible = $visible; return $this; } public function isValid(): bool { return $this->key !== null && $this->value !== null; } /** * @param array $data * @return $this */ public function setFromArray(array $data): static { if (isset($data['key']) && is_string($data['key'])) { $this->setKey($data['key']); } if (isset($data['value'])) { $this->setValue($data['value']); } if (isset($data['label']) && is_string($data['label'])) { $this->setLabel($data['label']); } if (isset($data['visible']) && is_bool($data['visible'])) { $this->setVisible($data['visible']); } return $this; } } ================================================ FILE: src/Data/Token.php ================================================ value === null) { $this->generate(); } } /** * @param string $token * @return bool */ public function matches(string $token): bool { return hash_equals($this->value, $token); } public function jsonSerialize(): string { return $this->value; } /** * @throws RandomException */ protected function generate(): void { $this->value = bin2hex(random_bytes(32)); } public function get(): ?string { return $this->value; } } ================================================ FILE: src/Detective.php ================================================ addDetective(new \Aternos\Codex\Minecraft\Detective\Detective()) ->addDetective(new \Aternos\Codex\Hytale\Detective\Detective()); } } ================================================ FILE: src/Filter/AccessTokenFilter.php ================================================ filter($data); } return $data; } /** * @return FilterType */ abstract public function getType(): FilterType; /** * @return array */ abstract public function getData(): mixed; /** * @return array */ public function jsonSerialize(): array { return [ "type" => $this->getType()->value, "data" => $this->getData(), ]; } /** * Filter the $data string and return it * * @param string $data * @return string */ abstract public function filter(string $data): string; } ================================================ FILE: src/Filter/FilterType.php ================================================ get(ConfigKey::STORAGE_LIMIT_BYTES); return mb_strcut($data, 0, $lengthLimit); } /** * @return FilterType */ public function getType(): FilterType { return FilterType::LIMIT_BYTES; } /** * @return array */ public function getData(): array { return [ "limit" => Config::getInstance()->get(ConfigKey::STORAGE_LIMIT_BYTES) ]; } } ================================================ FILE: src/Filter/LimitLinesFilter.php ================================================ get(ConfigKey::STORAGE_LIMIT_LINES); return implode("\n", array_slice(explode("\n", $data), 0, $linesLimit)); } /** * @return FilterType */ public function getType(): FilterType { return FilterType::LIMIT_LINES; } /** * @return array */ public function getData(): array { return [ "limit" => Config::getInstance()->get(ConfigKey::STORAGE_LIMIT_LINES) ]; } } ================================================ FILE: src/Filter/Pattern/Modifier.php ================================================ value; } } ================================================ FILE: src/Filter/Pattern/Pattern.php ================================================ modifiers as $modifier) { $modifiersString .= $modifier->value; } return static::DELIMITER . $this->pattern . static::DELIMITER . $modifiersString; } public function getPattern(): string { return $this->pattern; } public function getModifiers(): array { return $this->modifiers; } public function jsonSerialize(): array { return [ 'pattern' => $this->getPattern(), 'modifiers' => $this->getModifiers() ]; } } ================================================ FILE: src/Filter/Pattern/PatternWithReplacement.php ================================================ replacement; } public function jsonSerialize(): array { return array_merge( parent::jsonSerialize(), [ 'replacement' => $this->getReplacement() ] ); } } ================================================ FILE: src/Filter/RegexFilter.php ================================================ $this->getPatterns(), "exemptions" => $this->getExemptions(), ]; } /** * @inheritDoc */ public function filter(string $data): string { foreach ($this->getPatterns() as $pattern) { $data = preg_replace_callback($pattern->get(), function ($matches) use ($pattern) { foreach ($this->getExemptions() as $exemptionPattern) { if (preg_match($exemptionPattern->get(), $matches[0])) { return $matches[0]; } } return $pattern->getReplacement(); }, $data); } return $data; } } ================================================ FILE: src/Filter/TrimFilter.php ================================================ toString(); } protected function shouldAllowCredentials(): bool { return true; } } ================================================ FILE: src/Frontend/Action/DeleteLogAction.php ================================================ toString(); } protected function shouldAllowCredentials(): bool { return true; } protected function getRequestToken(): ?string { return new TokenCookie()->getValue(); } protected function handleDeletedLog(Log $log): void { new TokenCookie()->setLog($log)->delete(); } } ================================================ FILE: src/Frontend/Action/FaviconAction.php ================================================ renew(); require __DIR__ . "/../../../web/frontend/log.php"; return true; } } ================================================ FILE: src/Frontend/Assets/Asset.php ================================================ type) || !isset($data->path) || !isset($data->hash)) { return null; } $type = AssetType::tryFrom($data->type); if ($type === null) { return null; } return new static($type, $data->path, $data->hash); } public function __construct( protected AssetType $type, protected string $path, protected ?string $hash = null) { $this->path = ltrim($this->path, '/'); } public function getPath(): string { return $this->path; } public function getPathWithVersion(): string { return $this->path . '?v=' . rawurlencode(substr($this->getHash(), 0, 16)); } protected function getAbsoluteBasePath(): string { return __DIR__ . "/../../../web/public/"; } protected function getAbsolutePath(): string { return $this->getAbsoluteBasePath() . $this->path; } protected function buildHash(): string { return hash_file(static::HASH_ALGORITHM, $this->getAbsolutePath()); } protected function getHash(): string { if ($this->hash === null) { return $this->buildHash(); } return $this->hash; } protected function getBase64Hash(): string { return base64_encode(hex2bin($this->getHash())); } public function jsonSerialize(): array { return [ 'type' => $this->getType()->value, 'path' => $this->getPath(), 'hash' => $this->getHash(), ]; } public function getType(): AssetType { return $this->type; } public function getHTML(): string { return match ($this->type) { AssetType::CSS => 'getIntegrityAttribute() . ' />', AssetType::JS => '' }; } protected function getIntegrityAttribute(): string { if (!Config::getInstance()->get(ConfigKey::FRONTEND_ASSETS_INTEGRITY)) { return ''; } return ' integrity="' . static::HASH_ALGORITHM . '-' . $this->getBase64Hash() . '"'; } } ================================================ FILE: src/Frontend/Assets/AssetLoader.php ================================================ loadCache(); } /** * @param AssetType $assetType * @param string $path * @return string */ public function getHTML(AssetType $assetType, string $path): string { return $this->getAsset($assetType, $path)->getHTML(); } /** * @param AssetType $assetType * @param string $path * @return Asset */ protected function getAsset(AssetType $assetType, string $path): Asset { $cachedAsset = $this->findCachedAsset($assetType, $path); if ($cachedAsset !== null) { return $cachedAsset; } return new Asset($assetType, $path); } /** * @param AssetType $assetType * @param string $path * @return Asset|null */ protected function findCachedAsset(AssetType $assetType, string $path): ?Asset { foreach ($this->cachedAssets as $asset) { if ($asset->getPath() === $path && $asset->getType() === $assetType) { return $asset; } } return null; } protected function loadCache(): void { if (!file_exists(self::CACHE_PATH)) { return; } $content = file_get_contents(self::CACHE_PATH); if ($content === false) { return; } $data = json_decode($content); if (!is_array($data)) { return; } foreach ($data as $assetData) { if (!is_object($assetData)) { continue; } $asset = Asset::fromObject($assetData); if ($asset === null) { continue; } $this->cachedAssets[] = $asset; } } public function writeCache(): void { $assets = [ new Asset(AssetType::CSS, "css/mclogs.css"), new Asset(AssetType::JS, "js/start.js"), new Asset(AssetType::JS, "js/log.js"), new Asset(AssetType::CSS, "vendor/fontawesome/css/fontawesome.min.css") ]; file_put_contents(static::CACHE_PATH, json_encode($assets)); } } ================================================ FILE: src/Frontend/Assets/AssetType.php ================================================ getScheme() === "https"; } /** * @return bool */ protected function isHttpOnly(): bool { return true; } /** * @return string */ protected function getSameSite(): string { return "Lax"; } public function __construct() { $this->value = $_COOKIE[$this->getKey()] ?? null; } /** * @param string $value * @return bool */ public function set(string $value): bool { $options = [ 'expires' => $this->getMaxAge() !== null ? time() + $this->getMaxAge() : 0, 'path' => $this->getPath(), 'domain' => $this->getDomain(), 'secure' => $this->isSecure(), 'httponly' => $this->isHttpOnly(), 'samesite' => $this->getSameSite() ]; $result = setcookie( $this->getKey(), $value, $options ); if ($result) { $this->value = $value; } return $result; } /** * @return bool */ public function delete(): bool { $options = [ 'expires' => time() - 3600, 'path' => $this->getPath(), 'domain' => $this->getDomain(), 'secure' => $this->isSecure(), 'httponly' => $this->isHttpOnly(), 'samesite' => $this->getSameSite() ]; $result = setcookie( $this->getKey(), '', $options ); if ($result) { $this->value = null; } return $result; } /** * @return string|null */ public function getValue(): ?string { return $this->value; } /** * @return bool */ public function exists(): bool { return $this->getValue() !== null; } } ================================================ FILE: src/Frontend/Cookie/SettingsCookie.php ================================================ log = $log; return $this; } /** * @inheritDoc */ protected function getKey(): string { return "MCLOGS_LOG_TOKEN"; } /** * @param Log|null $log */ public function __construct(protected ?Log $log = null) { parent::__construct(); } /** * @return string */ protected function getPath(): string { if (!$this->log) { return "/"; } return "/" . $this->log->getId()->get(); } protected function getMaxAge(): ?int { return Config::getInstance()->get(ConfigKey::STORAGE_TTL); } } ================================================ FILE: src/Frontend/FrontendRouter.php ================================================ register(Method::GET, "#^/$#", new Action\StartAction()) ->register(Method::GET, "#^/" . Id::PATTERN . "$#", new Action\ViewLogAction()) ->register(Method::POST, "#^/new$#", new Action\CreateLogAction()) ->register(Method::DELETE, "#^/" . Id::PATTERN . "$#", new Action\DeleteLogAction()) ->register(Method::GET, "#^/favicon\.svg$#", new Action\FaviconAction()) ->setDefaultAction(new Action\NotFoundAction()); } } ================================================ FILE: src/Frontend/Settings/Setting.php ================================================ "Full Width", Setting::NO_WRAP => "No Wrap", Setting::FLOATING_SCROLLBAR => "Floating Scrollbar", Setting::OVERFLOW => "Overflow" }; } /** * @return string|null */ function getBodyClass(): ?string { return match ($this) { Setting::FULL_WIDTH => "setting-full-width", Setting::NO_WRAP => "setting-no-wrap", Setting::FLOATING_SCROLLBAR => "setting-floating-scrollbar", Setting::OVERFLOW => "setting-overflow", default => null }; } } ================================================ FILE: src/Frontend/Settings/Settings.php ================================================ */ protected array $data = []; public function __construct() { $rawData = new SettingsCookie()->getValue(); if ($rawData) { $parsedData = json_decode($rawData, true); if (is_array($parsedData)) { $this->data = $parsedData; } } } /** * @param Setting $key * @return bool */ public function get(Setting $key): bool { $value = $this->data[$key->value] ?? false; if (is_bool($value)) { return $value; } return false; } /** * @return string[] */ public function getBodyClasses(): array { $classes = []; foreach (Setting::cases() as $setting) { if ($this->get($setting)) { $bodyClass = $setting->getBodyClass(); if ($bodyClass) { $classes[] = $bodyClass; } } } return $classes; } /** * @return string */ public function getBodyClassesString(): string { $classes = $this->getBodyClasses(); if (empty($classes)) { return ""; } return " " . implode(" ", $this->getBodyClasses()); } } ================================================ FILE: src/Id.php ================================================ id === null) { $this->generate(); } } /** * Generates a new id * * @return string */ protected function generate(): string { $config = \Aternos\Mclogs\Config\Config::getInstance(); $idLength = $config->get(ConfigKey::ID_LENGTH); $newId = ""; for ($i = 0; $i < $idLength; $i++) { $newId .= static::CHARACTERS[rand(0, strlen(static::CHARACTERS) - 1)]; } return $this->id = $newId; } /** * @return string */ public function get(): string { return $this->id; } /** * @return string */ public function __toString(): string { return $this->id; } public function jsonSerialize(): string { return $this->id; } } ================================================ FILE: src/Log.php ================================================ findLog($id, $includeContent); if ($data === null) { return null; } return static::fromObject($id, $data); } /** * @param (string|Id)[] $ids * @param bool $includeContent * @return array */ public static function findAll(array $ids, bool $includeContent = true): array { $ids = array_map(fn($id) => (string)$id, $ids); $objects = MongoDBClient::getInstance()->findLogs($ids, $includeContent); $logs = []; foreach ($objects as $data) { $id = new Id($data->_id); $logs[$id->get()] = static::fromObject($id, $data); } return $logs; } /** * @param Id $id * @param object $data * @return static */ protected static function fromObject(Id $id, object $data): static { return new static($id) ->setContent($data->data ?? "") ->setToken(isset($data->token) ? new Token($data->token) : null) ->setMetadata(MetadataEntry::allFromArray($data->metadata ?? [])) ->setSource($data->source ?? null) ->setCreated($data->created ?? null) ->setExpires($data->expires ?? null); } /** * Create and save a new log * * @param string $content * @param MetadataEntry[] $metadata * @param string|null $source * @return static */ public static function create(string $content, array $metadata = [], ?string $source = null): static { return new static() ->setMetadata($metadata) ->setSource($source) ->setToken(new Token()) ->save($content); } /** * @param Id|null $id */ public function __construct(protected ?Id $id = null) { } /** * @param Token|null $token * @return $this */ public function setToken(?Token $token): static { $this->token = $token; return $this; } /** * @param MetadataEntry[] $metadata * @return $this */ public function setMetadata(array $metadata): static { $this->metadata = $metadata; return $this; } /** * @param MetadataEntry $metadataEntry * @return $this */ public function addMetadata(MetadataEntry $metadataEntry): static { $this->metadata[] = $metadataEntry; return $this; } /** * @param string|null $source * @return $this */ public function setSource(?string $source): static { if (is_string($source) && strlen($source) > static::SOURCE_MAX_LENGTH) { $source = substr($source, 0, static::SOURCE_MAX_LENGTH); } $this->source = $source; return $this; } /** * @return string|null */ public function getSource(): ?string { return $this->source; } /** * @param UTCDateTime|null $created * @return $this */ public function setCreated(?UTCDateTime $created): static { $this->created = $created; return $this; } /** * @param UTCDateTime|null $expires * @return $this */ public function setExpires(?UTCDateTime $expires): static { $this->expires = $expires; return $this; } /** * @return UTCDateTime|null */ public function getCreated(): ?UTCDateTime { return $this->created; } /** * @return UTCDateTime|null */ public function getExpires(): ?UTCDateTime { return $this->expires; } /** * @param string $content * @return $this */ public function setContent(string $content): static { $this->processAndDeobfuscate($content); return $this; } public function getContent(): string { return $this->log->getLogFile()->getContent(); } protected function processAndDeobfuscate(string $data): void { $this->process($data); $deobfuscator = new Deobfuscator($this->getCodexLog()); if ($deobfuscatedData = $deobfuscator->deobfuscate()) { $this->process($deobfuscatedData); } } protected function process($data): void { $this->log = new Detective()->setLogFile(new StringLogFile($data))->detect(); $this->log->parse(); if ($this->log instanceof AnalysableLogInterface) { $this->log->analyse(); } } /** * Get the codex log object * * @return LogInterface */ public function getCodexLog(): LogInterface { return $this->log; } /** * Get the log analysis * * @return Analysis|null */ public function getAnalysis(): ?Analysis { $log = $this->getCodexLog(); if ($log instanceof AnalysableLogInterface) { return $log->analyse(); } return null; } /** * @return Printer */ public function getPrinter(): Printer { if ($this->printer === null) { $this->printer = new Printer()->setLog($this->log)->setId($this->id); } return $this->printer; } /** * Get the amount of lines in this log * * @return int */ public function getLinesCount(): int { $codexLog = $this->getCodexLog(); $lines = 0; foreach ($codexLog as $entry) { $lines += count($entry); } return $lines; } /** * @return string */ public function getLinesString(): string { $lineCount = $this->getLinesCount(); return $lineCount . ($lineCount === 1 ? " line" : " lines"); } /** * @return int */ public function getSize(): int { return strlen($this->getContent()); } /** * Get the amount of error entries in the log * * @return int */ public function getErrorsCount(): int { $errorCount = 0; foreach ($this->log as $entry) { if ($entry->getLevel()->asInt() <= Level::ERROR->asInt()) { $errorCount++; } } return $errorCount; } /** * @return bool */ public function hasErrors(): bool { return $this->getErrorsCount() > 0; } /** * @return string */ public function getErrorsString(): string { $errorCount = $this->getErrorsCount(); return $errorCount . ($errorCount === 1 ? " error" : " errors"); } protected function generateId(): Id { do { $this->id = new Id(); } while (MongoDBClient::getInstance()->hasLog($this->id)); return $this->id; } /** * Save the log to the database * * @return $this */ public function save(string $content): static { if ($this->id === null) { $this->generateId(); } $content = Filter::filterAll($content); MongoDBClient::getInstance()->getLogsCollection()->insertOne([ "_id" => $this->id->get(), "data" => $content, "token" => $this->token?->get(), "source" => $this->source, "metadata" => $this->metadata, "expires" => $this->expires = $this->getExpiryTimestamp(), "created" => $this->created = new UTCDateTime() ]); return $this->setContent($content); } /** * @return UTCDateTime */ protected function getExpiryTimestamp(): UTCDateTime { $ttl = \Aternos\Mclogs\Config\Config::getInstance()->get(ConfigKey::STORAGE_TTL); $expires = time() + $ttl; return new UTCDateTime($expires * 1000); } /** * Renew the expiry timestamp to expand the ttl * * @return bool */ public function renew(): bool { $expires = $this->getExpiryTimestamp(); $result = MongoDBClient::getInstance()->setLogExpires($this->id, $expires); if ($result) { $this->expires = $expires; } return $result; } /** * @return Uri */ public function getURL(): Uri { return URL::getBase()->withPath("/" . $this->id->get()); } /** * * @return string */ public function getDisplayURL(): string { $url = $this->getURL(); return $url->getHost() . $url->getPath(); } /** * @return Uri */ public function getRawURL(): Uri { return URL::getApi()->withPath("/1/raw/" . $this->id->get()); } /** * @return Id|null */ public function getId(): ?Id { return $this->id; } /** * @return Token|null */ public function getToken(): ?Token { return $this->token; } /** * @return bool */ public function delete(): bool { return MongoDBClient::getInstance()->deleteLog($this->id->get()); } /** * @return MetadataEntry[] */ public function getMetadata(): array { return $this->metadata; } /** * @return MetadataEntry[] */ public function getVisibleMetadata(): array { return array_filter($this->metadata, function (MetadataEntry $entry) { return $entry->isVisible(); }); } /** * @return bool */ public function setTokenCookie(): bool { if (!$this->getToken()) { return false; } return new TokenCookie($this)->set($this->getToken()->get()); } /** * @return bool */ public function hasValidTokenCookie(): bool { $tokenCookie = new TokenCookie(); $cookieValue = $tokenCookie->getValue(); if ($cookieValue === null || !$this->getToken()) { return false; } return $this->getToken()->matches($cookieValue); } /** * @return string */ public function getPageTitle(): string { return $this->getCodexLog()?->getTitle() . " [#" . $this->getId()?->get() . "]"; } /** * @return string */ public function getPageDescription(): string { $description = $this->getLinesString(); if ($this->hasErrors()) { $description .= " | " . $this->getErrorsString(); } $problems = $this->getAnalysis()->getProblems(); if (count($problems) > 0) { $problemString = "problems"; if (count($problems) === 1) { $problemString = "problem"; } $description .= " | " . count($problems) . " " . $problemString . " automatically detected"; } return $description; } } ================================================ FILE: src/Printer/FormatModification.php ================================================ addModification(new FormatModification()); } /** * @var Id */ protected Id $id; /** * @param Id $id * @return Printer */ public function setId(Id $id): static { $this->id = $id; return $this; } /** * @return string */ protected function printLog(): string { return '
' . parent::printLog() . '
'; } /** * @param EntryInterface|null $entry * @return string * @throws \Exception */ protected function printEntry(?EntryInterface $entry = null): string { $entry = $entry ?? $this->entry; /** @var Entry $entry */ $return = ''; $first = true; foreach ($entry as $line) { $entryClass = "entry-no-error"; if ($entry->getLevel()->asInt() <= Level::ERROR->asInt()) { $entryClass = "entry-error"; } $return .= '
'; $return .= ''; $return .= '
'; $lineString = $this->printLine($line); if ($entry->getPrefix() !== null) { $prefix = htmlentities($entry->getPrefix()); $lineString = str_replace($prefix, '' . $prefix . '', $lineString); } $return .= $lineString; $return .= '
'; $return .= '
'; $first = false; } return $return; } /** * @param LineInterface $line * @return string */ protected function printLine(LineInterface $line): string { return $this->runModifications(htmlentities($line->getText())) . PHP_EOL; } } ================================================ FILE: src/Router/Action.php ================================================ getMethod() !== $method) { return false; } return preg_match($this->getPattern(), $path) === 1; } /** * @return Method */ public function getMethod(): Method { return $this->method; } /** * @return string */ public function getPattern(): string { return $this->pattern; } /** * @return Action */ public function getAction(): Action { return $this->action; } } ================================================ FILE: src/Router/Router.php ================================================ routes[] = new Route($method, $pattern, $action); return $this; } /** * @param Action $defaultAction * @return $this */ public function setDefaultAction(Action $defaultAction): static { $this->defaultAction = $defaultAction; return $this; } /** * @return $this */ public function run(): static { $route = $this->findRoute(); if (!$route) { $this->defaultAction?->run(); return $this; } $result = $route->getAction()->run(); if (!$result) { $this->defaultAction?->run(); } return $this; } /** * @return Route|null */ protected function findRoute(): ?Route { $path = URL::getCurrent()->getPath(); $method = Method::getCurrent(); foreach ($this->routes as $route) { if ($route->matches($method, $path)) { return $route; } } return null; } } ================================================ FILE: src/Storage/MongoDBClient.php ================================================ get(ConfigKey::MONGODB_URL); $url = new Uri($configUrl); $query = $url->getQuery(); $queryParams = []; if ($query !== null) { parse_str($query, $queryParams); } if (!isset($queryParams['serverSelectionTimeoutMS'])) { $queryParams['serverSelectionTimeoutMS'] = 5_000; } if (!isset($queryParams['socketTimeoutMS'])) { $queryParams['socketTimeoutMS'] = 60_000; } $newQuery = http_build_query($queryParams); $newUrl = $url->withQuery($newQuery); return $newUrl->toString(); } /** * Connect to MongoDB */ protected function connect(): void { if ($this->connection === null) { $config = Config::getInstance(); $this->connection = new Client($this->getConnectionURL()); $this->database = $this->connection->getDatabase($config->get(ConfigKey::MONGODB_DATABASE)); } } /** * Ensure indexes exist * * @return void */ public function ensureIndexes(): void { $logs = $this->getLogsCollection(); $logs->createIndex(['expires' => 1], ['expireAfterSeconds' => 0]); $cache = $this->getCacheCollection(); $cache->createIndex(['expires' => 1], ['expireAfterSeconds' => 0]); } /** * @return void */ public function reset(): void { $this->connection = null; $this->logs = null; $this->cache = null; } /** * Get the collection for logs * * @return Collection */ public function getLogsCollection(): Collection { if ($this->logs === null) { $this->connect(); $this->logs = $this->database->getCollection('logs'); } return $this->logs; } /** * @param string $id * @param bool $includeContent * @return object|null */ public function findLog(string $id, bool $includeContent = true): ?object { $options = []; if (!$includeContent) { $options['projection'] = ['data' => 0]; } $collection = $this->getLogsCollection(); $result = $collection->findOne(['_id' => $id], $options); if ($result === null) { // Check for legacy ID without the first character return $collection->findOne(['_id' => substr($id, 1)], $options); } return $result; } /** * @param string[] $ids * @param bool $includeContent * @return object[] */ public function findLogs(array $ids, bool $includeContent = true): array { $options = []; if (!$includeContent) { $options['projection'] = ['data' => 0]; } $collection = $this->getLogsCollection(); $results = $collection->find(['_id' => ['$in' => $ids]], $options)->toArray(); $foundIds = []; foreach ($results as $result) { $foundIds[] = (string)$result->_id; } $missingIds = array_diff($ids, $foundIds); if (!empty($missingIds)) { $legacyIds = []; foreach ($missingIds as $id) { $legacyIds[substr($id, 1)] = $id; } // Check for legacy IDs without the first character $legacyResults = $collection->find(['_id' => ['$in' => array_keys($legacyIds)]], $options)->toArray(); foreach ($legacyResults as $result) { // Map the legacy ID back to the original ID $originalId = $legacyIds[(string)$result->_id]; $result->_id = $originalId; // Add the found legacy results to the main results array $results[] = $result; } } return $results; } /** * @param string $id * @return bool */ public function deleteLog(string $id): bool { $collection = $this->getLogsCollection(); $result = $collection->deleteOne(['_id' => $id]); if ($result->getDeletedCount() === 0) { // Check for legacy ID without the first character $result = $collection->deleteOne(['_id' => substr($id, 1)]); return $result->getDeletedCount() === 1; } return true; } /** * @param array $ids * @return int Number of logs deleted */ public function deleteLogs(array $ids): int { $collection = $this->getLogsCollection(); $result = $collection->deleteMany(['_id' => ['$in' => $ids]]); $deletedCount = $result->getDeletedCount(); if ($deletedCount === count($ids)) { return $deletedCount; } // Check for legacy IDs without the first character $legacyIds = []; foreach ($ids as $id) { $legacyIds[] = substr($id, 1); } $legacyResult = $collection->deleteMany(['_id' => ['$in' => $legacyIds]]); return $deletedCount + $legacyResult->getDeletedCount(); } /** * @param string $id * @return bool */ public function hasLog(string $id): bool { return $this->findLog($id) !== null; } /** * @param string $id * @param UTCDateTime $expires * @return bool */ public function setLogExpires(string $id, UTCDateTime $expires): bool { $collection = $this->getLogsCollection(); $result = $collection->updateOne( ['_id' => $id], ['$set' => ['expires' => $expires]] ); return $result->getModifiedCount() === 1; } /** * Get the collection for caching * * @return Collection */ public function getCacheCollection(): Collection { if ($this->cache === null) { $this->connect(); $this->cache = $this->database->getCollection('cache'); } return $this->cache; } } ================================================ FILE: src/Util/Singleton.php ================================================ 365 * 24 * 60 * 60, "month" => 30 * 24 * 60 * 60, "week" => 7 * 24 * 60 * 60, "day" => 24 * 60 * 60, "hour" => 60 * 60, "minute" => 60, "second" => 1, ]; /** * @param int $value * @param string $unit * @return string */ protected function formatUnit(int $value, string $unit): string { if ($value === 1) { return $value . " " . $unit; } else { return $value . " " . $unit . "s"; } } /** * @param int $duration * @param string $separator * @return string */ public function format(int $duration, string $separator = ", "): string { $parts = []; while ($duration > 0) { foreach (self::UNITS as $unit => $seconds) { if ($duration >= $seconds) { $value = intdiv($duration, $seconds); $duration -= $value * $seconds; $parts[] = $this->formatUnit($value, $unit); break; } } } return implode($separator, $parts); } } ================================================ FILE: src/Util/URL.php ================================================ withHost(static::API_SUBDOMAIN . $base->getHost()); } /** * @return Uri */ public static function getCurrent(): Uri { if (static::$current) { return static::$current; } $scheme = $_SERVER['REQUEST_SCHEME']; $host = $_SERVER['HTTP_HOST']; $requestUri = $_SERVER['REQUEST_URI']; return static::$current = new Uri("$scheme://$host$requestUri"); } /** * @return bool */ public static function isApi(): bool { $currentHost = static::getCurrent()->getHost(); $apiHost = static::getApi()->getHost(); return $currentHost === $apiHost; } /** * @return string */ public static function getLastPathPart(): string { $path = static::getCurrent()->getPath(); $parts = explode("/", $path); do { $part = trim(array_pop($parts)); } while ($part === "" && count($parts) > 0); return $part; } } ================================================ FILE: web/frontend/404.php ================================================ 404 - Page not found
404
Page not found

The log you're looking for doesn't exist or has expired.

Back to Home
================================================ FILE: web/frontend/api-docs.php ================================================ API Documentation - <?= htmlspecialchars($config->getName()); ?>

API Documentation

Integrate getName()); ?> directly into your server panel, your hosting software or anything else. This platform was built for high performance automation and can easily be integrated into any existing software via our HTTP API.

Create a log

POST withPath("/1/log")->toString()); ?> application/json
Posting content with the content type application/x-www-form-urlencoded is still supported for backwards compatibility, but does not support setting metadata.
Field Required Type Description
content string The raw log file content as string. Limited to get(ConfigKey::STORAGE_LIMIT_BYTES) / 1024 / 1024, 2); ?> MiB and get(ConfigKey::STORAGE_LIMIT_LINES)); ?> lines. Will be truncated if possible and necessary, but truncating on the client side is recommended.
source string The name of the source, e.g. a domain or software name.
metadata array An array of metadata entries.

Example body application/json

{
    "content": "[log file content...]",
    "source": "example.org"
}

Metadata

You can send metadata alongside the log content to be displayed on the log page and/or be read by other applications through this API. This is entirely optional, but can help to provide additional context, e.g. internal server IDs, software versions etc.

A metadata entry is an object with the following fields:

Field Required Type Description
key string The metadata key. Can be used to identify the entry in your code later.
value string|int|float|bool|null The metadata value.
label string The display label. If not provided, the key will be used as label.
visible bool Whether this metadata should be visible on the log page or is only available through the API. Default is true.

Example body with metadata application/json

{
    "content": "[log file content...]",
    "source": "example.org",
    "metadata": [
        {
            "key": "server_id",
            "value": 12345,
            "visible": false
        },
        {
            "key": "software_version",
            "value": "1.2.3",
            "label": "Software Version",
            "visible": true
        }
    ]
}

Responses

Success application/json

The token provided in this response can be used to delete this log later. Store or discard it securely, it will not be shown again.
{
    "success":true,
    "id":"WnMMikq",
    "source":null,
    "created":1769597979,
    "expires":1777373979,
    "size":157369,
    "lines":1201,
    "errors":8,
    "url": "withPath("/WnMMikq")->toString()); ?>",
    "raw": "withPath("/1/raw/WnMMikq")->toString()); ?>",
    "token":"78351fafe495398163fff847f9a26dda440435dcf7b5f92e8e36308f3683d771",
    "metadata": [
        {
            "key": "server_id",
            "value": 12345,
            "visible": false
        },
        {
            "key": "software_version",
            "value": "1.2.3",
            "label": "Software Version",
            "visible": true
        }
    ]
}

Error application/json

{
    "success": false,
    "error": "Required field 'content' not found."
}

Get log info and content

GET toString()); ?>/1/log/[id]

This endpoint only returns the log info and metadata by default (same response as creating a log), you can also get the content in the same request by enabling it in different formats using GET parameters. You can combine multiple parameters to get multiple content formats in one request, but keep in mind that this will increase the response size.

GET Parameter Response field Description
raw content.raw Includes the raw log content as string in the response.
parsed content.parsed Includes the parsed log content as array/objects in the response.
insights content.insights Includes the automatically detected insights in the response.

Responses

Success application/json

All content fields are only included if the corresponding GET parameter is provided. If no content parameter is provided, the entire content object is omitted from the response.
{
    "success":true,
    "id":"WnMMikq",
    "source":null,
    "created":1769597979,
    "expires":1777373979,
    "size":157369,
    "lines":1201,
    "errors":8,
    "url": "withPath("/WnMMikq")->toString()); ?>",
    "raw": "withPath("/1/raw/WnMMikq")->toString()); ?>",
    "metadata": [
        {
            "key": "server_id",
            "value": 12345,
            "visible": false
        },
        {
            "key": "software_version",
            "value": "1.2.3",
            "label": "Software Version",
            "visible": true
        }
    ],
    "content": {
        "raw": "[log file content...]",
        "parsed": [ /* parsed log entries */ ],
        "insights": { "problems": [ /* detected problems */ ], "information": [ /* detected information */ ] }
    }
}

Error application/json

{
    "success": false,
    "error": "Log not found."
}

Delete a log

Deleting a log requires the token that was provided when creating the log.
DELETE toString()); ?>/1/log/[id]

Headers

Header Example Description
Authorization Authorization: Bearer 78351fafe495398163f... The type (always "Bearer") and the log token received when creating the log.

Responses

Success application/json

{
    "success": true
}

Error application/json

{
    "success": false,
    "error": "Invalid token."
}

Bulk delete multiple logs

This method allows deleting up to at once. Deleting logs requires the tokens that were provided when the logs were created.
POST toString()); ?>/1/bulk/log/delete

Example body application/json

 "6wexMDE",
                                        "token" => "78351fafe495398163fff847f9a26dda440435dcf7b5f92e8e36308f3683d771"
                                ],
                                [
                                        "id" => "OahzhMG",
                                        "token" => "6520dd42ec3d5fd0e83f28220974fb83d3bdc0746853f5022373f8e5b062651b"
                                ],
                        ], JSON_PRETTY_PRINT); ?>

Responses

Success application/json

The bulk delete request will return a successful result and status code 207, indicating that the request was processed. Results for the individual operations are included in the response body.
addResponse("6wexMDE", new ApiResponse())
                                ->addResponse("OahzhMG", new ApiResponse()), JSON_PRETTY_PRINT); ?>

Partial success application/json

If a bulk delete request is valid, but not all logs can be deleted (e.g. due to invalid tokens or non-existing logs), it will still overall be considered successful, but the response body will include error results for the logs that could not be deleted.
addResponse("6wexMDE", new ApiResponse())
                                ->addResponse("OahzhMG", new ApiError(404, "Log not found.")), JSON_PRETTY_PRINT); ?>

Error application/json

If a bulk delete request is malformed or invalid, the entire request will be rejected with an error response and no logs will be deleted.
{
    "success": false,
    "error": "No logs provided."
}

Get the raw log file content

Only use this endpoint if you really only need the raw log content. For most use cases, getting the log info and content together from the log endpoint is recommended.
GET toString()); ?>/1/raw/[id]
Field Type Description
[id] string The log file id, received from the paste endpoint or from a URL (toString()); ?>/[id]).

Success text/plain

[18:25:33] [Server thread/INFO]: Starting minecraft server version 1.16.2
[18:25:33] [Server thread/INFO]: Loading properties
[18:25:34] [Server thread/INFO]: Default game type: SURVIVAL
...

Error application/json

{
    "success": false,
    "error": "Log not found."
}

Get insights

This endpoint is mainly kept for backwards compatibility. For new applications, getting the insights together with the log info from the log endpoint is recommended.
GET toString()); ?>/1/insights/[id]
Field Type Description
[id] string The log file id, received from the paste endpoint or from a URL (toString()); ?>/[id]).

Success application/json

{
  "id": "name/type",
  "name": "Software name, e.g. Vanilla",
  "type": "Type name, e.g. Server Log",
  "version": "Version, e.g. 1.12.2",
  "title": "Combined title, e.g. Vanilla 1.12.2 Server Log",
  "analysis": {
    "problems": [
      {
        "message": "A message explaining the problem.",
        "counter": 1,
        "entry": {
          "level": 6,
          "time": null,
          "prefix": "The prefix of this entry, usually the part containing time and loglevel.",
          "lines": [
            {
              "number": 1,
              "content": "The full content of the line."
            }
          ]
        },
        "solutions": [
          {
            "message": "A message explaining a possible solution."
          }
        ]
      }
    ],
    "information": [
      {
        "message": "Label: value",
        "counter": 1,
        "label": "The label of this information, e.g. Minecraft version",
        "value": "The value of this information, e.g. 1.12.2",
        "entry": {
          "level": 6,
          "time": null,
          "prefix": "The prefix of this entry, usually the part containing time and loglevel.",
          "lines": [
            {
              "number": 6,
              "content": "The full content of the line."
            }
          ]
        }
      }
    ]
  }
}

Error application/json

{
    "success": false,
    "error": "Log not found."
}

Analyse a log without saving it

If you only want to use the analysis features of this service without saving the log, you can use this endpoint. Please do not save logs that you only want to analyse, as this wastes storage space and resources.

POST withPath("/1/analyse")->toString()); ?> application/x-www-form-urlencoded application/json
Field Type Description
content string The raw log file content as string. Maximum length is 10MiB and 25k lines, will be shortened if necessary.

Success application/json

{
  "id": "name/type",
  "name": "Software name, e.g. Vanilla",
  "type": "Type name, e.g. Server Log",
  "version": "Version, e.g. 1.12.2",
  "title": "Combined title, e.g. Vanilla 1.12.2 Server Log",
  "analysis": {
    "problems": [
      {
        "message": "A message explaining the problem.",
        "counter": 1,
        "entry": {
          "level": 6,
          "time": null,
          "prefix": "The prefix of this entry, usually the part containing time and loglevel.",
          "lines": [
            {
              "number": 1,
              "content": "The full content of the line."
            }
          ]
        },
        "solutions": [
          {
            "message": "A message explaining a possible solution."
          }
        ]
      }
    ],
    "information": [
      {
        "message": "Label: value",
        "counter": 1,
        "label": "The label of this information, e.g. Minecraft version",
        "value": "The value of this information, e.g. 1.12.2",
        "entry": {
          "level": 6,
          "time": null,
          "prefix": "The prefix of this entry, usually the part containing time and loglevel.",
          "lines": [
            {
              "number": 6,
              "content": "The full content of the line."
            }
          ]
        }
      }
    ]
  }
}

Error application/json

{
    "success": false,
    "error": "Required field 'content' is empty."
}

Check storage limits

GET withPath("/1/limits")->toString()); ?>

Success application/json

{
  "storageTime": 7776000,
  "maxLength": 10485760,
  "maxLines": 25000
}
Field Type Description
storageTime integer The duration in seconds that a log is stored for after the last view.
maxLength integer Maximum file length in bytes. Logs over this limit will be truncated to this length.
maxLines integer Maximum number of lines. Additional lines will be removed.

Get filters

Filters modify the log content before storing it. They are applied automatically when creating a new log on the server side. You can get a list of active filters from this endpoint if you want to apply the same filters on the client side before uploading a log.

GET withPath("/1/filters")->toString()); ?>

Success application/json

Filter types

Type Description
trim Trim any whitespace characters from the beginning and end of the log content.
limit-bytes Limit the log content to a maximum number of bytes (data.limit). Content exceeding this limit will be truncated.
limit-lines Limit the log content to a maximum number of lines (data.limit). Additional lines will be removed.
regex Apply regular expression replacements to the log content. Each pattern in data.patterns will be applied in order and replaced with the provided replacement, unless the matched string matches one of the exemption patterns in data.exemptions.
Make sure to handle any filter error, e.g. unknown filter types gracefully, as new filter types may be added in the future.

Notes

The API has currently a rate limit of 60 requests per minute per IP address. This is set to ensure the operability of this service. If you have any use case that requires a higher limit, feel free to contact us.

================================================ FILE: web/frontend/log.php ================================================ <?=htmlspecialchars($log->getPageTitle()); ?>

getCodexLog()->getTitle()); ?>

hasErrors()): ?>
getErrorsString()); ?>
getLinesString()); ?>
Raw
getAnalysis()->getInformation(); ?> getVisibleMetadata()) > 0 || count($information) > 0): ?>
getVisibleMetadata()) > 0): ?>
Metadata
getVisibleMetadata() as $metadata): ?> getDisplayLabel()); ?>: getDisplayValue()); ?>
0): ?>
Detected
getLabel()); ?>: getValue()); ?>
getAnalysis()?->getProblems(); ?> 0): ?>
detected
getEntry()[0]->getNumber(); ?>
" class="problem-entry" onclick="updateLineNumber('#L');"> Problem getMessage()); ?> Line getSolutions()) > 0): ?>
getSolutions()) === 1 ? 'Solution:' : 'Solutions:'; ?> getSolutions() as $solution): ?>
$1'", htmlspecialchars($solution->getMessage())); ?>
getPrinter()->print(); ?>
getHTML(AssetType::JS, "js/log.js"); ?> ================================================ FILE: web/frontend/parts/favicon.php ================================================ ================================================ FILE: web/frontend/parts/footer.php ================================================ get(ConfigKey::LEGAL_IMPRINT); $privacyUrl = Config::getInstance()->get(ConfigKey::LEGAL_PRIVACY); ?> ================================================ FILE: web/frontend/parts/head.php ================================================ getHTML(AssetType::CSS, "vendor/fontawesome/css/fontawesome.min.css"); ?> getHTML(AssetType::CSS, "css/mclogs.css"); ?> toString()); ?>" type="image/svg+xml"> get(ConfigKey::FRONTEND_ANALYTICS)): ?> ================================================ FILE: web/frontend/parts/header.php ================================================

Paste your logs.

Built for Minecraft & Hytale
================================================ FILE: web/frontend/start.php ================================================ <?= htmlspecialchars(Config::getInstance()->getName()); ?> - Paste, share & analyse your logs

Paste or drop your log here

Drop
getHTML(AssetType::JS, "js/start.js"); ?> ================================================ FILE: web/public/css/mclogs.css ================================================ /* plus-jakarta-sans-regular - latin */ @font-face { font-display: swap; font-family: 'Plus Jakarta Sans'; font-style: normal; font-weight: 400; src: url('../vendor/fonts/plus-jakarta-sans-v12-latin-regular.woff2') format('woff2'); } /* plus-jakarta-sans-500 - latin */ @font-face { font-display: swap; font-family: 'Plus Jakarta Sans'; font-style: normal; font-weight: 500; src: url('../vendor/fonts/plus-jakarta-sans-v12-latin-500.woff2') format('woff2'); } /* plus-jakarta-sans-600 - latin */ @font-face { font-display: swap; font-family: 'Plus Jakarta Sans'; font-style: normal; font-weight: 600; src: url('../vendor/fonts/plus-jakarta-sans-v12-latin-600.woff2') format('woff2'); } /* jetbrains-mono-regular - cyrillic_cyrillic-ext_greek_latin_latin-ext_vietnamese */ @font-face { font-display: swap; font-family: 'JetBrains Mono'; font-style: normal; font-weight: 400; src: url('../vendor/fonts/jetbrains-mono-v24-cyrillic_cyrillic-ext_greek_latin_latin-ext_vietnamese-regular.woff2') format('woff2'); } /* jetbrains-mono-italic - cyrillic_cyrillic-ext_greek_latin_latin-ext_vietnamese */ @font-face { font-display: swap; font-family: 'JetBrains Mono'; font-style: italic; font-weight: 400; src: url('../vendor/fonts/jetbrains-mono-v24-cyrillic_cyrillic-ext_greek_latin_latin-ext_vietnamese-italic.woff2') format('woff2'); } /* jetbrains-mono-700 - cyrillic_cyrillic-ext_greek_latin_latin-ext_vietnamese */ @font-face { font-display: swap; font-family: 'JetBrains Mono'; font-style: normal; font-weight: 700; src: url('../vendor/fonts/jetbrains-mono-v24-cyrillic_cyrillic-ext_greek_latin_latin-ext_vietnamese-700.woff2') format('woff2'); } /* jetbrains-mono-700italic - cyrillic_cyrillic-ext_greek_latin_latin-ext_vietnamese */ @font-face { font-display: swap; font-family: 'JetBrains Mono'; font-style: italic; font-weight: 700; src: url('../vendor/fonts/jetbrains-mono-v24-cyrillic_cyrillic-ext_greek_latin_latin-ext_vietnamese-700italic.woff2') format('woff2'); } :root { --bg-surface: color-mix(in srgb, var(--bg) 92%, var(--text) 8%); --bg-elevated: color-mix(in srgb, var(--bg) 95%, var(--text) 5%); --bg-inset: var(--bg-surface); --text-muted: color-mix(in srgb, var(--text) 55%, var(--bg) 45%); --accent-hover: color-mix(in srgb, var(--accent) 78%, var(--bg) 22%); --accent-bg: color-mix(in srgb, var(--accent) 12%, transparent); --accent-border: var(--accent); --error-bg: color-mix(in srgb, var(--error) 10%, transparent); --error-border: color-mix(in srgb, var(--error) 40%, transparent); --border: rgba(255, 255, 255, 0.08); --surface: rgba(255, 255, 255, 0.04); --font-sans: 'Plus Jakarta Sans', system-ui, sans-serif; --font-mono: 'JetBrains Mono', 'Fira Code', monospace; --max-width: 1400px; --page-padding: clamp(1rem, 2.5vw, 1.25rem); --max-width-content: min(100%, calc(var(--max-width)) - var(--page-padding) * 2); --radius: 12px; --scrollbar-height: 8px; --browser: unset; scroll-behavior: smooth; } @view-transition { navigation: auto; } /* Global scrollbar styling */ *::-webkit-scrollbar { width: 8px; height: var(--scrollbar-height); } *::-webkit-scrollbar-track { background: transparent; } *::-webkit-scrollbar-thumb { background-color: var(--accent); border-radius: 4px; } *::-webkit-scrollbar-thumb:hover { background-color: var(--accent-hover); } ::selection { background-color: var(--accent); color: var(--text); } * { margin: 0; padding: 0; box-sizing: border-box; scrollbar-color: var(--accent) transparent; } html { height: 100%; text-size-adjust: 100%; -webkit-text-size-adjust: 100%; } body { font-family: var(--font-sans), system-ui, sans-serif; background-color: var(--bg); color: var(--text); line-height: 1.5; min-height: 100%; display: flex; flex-direction: column; position: relative; font-weight: 400; } /* Log Settings */ body.setting-full-width { --max-width: 100%; --max-width-content: calc(100% - var(--page-padding) * 2); } body.setting-overflow .log-container { max-width: unset; min-width: 100%; } body.setting-no-wrap .log-inner { white-space: pre; } body.setting-no-wrap .log-inner .line-content { word-break: normal; overflow-wrap: normal; } body.setting-no-wrap .log-inner .level { white-space: pre; } body.setting-no-wrap .log-inner .collapsed-lines-count { justify-content: flex-start; } a { color: inherit; text-decoration: none; transition: color 0.15s ease; } a:hover:not(.btn) { color: var(--accent); } body::before { content: ''; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-image: linear-gradient(color-mix(in srgb, var(--text-muted) 5%, var(--bg) 95%) 1px, transparent 1px), linear-gradient(90deg, color-mix(in srgb, var(--text-muted) 5%, var(--bg) 95%) 1px, transparent 1px); background-size: 40px 40px; pointer-events: none; z-index: 0; } /** Buttons **/ .btn { background-color: var(--accent); color: var(--bg); font-family: inherit; font-size: clamp(0.85rem, 2vw, 0.9rem); font-weight: 600; cursor: pointer; display: flex; align-items: center; border: 2px solid transparent; padding: clamp(0.6rem, 2vw, 0.7rem) clamp(1.2rem, 3vw, 1.5rem); border-radius: 8px; gap: .4rem; line-height: 1; transition: color .15s ease, background-color .15s ease, border-color .15s ease; } .btn:hover:not(:disabled) { background-image: linear-gradient(#00000014,#00000014); } .btn:disabled, .btn.disabled { opacity: 0.5; cursor: not-allowed; } .btn-small { font-size: clamp(0.75rem, 1.8vw, 0.8rem); padding: clamp(0.35rem, 1.5vw, 0.4rem) clamp(0.85rem, 2.5vw, 1rem); } .btn-transparent { background-color: transparent; color: var(--accent); border: 0 none; } .btn-transparent:hover { color: var(--accent); } .btn-danger { background-color: var(--error); color: var(--text); } #error-toggle { cursor: pointer; transition: background-color 0.15s ease, color 0.15s ease, border-color 0.15s ease; } #error-toggle.toggled { background-color: var(--error-bg); color: var(--text); border-color: var(--error); } #error-toggle.toggled:hover { background-color: var(--error-bg); } .btn-white { background-color: #fff; color: var(--bg); } .btn-dark { background-color: var(--surface); color: var(--text); border-color: var(--border); } /** Header **/ header { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; width: 100%; max-width: var(--max-width); margin: 0 auto; padding: clamp(1rem, 3vw, 2rem) var(--page-padding); position: relative; z-index: 1; transition: max-width .25s ease; } .logo { view-transition-name: logo; display: flex; align-items: center; gap: .9rem; text-decoration: none; transition: transform 0.15s cubic-bezier(0.4, 0, 0.2, 1); transform-origin: center; } .logo:active { transform: scale(.9); } .logo-icon { height: clamp(1.5rem, 3vw, 2rem); width: auto; margin-top: 3px; color: var(--accent); } .logo-text { font-size: clamp(1.75rem, 3vw, 2rem); font-weight: 600; color: var(--text); margin-top: -3px; } .tagline { display: flex; flex-direction: column; gap: 0.25rem; text-align: right; } .tagline-main { font-size: clamp(1rem, 3vw, 1.5rem); color: var(--text); font-weight: 400; } .tagline-sub { font-size: clamp(0.75rem, 2vw, 1rem); color: var(--text-muted); } .title-verb { font-weight: 600; color: var(--accent); } /** Footer **/ footer { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 1rem; color: var(--text-muted); font-size: clamp(0.75rem, 2vw, 0.9rem); max-width: var(--max-width); width: 100%; margin: 0 auto; padding: clamp(1rem, 3vw, 2rem) clamp(1rem, 2.5vw, 1.25rem); position: relative; z-index: 1; transition: max-width .25s ease; } .legal { display: flex; align-items: center; gap: 0.5rem; } .footer-nav { display: flex; gap: 1.5rem; } .footer-nav a { color: var(--text-muted); display: flex; align-items: center; gap: 0.5rem; } .footer-nav a:hover { color: var(--accent); } .footer-nav a i { font-size: clamp(0.9rem, 2vw, 1rem); } .footer-text a { color: var(--text-muted); } .footer-text a:hover { color: var(--accent); } /** Main **/ main { max-width: var(--max-width-content); width: 100%; margin: 0 auto; flex: 1; display: flex; flex-direction: column; background-color: var(--bg-surface); border-radius: var(--radius); position: relative; overflow: hidden; z-index: 1; transition: max-width .25s ease; } .paste-area { flex: 1; width: 100%; display: flex; flex-direction: column; border-radius: var(--radius); position: relative; transition: background-color 0.25s ease, border-color 0.25s ease; border: 2px dashed transparent; } .paste-area::after { content: ''; position: absolute; bottom: 0; left: 0; right: 0; height: 120px; background: linear-gradient(to bottom, transparent 0%, color-mix(in srgb, var(--bg-surface) 40%, transparent) 40%, color-mix(in srgb, var(--bg-surface) 80%, transparent) 70%, var(--bg-surface) 100%); pointer-events: none; z-index: 5; border-radius: 0 0 var(--radius) var(--radius); } .paste-area.dragover, .paste-area.window-dragover { background-color: color-mix(in srgb, var(--bg-surface) 90%, var(--accent) 10%); border-color: var(--accent); } .paste-area.dragover .paste-placeholder i.fa-cloud-arrow-up, .paste-area.window-dragover .paste-placeholder i.fa-cloud-arrow-up { color: var(--accent); transform: scale(1.1) translateY(-4px); } .paste-area.dragover .paste-placeholder p, .paste-area.window-dragover .paste-placeholder p { color: var(--accent); } .paste-placeholder { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; justify-content: center; flex-direction: column; align-items: center; z-index: 2; font-size: clamp(1rem, 3vw, 1.5rem); } .paste-placeholder i.fa-cloud-arrow-up { font-size: clamp(2rem, 8vw, 3.5rem); color: var(--text-muted); margin-bottom: clamp(0.5rem, 2vw, 1.5rem); transition: color 0.25s ease, transform 0.25s ease; } .paste-placeholder p { color: var(--text); margin-bottom: clamp(1.2rem, 2vw, 1.5rem); transition: color 0.25s ease; font-weight: 600; } .paste-hints { display: flex; gap: clamp(1rem, 3vw, 1.5rem); justify-content: center; color: var(--text-muted); font-size: clamp(0.75rem, 1.8vw, 0.8rem); } .paste-hints span, .paste-hints button { display: flex; align-items: center; gap: 0.5rem; font-size: clamp(0.75rem, 1.8vw, 0.8rem); } .paste-hints button { background: none; border: none; padding: 0; color: var(--text-muted); font-weight: 400; } .paste-hints button.btn:hover { background-image: none; } .paste-hints i { font-size: clamp(0.85rem, 2vw, 0.9rem); } .paste-area .btn-save { position: absolute; bottom: 1.5rem; left: 50%; transform: translateX(-50%); width: fit-content; z-index: 10; font-size: clamp(1rem, 2.5vw, 1.1rem); padding: 0.85rem 2rem; } .paste-area .btn-save:not(:disabled) { box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); animation: btn-save-pulse 1.5s ease-in-out infinite; } @keyframes btn-save-pulse { 0% { box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15), 0 0 0 0 color-mix(in srgb, var(--accent) 80%, transparent); } 70% { box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15), 0 0 0 12px color-mix(in srgb, var(--accent) 0%, transparent); } 100% { box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15), 0 0 0 0 color-mix(in srgb, var(--accent) 0%, transparent); } } .paste-area textarea { view-transition-name: log; flex: 1; width: 100%; background: transparent; border: none; outline: none; resize: none; padding: clamp(.5rem, 3vw, 1.2rem); font-family: var(--font-mono), monospace; font-size: clamp(0.75rem, 2vw, 0.9rem); color: var(--text); position: relative; } .paste-error { display: none; position: absolute; top: clamp(1rem, 2.5vw, 1.5rem); right: clamp(1rem, 2.5vw, 1.5rem); color: var(--error); font-weight: 600; font-size: clamp(0.85rem, 2vw, 0.9rem); padding: clamp(0.7rem, 2vw, 0.8rem) clamp(1rem, 2.5vw, 1.25rem); background-color: var(--error-bg); border: 1px solid var(--error-border); border-radius: 8px; z-index: 1000; animation: error-slide-in 0.3s ease-out; } .paste-error.show { display: block; } @keyframes error-slide-in { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } } /** Log Page Layout **/ .log-body main { flex: 0 0 auto; border-radius: var(--radius) var(--radius) 0 0; } .log-container { max-width: var(--max-width-content); min-width: var(--max-width-content); margin: 0 auto; background-color: var(--bg-surface); position: relative; z-index: 1; transition: max-width .25s ease, min-width .25s ease; } .log-footer { max-width: var(--max-width-content); width: 100%; margin: 0 auto; padding: 0 var(--page-padding); background-color: var(--bg-surface); border-radius: 0 0 var(--radius) var(--radius); position: relative; z-index: 1; transition: max-width .25s ease; } /** Log Header **/ .log-header { padding: clamp(1rem, 3vw, 1.5rem) var(--page-padding); border-bottom: 1px solid var(--border); } .log-header-inner { display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 1rem; } .log-header .left { flex: 1 1 300px; min-width: 0; } .log-header .right { flex-shrink: 0; } .log-header .log-title h1 { font-size: clamp(1.1rem, 3vw, 1.25rem); font-weight: 600; color: var(--text); display: flex; align-items: center; gap: 0.5rem; line-height: 1.3; flex-wrap: wrap; } .log-header .log-title h1 i { color: var(--accent); } .log-header .log-title { display: flex; align-items: center; gap: 0.75rem; flex-wrap: wrap; } .log-header .log-title-actions { display: flex; align-items: center; gap: 0.5rem; } .log-header .log-url-btn { display: inline-flex; align-items: center; gap: 0.4rem; padding: clamp(0.2rem, 1vw, 0.25rem) clamp(0.4rem, 1.5vw, 0.5rem); background-color: var(--surface); border: 1px solid var(--border); border-radius: 6px; font-size: clamp(0.7rem, 1.8vw, 0.75rem); color: var(--text-muted); font-family: var(--font-mono), monospace; line-height: 1; transition: border-color 0.15s ease, background-color 0.15s ease, color 0.15s ease; vertical-align: middle; cursor: pointer; } .log-header .log-url-btn:hover { border-color: var(--accent-border); background-color: var(--accent-bg); color: var(--text); } .log-header .log-url-btn i { font-size: 0.85em; opacity: 0.5; color: var(--accent); } .log-info-rows { display: flex; flex-direction: column; gap: 0.5rem; margin-top: 1rem; } .log-info-row { padding: clamp(0.4rem, 1.5vw, 0.5rem) clamp(0.6rem, 2vw, 0.75rem); background-color: var(--surface); border-radius: 6px; } .info-row-header { display: flex; align-items: center; gap: 0.4rem; font-size: clamp(0.7rem, 1.8vw, 0.75rem); font-weight: 600; color: var(--text-muted); letter-spacing: 0.03em; padding-right: clamp(0.6rem, 2vw, 0.75rem); border-right: 1px solid var(--border); } .info-row-header i { font-size: 0.7rem; opacity: 0.8; } .info-row-items { display: flex; flex-wrap: wrap; align-items: center; gap: 0.75rem; } .info-item { display: inline-flex; align-items: center; gap: 0.4rem; font-size: clamp(0.75rem, 1.8vw, 0.8rem); color: var(--text-muted); } .info-label { font-weight: 500; } .info-value { color: var(--text); font-weight: 500; font-family: var(--font-mono), monospace; } .log-header .details { display: flex; align-items: center; } .log-header .log-info-actions { display: flex; gap: 0.5rem; flex-wrap: wrap; align-items: center; } /** Problems Panel **/ .problems-panel-container { border-top: 1px solid var(--border); padding-top: clamp(0.75rem, 2vw, 1rem); margin-top: clamp(0.75rem, 2vw, 1rem); } .problems-panel { overflow: hidden; border: 1px solid var(--border); background-color: var(--surface); border-radius: 8px; } .problems-header { display: flex; align-items: center; gap: clamp(0.5rem, 1.5vw, 0.6rem); padding: clamp(0.6rem, 2vw, 0.75rem) clamp(0.85rem, 2.5vw, 1rem); background-color: var(--surface); border-bottom: 1px solid var(--border); } .problems-count { display: inline-flex; align-items: center; justify-content: center; min-width: clamp(1.25rem, 2.5vw, 1.4rem); height: clamp(1.25rem, 2.5vw, 1.4rem); background-color: var(--accent); color: var(--bg); font-size: clamp(0.75rem, 1.8vw, 0.8rem); font-weight: 600; border-radius: 4px; } .problems-title { font-size: clamp(0.9rem, 2vw, 1rem); font-weight: 600; color: var(--text); } .problems-list { display: flex; flex-direction: column; } .problem-item { display: flex; flex-direction: column; gap: clamp(0.4rem, 1vw, 0.5rem); padding: clamp(0.75rem, 2vw, 1rem) clamp(0.85rem, 2.5vw, 1rem); border-bottom: 1px solid var(--border); } .problem-item:last-child { border-bottom: none; } .problem-entry { display: flex; border-radius: 5px; overflow: hidden; font-size: clamp(0.85rem, 2vw, 0.9rem); background: var(--error-bg); border: 1px solid var(--error-border); text-decoration: none; transition: border-color 0.15s ease; } .problem-entry:hover { border-color: var(--error); } .problem-label { display: flex; align-items: center; gap: 0.4rem; padding: clamp(0.3rem, 1vw, 0.4rem) clamp(0.55rem, 1.5vw, 0.65rem); font-weight: 600; font-size: clamp(0.75rem, 1.8vw, 0.8rem); white-space: nowrap; background-color: var(--error); color: #fff; } .problem-text { display: flex; align-items: center; padding: clamp(0.3rem, 1vw, 0.4rem) clamp(0.55rem, 1.5vw, 0.65rem); color: var(--text); font-weight: 500; flex: 1; word-break: break-word; } .problem-line { display: inline-flex; align-items: center; margin: clamp(0.25rem, 0.8vw, 0.35rem) clamp(0.55rem, 1.5vw, 0.65rem); padding: 0.2em 0.5em; font-family: var(--font-mono), monospace; font-size: clamp(0.7rem, 1.6vw, 0.75rem); font-weight: 500; color: var(--text-muted); background-color: var(--surface); border: 1px solid var(--border); border-radius: 4px; white-space: nowrap; } .problem-solutions { display: flex; flex-direction: column; gap: clamp(0.25rem, 0.5vw, 0.3rem); padding: clamp(0.4rem, 1vw, 0.5rem) clamp(0.55rem, 1.5vw, 0.65rem); background-color: var(--surface); border-radius: 5px; } .problem-solutions-label { font-size: clamp(0.75rem, 1.8vw, 0.8rem); font-weight: 600; color: var(--text-muted); } .problem-solution { display: flex; align-items: baseline; gap: clamp(0.4rem, 1vw, 0.5rem); font-size: clamp(0.8rem, 1.8vw, 0.85rem); } .problem-solution i { color: var(--accent); font-size: 0.85em; } .problem-solution span { color: var(--text); } /** Log Viewer **/ .log { view-transition-name: log; padding: 0; border-bottom: 1px solid var(--border); background-color: var(--bg-elevated); position: relative; flex: 1; } .setting-floating-scrollbar .floating-scrollbar-container { display: flex; } .floating-scrollbar-container { --floating-scrollbar-width: 0; --floating-scrollbar-content-width: 0; position: fixed; display: none; justify-content: center; bottom: 0; width: 100%; z-index: 10; } .floating-scrollbar { overflow-x: scroll; width: var(--floating-scrollbar-width); } .floating-scrollbar-content { width: var(--floating-scrollbar-content-width); height: var(--scrollbar-height); } .log-inner { overflow-y: hidden; font-family: var(--font-mono), monospace; font-size: clamp(0.75rem, 2vw, 0.9rem); line-height: 1.6; overflow-x: auto; position: relative; padding: 0.5rem 0 0; display: grid; grid-template-columns: auto 1fr; contain: layout style paint; will-change: scroll-position; } .log-inner .entry { display: contents; width: 100%; } .log-inner .entry.entry-error .line-content, .log-inner .entry.entry-error .line-number-container{ background-color: var(--error-bg); } .log-inner .line-number-container { min-width: 2.75rem; padding: 0 0.4rem; border-right: 1px solid var(--border); text-align: right; user-select: none; } .log-inner .line-number { padding: clamp(0.08rem, 1vw, 0.1rem) clamp(0.2rem, 1.5vw, 0.25rem); color: var(--text-muted); font-weight: 500; font-size: clamp(0.65rem, 1.8vw, 0.8rem); border-radius: 4px; } .log-inner .entry.line-active .line-number { background-color: var(--accent); color: var(--bg); font-weight: 600; } .log-inner .entry.line-active .line-number-container, .log-inner .entry.line-active .line-content { background-color: color-mix(in srgb, var(--accent) 15%, var(--bg) 85%); } .log-inner .entry.entry-error.line-active .line-number { background-color: var(--error); color: #fff; } .log-inner .entry.entry-error.line-active .line-number-container, .log-inner .entry.entry-error.line-active .line-content { background-color: color-mix(in srgb, var(--error) 25%, var(--bg) 75%); } .log-inner .line-content { padding-left: clamp(0.4rem, 1vw, 0.9rem); padding-right: clamp(0.4rem, 2vw, 0.6rem); word-break: break-word; overflow-wrap: anywhere; color: var(--text); } /* Firefox fallback: use table layout instead of grid */ @supports (-moz-appearance: none) { :root { --browser: 'firefox'; } .log-inner { display: table; table-layout: fixed; width: 100%; } .log-inner .entry, .log-inner .collapsed-lines { display: table-row; } .log-inner .line-number-container, .log-inner .collapsed-lines > div:first-child { display: table-cell; width: 3.6rem; } @media (max-width: 600px) { .log-inner .line-number-container { width: 2.7rem; } } .log-inner .line-content, .log-inner .collapsed-lines-count { display: table-cell; } .log-inner .collapsed-lines-count { text-align: center; vertical-align: middle; } body.setting-no-wrap .log { overflow-x: auto; } body.setting-no-wrap .log-inner { table-layout: auto; } } .collapsed-lines { display: contents; cursor: pointer; } .collapsed-lines > div:first-child { background-color: var(--surface); border-right: 1px solid var(--border); } .collapsed-lines-count { display: flex; align-items: center; justify-content: center; gap: 0.75rem; padding: 0.6rem 1.25rem; background-color: var(--surface); color: var(--text); font-size: clamp(0.85rem, 2vw, 0.9rem); font-family: var(--font-mono), monospace; font-weight: 500; transition: background-color 0.15s ease, color 0.15s ease; } .collapsed-lines:hover .collapsed-lines-count { background-color: var(--accent-bg); color: var(--accent); } .collapsed-lines-count i { font-size: 0.75rem; color: var(--text-muted); transition: color 0.15s ease; } .collapsed-lines:hover .collapsed-lines-count i { color: var(--accent); } .log-inner .level { display: block; white-space: pre-wrap; tab-size: 4; width: 100%; } .log-inner .level-prefix { font-weight: 500; opacity: 0.9; } /** Log Level Styles **/ .level { white-space: pre-wrap; tab-size: 4; word-break: normal; } .level-prefix { font-weight: bold; } .level-info { color: var(--text); } .level-title { font-weight: bold; color: var(--bg); background-color: var(--accent); padding: 0 8px; border-radius: 2px; } .level-info .level-prefix, .level-notice .level-prefix, .level-debug .level-prefix { color: var(--accent); } .level-warning { color: #FF6625; } .level-error, .level-critical, .level-emergency, .level-stacktrace { color: var(--error); } .level-comment { color: #A4A4A4; } /** Minecraft Format Colors **/ .format-black { color: #000; } .format-darkblue { color: #0000AA; } .format-darkgreen { color: #00AA00; } .format-darkaqua { color: #00AAAA; } .format-darkred { color: #AA0000; } .format-darkpurple { color: #AA00AA; } .format-gold { color: #FFAA00; } .format-gray { color: #AAAAAA; } .format-darkgray { color: #555555; } .format-blue { color: #5555FF; } .format-green { color: #55FF55; } .format-aqua { color: #55FFFF; } .format-red { color: #FF5555; } .format-lightpurple { color: #FF55FF; } .format-yellow { color: #FFFF55; } .format-white { color: #FFFFFF; } .format-reset { color: #FFFFFF; font-weight: normal; text-decoration: none; font-style: normal; display: inline-block; } .format-bold { font-weight: bold; } .format-underline { text-decoration: underline; } .format-italic { font-style: italic; } .format-strike { text-decoration: line-through; } /** Log Content Styles **/ .multiline { padding-left: 64px; } .highlight-error { background: var(--error); color: #fff; padding: 0 3px; border-radius: 2px; font-weight: bold; display: inline-block; } .highlight-warning { background: #FF6625; color: var(--text); padding: 0 3px; border-radius: 2px; font-weight: bold; display: inline-block; } .entry { overflow-wrap: anywhere; } @media (max-width: 800px) { .multiline { padding-left: 0; } .problem-line { display: none; } } /** Log bottom **/ .log-bottom { display: flex; justify-content: space-between; align-items: center; padding: clamp(0.75rem, 2vw, 1rem) 0; border-bottom: 1px solid var(--border); } .log-bottom .actions { display: flex; flex-wrap: wrap; gap: 10px; } /** Generic Popover **/ .popover-wrapper { position: relative; } .popover-trigger { cursor: pointer; } .popover-trigger i { transition: transform 0.2s ease; } .popover-content { position: fixed; inset: unset; margin-bottom: 0.5rem; background-color: var(--bg-surface); border: 1px solid var(--border); border-radius: 8px; padding: 0.5rem; min-width: 200px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); overflow: hidden; } .popover-content:popover-open { display: flex; flex-direction: column; gap: 0.25rem; } .popover-content::after { content: ''; position: absolute; bottom: -6px; right: 1rem; width: 10px; height: 10px; background-color: var(--bg-surface); border-right: 1px solid var(--border); border-bottom: 1px solid var(--border); transform: rotate(45deg); } .popover-content::backdrop { background: transparent; } /* Popover danger variant */ .popover-content.popover-danger { background-color: var(--bg-surface); border-color: var(--error); text-align: center; } .popover-content.popover-danger::after { background-color: var(--bg-surface); border-color: var(--error); } .popover-error { display: none; font-weight: 600; font-size: clamp(0.85rem, 2vw, 0.9rem); padding: clamp(0.2rem, 2vw, 0.2rem); color: var(--text); background-color: var(--error-bg); border: 1px solid var(--error-border); border-radius: 8px; margin-bottom: 0.5rem; } /** Settings Popover **/ .settings-trigger { anchor-name: --settings-trigger; } .settings-overlay { position-anchor: --settings-trigger; bottom: anchor(top); right: anchor(right); } /** Delete Popover **/ .delete-trigger { anchor-name: --delete-trigger; } .delete-trigger:hover { opacity: 1; } .delete-overlay { position-anchor: --delete-trigger; bottom: anchor(top); right: anchor(right); min-width: 250px; padding: 1rem; gap: 0.75rem; } .delete-message { font-size: 0.9rem; color: var(--text); font-weight: 500; margin-bottom: 10px; } .delete-actions { display: flex; gap: 0.5rem; } .delete-actions .btn { flex: 1; justify-content: center; } .setting { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: 0.5rem 0.75rem; border-radius: 6px; cursor: pointer; transition: background-color 0.1s ease; } .setting:hover { background-color: var(--surface); } .setting-label { font-size: 0.9rem; color: var(--text); } .setting-checkbox { appearance: none; width: 2.5rem; height: 1.4rem; background-color: var(--surface); border-radius: 1rem; position: relative; cursor: pointer; transition: background-color 0.15s ease; flex-shrink: 0; } .setting-checkbox::before { content: ''; position: absolute; top: 0.2rem; left: 0.2rem; width: 1rem; height: 1rem; background-color: var(--text-muted); border-radius: 50%; transition: left 0.15s ease, background-color 0.15s ease; } .setting-checkbox:checked { background-color: var(--accent); } .setting-checkbox:checked::before { left: 1.3rem; background-color: var(--bg); } .log-details { display: grid; grid-template-columns: 1fr 1fr; align-items: center; gap: clamp(0.75rem, 2vw, 1.25rem); padding: clamp(0.75rem, 2vw, 1rem) 0; border-top: 1px solid var(--border); font-size: clamp(0.85rem, 2vw, 0.9rem); color: var(--text-muted); } .log-details:has(:nth-child(3)) { grid-template-columns: 1fr 1fr 1fr; } .log-details .meta-data { display: flex; align-items: center; gap: 0.7rem; flex-wrap: wrap; } .log-details i { margin-right: 0.25rem; } .log-details *:nth-child(2) { text-align: center; } .log-details *:last-child { text-align: right; } @media (max-width: 640px) { .log-details { grid-template-columns: 1fr; gap: 0.5rem; justify-content: center; } .log-details:has(:nth-child(3)) { grid-template-columns: 1fr; } .log-details .meta-data { justify-content: center; } .log-details *:nth-child(2), .log-details *:last-child { text-align: center; } } /** Error Page **/ .error-page { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; padding: clamp(2rem, 5vw, 3rem) clamp(1rem, 3vw, 1.5rem); } .error-code { font-size: clamp(4rem, 15vw, 8rem); font-weight: 600; color: var(--text); line-height: 1; opacity: 0.15; } .error-message { font-size: clamp(1.25rem, 4vw, 1.8rem); font-weight: 700; color: var(--text); margin-top: -0.5rem; } .error-description { font-size: clamp(0.9rem, 2vw, 1rem); color: var(--text-muted); margin-top: 0.75rem; margin-bottom: clamp(1.5rem, 4vw, 2rem); } /** API Documentation **/ .api-docs-header { display: flex; align-items: center; justify-content: space-between; gap: clamp(1rem, 3vw, 2rem); padding: clamp(1.25rem, 3vw, 2rem) clamp(1rem, 3vw, 1.5rem); border-bottom: 1px solid var(--border); background-color: var(--bg-elevated); } .api-docs-header-content { flex: 1; } .api-docs-header h1 { font-size: clamp(1.5rem, 4vw, 2rem); font-weight: 600; color: var(--text); margin-bottom: 0.75rem; } .api-docs-header p { font-size: clamp(0.9rem, 2vw, 1rem); color: var(--text-muted); line-height: 1.6; } .api-docs-header p strong { color: var(--text); font-weight: 600; } .api-docs-toc { padding: clamp(1rem, 2.5vw, 1.25rem) clamp(1rem, 3vw, 1.5rem); margin-bottom: 0; background-color: var(--bg-elevated); border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: clamp(0.75rem, 2vw, 1rem); flex-wrap: wrap; } .api-docs-toc h3 { font-size: clamp(0.85rem, 2vw, 0.95rem); font-weight: 500; color: var(--text-muted); margin: 0; white-space: nowrap; opacity: 0.6; pointer-events: none; user-select: none; } .api-docs-toc h3::after { content: ':'; margin-left: 0.25rem; opacity: 0.4; } .api-docs-toc-nav { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; justify-content: flex-start; } .api-docs-toc-nav a { display: inline-flex; align-items: center; padding: 0.4rem 0.85rem; color: var(--text-muted); font-size: clamp(0.8rem, 2vw, 0.85rem); border-radius: 6px; transition: background-color 0.15s ease, color 0.15s ease; text-decoration: none; font-weight: 500; white-space: nowrap; cursor: pointer; } .api-docs-toc-nav a:hover { background-color: rgba(255, 255, 255, 0.04); color: var(--text); } .api-docs-toc-nav a:active { background-color: rgba(255, 255, 255, 0.06); } .api-docs-section { padding: clamp(1.25rem, 3vw, 2rem) clamp(1rem, 3vw, 1.5rem); border-bottom: 1px solid var(--border); scroll-margin-top: 1rem; } .api-docs-section:last-of-type { border-bottom: none; } .api-docs-section h2 { font-size: clamp(1.25rem, 3vw, 1.5rem); font-weight: 600; color: var(--text); margin-top: 0; margin-bottom: 1rem; } .api-docs-section p { font-size: clamp(0.9rem, 2vw, 1rem); color: var(--text); line-height: 1.6; margin-top: 0; margin-bottom: 1.5rem; } .api-docs-section p + p { margin-top: -0.75rem; } .api-docs-section p + .api-endpoint, .api-docs-section p + .api-table, .api-docs-section p + h3, .api-docs-section p + h4 { margin-top: 0; } .api-docs-section h3 { font-size: clamp(1rem, 2.5vw, 1.1rem); font-weight: 600; color: var(--text); margin-top: 2rem; margin-bottom: 1rem; display: flex; align-items: center; gap: 0.5rem; } .api-docs-section h2 + h3, .api-docs-section .api-endpoint + h3, .api-docs-section .api-table + h3, .api-docs-section .api-note + h3 { margin-top: 1.5rem; } .api-docs-section h4 { font-size: clamp(0.95rem, 2vw, 1rem); font-weight: 600; color: var(--text); margin-top: 1.5rem; margin-bottom: 0.75rem; display: flex; align-items: center; gap: 0.5rem; } .api-docs-section h3 + h4 { margin-top: 1rem; } .api-endpoint { display: flex; align-items: center; flex-wrap: wrap; gap: clamp(0.5rem, 1.5vw, 0.75rem); padding: clamp(0.75rem, 2vw, 1rem) clamp(1rem, 2.5vw, 1.25rem); background-color: var(--bg-inset); border: 1px solid var(--border); border-radius: 8px; margin-top: 0; margin-bottom: 1.5rem; font-family: var(--font-mono), monospace; font-size: clamp(0.85rem, 2vw, 0.9rem); } .api-endpoint + .api-note, .api-endpoint + .api-table, .api-endpoint + h3, .api-endpoint + h4 { margin-top: 0; } .api-method { display: inline-flex; align-items: center; padding: clamp(0.2rem, 1vw, 0.25rem) clamp(0.6rem, 1.5vw, 0.75rem); background-color: var(--accent); color: var(--bg); font-weight: 600; border-radius: 4px; font-size: clamp(0.75rem, 1.8vw, 0.8rem); text-transform: uppercase; letter-spacing: 0.05em; } .api-url { color: var(--text); font-weight: 500; word-break: break-all; } .content-type { display: inline-flex; align-items: center; padding: clamp(0.2rem, 1vw, 0.25rem) clamp(0.6rem, 1.5vw, 0.75rem); background-color: var(--surface); color: var(--text-muted); border: 1px solid var(--border); border-radius: 4px; font-size: clamp(0.7rem, 1.8vw, 0.75rem); font-weight: 500; font-family: var(--font-mono), monospace; } .api-table { width: 100%; border-collapse: collapse; margin-top: 0; margin-bottom: 1.5rem; background-color: var(--bg-inset); border: 1px solid var(--border); border-radius: 8px; overflow: hidden; } .api-table + .api-note, .api-table + h3, .api-table + h4, .api-table + .api-code { margin-top: 0; } .api-table th { background-color: var(--surface); padding: clamp(0.6rem, 2vw, 0.75rem) clamp(0.85rem, 2.5vw, 1rem); text-align: left; font-weight: 600; font-size: clamp(0.8rem, 2vw, 0.85rem); color: var(--text); border-bottom: 1px solid var(--border); } .api-table td { padding: clamp(0.6rem, 2vw, 0.75rem) clamp(0.85rem, 2.5vw, 1rem); border-bottom: 1px solid var(--border); font-size: clamp(0.85rem, 2vw, 0.9rem); } .api-table tr:last-child td { border-bottom: none; } .api-table tr:hover { background-color: var(--surface); } .api-field { white-space: nowrap; font-family: var(--font-mono), monospace; color: var(--accent); font-weight: 500; } .api-type { font-family: var(--font-mono), monospace; color: var(--text-muted); font-weight: 500; } .api-description { color: var(--text); line-height: 1.5; } .api-required { text-align: center; font-size: 1rem; } .api-required i { color: var(--text-muted); opacity: 0.5; } .api-required.required i { color: var(--accent); opacity: 1; } .api-code { background-color: var(--bg-elevated); border: 1px solid var(--border); border-radius: 8px; padding: clamp(1rem, 2.5vw, 1.25rem); overflow-x: auto; font-family: var(--font-mono), monospace; font-size: clamp(0.8rem, 2vw, 0.85rem); line-height: 1.6; color: var(--text); margin-top: 0; margin-bottom: 1.5rem; white-space: pre; tab-size: 2; font-variant-ligatures: none; } .api-code + h3, .api-code + h4, .api-code + .api-note { margin-top: 1.5rem; } .api-note { margin-top: 0; margin-bottom: 1.5rem; padding: clamp(0.75rem, 2vw, 0.85rem) clamp(0.85rem, 2.5vw, 1rem); border-radius: 8px; border: 1px solid var(--accent-border); background-color: var(--accent-bg); font-size: clamp(0.85rem, 1.8vw, 0.9rem); color: var(--text); line-height: 1.6; } .api-note .content-type { margin: 0 10px; white-space: normal; word-break: break-word; display: inline; vertical-align: baseline; } .api-docs-notes { display: flex; align-items: center; justify-content: space-between; gap: clamp(1rem, 3vw, 2rem); padding: clamp(1.25rem, 3vw, 2rem) clamp(1rem, 3vw, 1.5rem); background-color: var(--bg-elevated); border: 1px solid var(--border); } .api-docs-notes-content { flex: 1; } .api-docs-notes-content h2 { font-size: clamp(1.25rem, 3vw, 1.5rem); font-weight: 600; color: var(--text); margin-bottom: 0.75rem; } .api-docs-notes-content p { font-size: clamp(0.9rem, 2vw, 1rem); color: var(--text-muted); line-height: 1.6; margin-bottom: 1rem; } .api-docs-notes-actions { display: flex; gap: 0.75rem; flex-wrap: wrap; } @media (max-width: 1024px) { body.setting-full-width { --max-width-content: min(100%, calc(var(--max-width))); } main { padding: 0; border-radius: 0; } .log-body main { border-radius: 0; } .log-container, .log-footer { border-radius: 0; } } @media (max-width: 640px) { .log-inner .line-number-container { min-width: unset; padding: 0; } footer { justify-content: center; } .legal, .footer-text { order: 2; } .footer-nav { width: 100%; order: 1; justify-content: center; } .problem-entry { align-items: stretch; } .problem-line { display: none; } .api-docs-header { flex-direction: column; align-items: flex-start; gap: 1.5rem; } .api-docs-section { padding: 1.5rem 1rem; } .api-docs-notes { flex-direction: column; align-items: flex-start; gap: 1.5rem; } .api-endpoint { flex-direction: column; align-items: flex-start; } .api-docs-toc { padding: 1rem; } .api-docs-toc-nav { gap: 0.25rem; } .api-docs-toc-nav a { padding: 0.35rem 0.7rem; } } ================================================ FILE: web/public/js/log.js ================================================ /* line numbers */ updateLineNumber(location.hash); for (let line of document.querySelectorAll('.line-number')) { line.addEventListener("click", () => updateLineNumber(line.attributes.getNamedItem("id").value)); } function updateLineNumber(id) { if (id && id.startsWith('#')) { id = id.substring(1); } if (!id) { return; } let element = document.getElementById(id); if (element.classList.contains("line-number")) { for (const line of document.querySelectorAll(".line-active")) { line.classList.remove("line-active"); } element.closest('.entry').classList.add('line-active'); } } /* Scroll to top/bottom buttons */ const downButton = document.getElementById("down-button"); if (downButton) { downButton.addEventListener("click", () => scrollToHeight(document.body.scrollHeight)); } const upButton = document.getElementById("up-button"); if (upButton) { upButton.addEventListener("click", () => scrollToHeight(0)); } /** * Scroll to a specific height * Disable smooth scrolling for large pages * @param {number} top height to scroll to * @param {number} [smoothScrollLimit] only use smooth scrolling if the distance is less than this value */ function scrollToHeight(top, smoothScrollLimit = 10000) { const distance = Math.abs(document.documentElement.scrollTop - top); const behavior = (distance < smoothScrollLimit) ? "smooth" : "instant"; window.scrollTo({left: 0, top, behavior}); } /* error collapse toggle */ const toggleErrorsButton = document.getElementById("error-toggle"); if (toggleErrorsButton) { toggleErrorsButton.addEventListener("click", toggleErrors); } function toggleErrors() { if (toggleErrorsButton.classList.contains("toggled")) { toggleErrorsButton.classList.remove("toggled"); uncollapseAllErrors(); } else { toggleErrorsButton.classList.add("toggled"); collapseAllErrors(); } } function collapseAllErrors() { let firstNoErrorLine = false; let lines = document.querySelectorAll('.log-inner > .entry'); let totalLines = lines.length; for (const [i, line] of lines.entries()) { let lineNumber = line.querySelector(".line-number").innerHTML; if (line.classList.contains("entry-no-error")) { line.style.display = "none"; if (firstNoErrorLine === false) { firstNoErrorLine = lineNumber; } if (i + 1 === totalLines && firstNoErrorLine) { line.insertAdjacentElement("afterend", generateCollapsedLines(firstNoErrorLine, lineNumber)); } } else { if (firstNoErrorLine) { line.insertAdjacentElement("beforebegin", generateCollapsedLines(firstNoErrorLine, lineNumber - 1)); firstNoErrorLine = false; } } } } function uncollapseAllErrors() { document.querySelectorAll('.entry-no-error').forEach(line => line.style.removeProperty("display")); document.querySelectorAll('.collapsed-lines').forEach(collapsed => collapsed.remove()); } function handleCollapsedClick(e) { let collapsed = e.currentTarget; let positionElement = document.getElementById(`L${parseInt(collapsed.dataset.end) + 1}`); let position; if (positionElement) { position = positionElement.getBoundingClientRect().top - window.scrollY; } for (let i = parseInt(collapsed.dataset.start); i <= parseInt(collapsed.dataset.end); i++) { document.getElementById(`L${i}`).parentElement.parentElement.style.removeProperty("display"); } if (positionElement) { window.scrollTo({ left: 0, top: positionElement.getBoundingClientRect().top - position - collapsed.offsetHeight, behavior: "instant" }); } collapsed.remove(); } function generateCollapsedLines(start, end) { let count = end - start + 1; let string = count === 1 ? "line" : "lines"; let collapsedRow = document.createElement("div"); collapsedRow.classList.add("collapsed-lines"); collapsedRow.dataset.start = start; collapsedRow.dataset.end = end; collapsedRow.appendChild(document.createElement("div")); collapsedRow.addEventListener("click", handleCollapsedClick); let collapsedLinesCount = document.createElement("div"); collapsedLinesCount.classList.add("collapsed-lines-count"); let icon = document.createElement("i"); icon.classList.add("fa-solid", "fa-angle-up"); collapsedLinesCount.appendChild(icon); collapsedLinesCount.append(` ${count} ${string} `); collapsedLinesCount.append(icon.cloneNode()); collapsedRow.appendChild(collapsedLinesCount); return collapsedRow; } /* convert timestamps */ let timeElements = document.querySelectorAll('[data-time]'); for (const element of timeElements) { const timestamp = parseInt(element.dataset.time); if (isNaN(timestamp)) { continue; } const date = new Date(timestamp * 1000); element.innerHTML = date.toLocaleString(); } /* settings */ const settingCheckboxes = document.querySelectorAll(".setting-checkbox"); settingCheckboxes.forEach(checkbox => checkbox.addEventListener("change", handleSettingChange)); let settingsChannel = null; if (typeof BroadcastChannel !== "undefined") { settingsChannel = new BroadcastChannel("mc-logs-settings"); settingsChannel.onmessage = (e) => { if (e.data.type === "settings-updated") { for (const checkbox of settingCheckboxes) { checkbox.checked = !!e.data.settings[checkbox.dataset.key]; applySetting(checkbox); } } }; } function handleSettingChange(e) { let checkbox = e.target; applySetting(checkbox); saveSettings(); if (settingsChannel) { settingsChannel.postMessage({ type: "settings-updated", settings: getCurrentSettings() }); } } function applySetting(checkbox) { let bodyClass = checkbox.dataset.bodyClass; if (checkbox.checked) { document.body.classList.add(bodyClass); } else { document.body.classList.remove(bodyClass); } switch (checkbox.dataset.key) { case "floatingScrollbar": initFloatingScrollbar(); break; } } function getCurrentSettings() { const data = {}; for (const checkbox of settingCheckboxes) { data[checkbox.dataset.key] = checkbox.checked; } return data; } function saveSettings() { const data = {}; for (const checkbox of settingCheckboxes) { data[checkbox.dataset.key] = checkbox.checked; } document.cookie = "MCLOGS_SETTINGS=" + encodeURIComponent(JSON.stringify(data)) + ";path=/;expires=" + new Date(new Date().getTime() + 100 * 365 * 24 * 60 * 60 * 1000).toUTCString(); } /* copy to clipboard */ const copyButtons = document.querySelectorAll("[data-clipboard]"); copyButtons.forEach(button => button.addEventListener("click", handleCopyButtonClick)); const doneClassName = "fa-solid fa-check"; async function handleCopyButtonClick(e) { const button = e.currentTarget; const data = button.dataset.clipboard; await navigator.clipboard.writeText(data); const iconElement = button.querySelector("i"); if (!iconElement) { return; } const originalClassName = iconElement.className; if (originalClassName === doneClassName) { return; } iconElement.className = doneClassName; setTimeout(() => { iconElement.className = originalClassName; }, 2000); } /* delete button */ const deleteButton = document.querySelector(".delete-log-button"); const deleteErrorElement = document.querySelector(".delete-overlay .popover-error"); if (deleteButton) { deleteButton.addEventListener("click", handleDeleteButtonClick); } async function handleDeleteButtonClick() { deleteErrorElement.style.display = "none"; const response = await fetch(window.location.href, { method: "DELETE", credentials: "include" }); if (!response.ok) { deleteErrorElement.style.display = "block"; deleteErrorElement.textContent = `${response.status} (${response.statusText})`; return; } window.location.href = "/"; } /* floating scroll bar */ const browser = getComputedStyle(document.body) .getPropertyValue("--browser") .replaceAll(/['"]/g, '') .trim() .toLowerCase(); const floatingScrollbar = document.querySelector(".floating-scrollbar"); let logContainer = null; if (browser === "firefox") { logContainer = document.querySelector(".log"); } else { logContainer = document.querySelector(".log-inner"); } if (floatingScrollbar && logContainer) { updateFloatingScrollbarWidths(); floatingScrollbar.addEventListener("scroll", () => { syncScroll(floatingScrollbar, logContainer); }); logContainer.addEventListener("scroll", () => { syncScroll(logContainer, floatingScrollbar); }); const observer = new ResizeObserver(() => { updateFloatingScrollbarWidths(); }); observer.observe(logContainer); } function syncScroll(source, target) { if (Math.abs(source.scrollLeft - target.scrollLeft) > 1) { target.scrollLeft = source.scrollLeft; } } function initFloatingScrollbar() { if (!floatingScrollbar || !logContainer) { return; } updateFloatingScrollbarWidths(); syncScroll(logContainer, floatingScrollbar); } function updateFloatingScrollbarWidths() { floatingScrollbar.style.setProperty( "--floating-scrollbar-width", `${logContainer.clientWidth}px` ); floatingScrollbar.style.setProperty( "--floating-scrollbar-content-width", `${logContainer.scrollWidth}px` ); } ================================================ FILE: web/public/js/start.js ================================================ /* Paste area */ const source = document.body.dataset.name || location.host; const pasteArea = document.getElementById('paste-text'); const pastePlaceholder = document.querySelector('.paste-placeholder'); const pasteSaveButtons = document.querySelectorAll('.paste-save'); const fileSelectButton = document.getElementById('paste-select-file'); const pasteClipboardButton = document.getElementById('paste-clipboard'); const pasteError = document.getElementById('paste-error'); pasteArea.focus(); pasteArea.addEventListener('input', reevaluateContentStatus); pasteArea.addEventListener('paste', handlePasteEvent); pasteSaveButtons.forEach(button => button.addEventListener('click', sendLog)); fileSelectButton.addEventListener('click', selectLogFile); pasteClipboardButton.addEventListener('click', pasteFromClipboard); reevaluateContentStatus(); document.addEventListener('keydown', event => { if (event.key.toLowerCase() === 's' && (event.ctrlKey || event.metaKey)) { void sendLog(); event.preventDefault(); return false; } return true; }); /** * Save the log to the API * @returns {Promise} */ async function sendLog() { if (pasteArea.value === "") { return; } clearError(); pasteSaveButtons.forEach(button => button.classList.add("btn-working")); try { let log = pasteArea.value; log = applyFilters(log); const bodyData = { "content": log, "source": source, "metadata": Array.isArray(self.METADATA) ? self.METADATA : [] }; let headers = { "Content-Type": "application/json" } let body = JSON.stringify(bodyData); if (isGzSupported()) { headers["Content-Encoding"] = "gzip"; body = await packGz(body); } const response = await fetch(`/new`, { method: "POST", credentials: "include", headers: { "Content-Type": "application/json", "Content-Encoding": "gzip" }, body }); if (!response.ok) { showError(`${response.status} (${response.statusText})`); return; } let data = null; try { data = await response.json(); } catch (e) { console.error("Failed to parse JSON returned by API", e); showError("API returned invalid JSON"); return; } if (typeof data === 'object' && !data.success && data.error) { console.error(new Error("API returned an error"), data.error); showError(data.error); return; } if (typeof data !== 'object' || !data.success || !data.id) { console.error(new Error("API returned an invalid response"), data); showError("API returned an invalid response"); return; } location.href = data.url; } catch (e) { showError("Network error"); } } /* filters */ function applyFilters(text) { if (typeof FILTERS === "undefined" || !Array.isArray(FILTERS)) { return text; } for (let filter of FILTERS) { text = applyFilter(text, filter); } return text; } function applyFilter(text, filter) { switch (filter.type) { case 'trim': return text.trim(); case 'limit-bytes': return text.substring(0, filter.data.limit); case 'limit-lines': return text.split('\n').slice(0, filter.data.limit).join('\n'); case 'regex': try { for (const pattern of filter.data.patterns) { const regex = new RegExp(pattern.pattern, 'g' + pattern.modifiers.join()); text = text.replace(regex, (match) => { for (const exemption of filter.data.exemptions) { if (new RegExp(exemption.pattern, exemption.modifiers.join()).test(match)) { return match; } } return pattern.replacement; }); } } catch (e) { console.error('Error applying regex filter', e); } return text; default: console.error('Unknown filter type', filter.type); return text; } } async function pasteFromClipboard() { try { let content = await navigator.clipboard.readText(); if (!content || content.trim().length === 0) { showError("Clipboard is empty."); return; } pasteArea.value = content; reevaluateContentStatus(); } catch (err) { showError("Clipboard is empty or not accessible."); } } function reevaluateContentStatus() { clearError(); if (pasteArea.value.length > 0) { pastePlaceholder.style.display = 'none'; pasteSaveButtons.forEach(button => button.removeAttribute("disabled")); } else { pastePlaceholder.style.display = 'flex'; pasteSaveButtons.forEach(button => button.setAttribute("disabled", "disabled")); } } function showError(message) { pasteSaveButtons.forEach(button => button.classList.remove("btn-working")); pasteError.innerText = message; pasteError.style.display = 'block'; } function clearError() { pasteSaveButtons.forEach(button => button.classList.remove("btn-working")); pasteError.innerText = ''; pasteError.style.display = 'none'; } /* File handling */ async function handlePasteEvent(e) { if (e.clipboardData?.files?.length > 0) { e.preventDefault(); await loadFileContents(e.clipboardData.files[0]); } } /** * @param {Blob} file * @return {Promise} */ function readFile(file) { return new Promise((resolve, reject) => { let reader = new FileReader(); // noinspection JSCheckFunctionSignatures reader.onload = () => resolve(new Uint8Array(reader.result)); reader.onerror = e => reject(e); reader.readAsArrayBuffer(file); }); } async function loadFileContents(file) { if (file.size > 1024 * 1024 * 100) { showError(`File is too large.`); return; } let content = await readFile(file); if (file.name.endsWith('.gz')) { if (!isGzSupported()) { showError(`Gzip files are not supported in this browser.`); return; } content = await unpackGz(content); } if (content.includes(0)) { showError(`This file is not supported.`); return; } pasteArea.value = new TextDecoder().decode(content); reevaluateContentStatus(); } function selectLogFile() { let input = document.createElement('input'); input.type = 'file'; input.style.display = 'none'; document.body.appendChild(input); input.onchange = async () => { if (input.files.length) { await loadFileContents(input.files[0]); } } input.click(); document.body.removeChild(input); } /* Gzip compression */ function isGzSupported() { return (typeof CompressionStream !== 'undefined') && (typeof DecompressionStream !== 'undefined'); } /** * @param {string} raw * @returns {Promise} */ async function packGz(raw) { let data = new TextEncoder().encode(raw); let inputStream = new ReadableStream({ start: (controller) => { controller.enqueue(data); controller.close(); } }); const cs = new CompressionStream('gzip'); const compressedStream = inputStream.pipeThrough(cs); return new Uint8Array(await new Response(compressedStream).arrayBuffer()); } /** * @param {Uint8Array} data * @return {Promise} */ async function unpackGz(data) { let inputStream = new ReadableStream({ start: (controller) => { controller.enqueue(data); controller.close(); } }); const ds = new DecompressionStream('gzip'); const decompressedStream = inputStream.pipeThrough(ds); return new Uint8Array(await new Response(decompressedStream).arrayBuffer()); } function isDragEventValid(e) { if (!e.dataTransfer) { return false; } let types = Array.from(e.dataTransfer.types); if (types.includes('text/uri-list')) { return false; } return types.includes('Files') || types.includes('text/plain'); } /* Drag and drop */ const dropZone = document.getElementById('dropzone'); let windowDragCount = 0; let dropZoneDragCount = 0; window.addEventListener('dragover', e => e.preventDefault()); window.addEventListener('dragenter', e => { e.preventDefault(); if (isDragEventValid(e)) { updateWindowDragCount(1); } }); window.addEventListener('dragleave', e => { e.preventDefault(); if (isDragEventValid(e)) { updateWindowDragCount(-1); } }); window.addEventListener('drop', e => { e.preventDefault(); if (isDragEventValid(e)) { updateWindowDragCount(-1); } }); dropZone.addEventListener('dragenter', e => { e.preventDefault(); if (isDragEventValid(e)) { updateDropZoneDragCount(1); } }); dropZone.addEventListener('dragleave', e => { e.preventDefault(); if (isDragEventValid(e)) { updateDropZoneDragCount(-1); } }); dropZone.addEventListener('drop', async e => { e.preventDefault(); if (isDragEventValid(e)) { updateDropZoneDragCount(-1); } await handleDropEvent(e); }); function updateWindowDragCount(amount) { windowDragCount = Math.max(0, windowDragCount + amount); if (windowDragCount > 0) { dropZone.classList.add('window-dragover'); } else { dropZone.classList.remove('window-dragover'); } } function updateDropZoneDragCount(amount) { dropZoneDragCount = Math.max(0, dropZoneDragCount + amount); if (dropZoneDragCount > 0) { dropZone.classList.add('dragover'); } else { dropZone.classList.remove('dragover'); } } async function handleDropEvent(e) { console.log(e.dataTransfer?.types); let files = e.dataTransfer.files; if (files.length !== 1) { if (Array.from(e.dataTransfer.types).includes('text/plain')) { pasteArea.value = e.dataTransfer.getData('text/plain'); reevaluateContentStatus(); } return; } await loadFileContents(files[0]); } ================================================ FILE: worker.php ================================================ ensureIndexes(); } catch (Exception $e) { error_log("Failed to ensure MongoDB indexes: " . $e->getMessage()); } $requestCount = 0; $maxRequests = Config::getInstance()->get(ConfigKey::WORKER_REQUESTS); do { $running = \frankenphp_handle_request(function () { MongoDBClient::getInstance()->reset(); URL::clear(); if (URL::isApi()) { ApiRouter::getInstance()->run(); } else { FrontendRouter::getInstance()->run(); } }); gc_collect_cycles(); $requestCount++; } while ($running && $requestCount < $maxRequests);