Skip to content
View in the app

A better way to browse. Learn more.

Learn more

long-jump-web-stats/addons/amxmodx/scripting/olds_ljweb.sma

olds_ljweb.sma
279 lines · 9.8 KB · Pawn (AMX Mod X)
Raw
/*
 * Long Jump Web Stats (olds.ro workshop card LIB-0973)
 * Copyright (C) 2026 daemon (olds.ro)
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details: <https://www.gnu.org/licenses/>.
 *
 * Copies the long jump records of the olds.ro Long Jump Statistics plugin (nVault "olds_ljs":
 * "pb:<key>" = "distance pre sync" per player, "top" = the record table) to a MySQL table that
 * web/ranking.php shows. Every half second the connected players' records are looked up; a
 * changed one (a new record) is written at once (SQL_ThreadQuery, INSERT ... ON DUPLICATE KEY
 * UPDATE). amx_ljwebsync (ADMIN_RCON) rewrites the table from the record table. Names and keys
 * are escaped with SQL_QuoteString. Database errors are logged once, then at most every five
 * minutes, never per jump.
 */
#include <amxmodx>
#include <amxmisc>
#include <nvault>
#include <sqlx>

#define PLUGIN  "Long Jump Web Stats"
#define VERSION "1.0.0"
#define AUTHOR  "daemon (olds.ro)"

#define TASK_POLL   97300
#define KEY_LEN     40
#define MAX_TOP     30
#define ERROR_QUIET 300.0

new g_host[64], g_user[64], g_pass[64], g_db[64], g_table[32]
new g_vault = INVALID_HANDLE
new bool:g_tableMade
new g_seenValue[MAX_PLAYERS + 1][64]
new g_seenTime[MAX_PLAYERS + 1]
new bool:g_seen[MAX_PLAYERS + 1]
new g_lastQuery[512]
new g_sent, g_ok, g_errors, g_quietErrors
new Float:g_lastErrorLog = -1000.0
new bool:g_warnedConfig

public plugin_init()
{
    register_plugin(PLUGIN, VERSION, AUTHOR)

    bind_pcvar_string(create_cvar("olds_ljw_host", "", FCVAR_PROTECTED, "MySQL host (host or host:port)"), g_host, charsmax(g_host))
    bind_pcvar_string(create_cvar("olds_ljw_user", "", FCVAR_PROTECTED, "MySQL user"), g_user, charsmax(g_user))
    bind_pcvar_string(create_cvar("olds_ljw_pass", "", FCVAR_PROTECTED, "MySQL password"), g_pass, charsmax(g_pass))
    bind_pcvar_string(create_cvar("olds_ljw_db", "", FCVAR_PROTECTED, "MySQL database"), g_db, charsmax(g_db))
    bind_pcvar_string(create_cvar("olds_ljw_table", "olds_lj", FCVAR_NONE, "Table name (letters, digits and _ only)"), g_table, charsmax(g_table))
    AutoExecConfig(true, "olds_ljweb")

    register_concmd("amx_ljwebsync", "cmd_sync", ADMIN_RCON, "- rewrites the web table from the in-game records")
    register_concmd("amx_ljweb_status", "cmd_status", ADMIN_RCON, "- shows the last query and the database errors")

    if (!SQL_SetAffinity("mysql"))
        log_amx("The sqlx mysql driver is not loaded: no records reach the web page")
}

public plugin_cfg()
{
    /* The statistics plugin's vault: nVault hands every plugin the same open vault. */
    g_vault = nvault_open("olds_ljs")
    if (g_vault == INVALID_HANDLE)
        log_amx("Cannot open the nVault olds_ljs: nothing to copy")
    set_task(0.5, "poll", TASK_POLL, _, _, "b")
}

public client_putinserver(id)
{
    g_seen[id] = false
}

public client_disconnected(id)
{
    g_seen[id] = false
}

/* ------------------------------------------------------------------ the database */

bool:table_ok()
{
    if (!g_table[0])
        return false
    for (new i = 0; g_table[i]; i++)
    {
        new c = g_table[i]
        if (!(('a' <= c <= 'z') || ('A' <= c <= 'Z') || ('0' <= c <= '9') || c == '_'))
            return false
    }
    return true
}

bool:config_ok()
{
    if (g_host[0] && g_db[0] && table_ok())
        return true
    if (!g_warnedConfig)
    {
        log_amx("Set olds_ljw_host, olds_ljw_db and a table name of letters, digits and _ (olds_ljw_table): nothing is written")
        g_warnedConfig = true
    }
    return false
}

send_query(const sql[])
{
    copy(g_lastQuery, charsmax(g_lastQuery), sql)
    new Handle:tuple = SQL_MakeDbTuple(g_host, g_user, g_pass, g_db, 3)
    SQL_ThreadQuery(tuple, "on_query", sql)
    SQL_FreeHandle(tuple)
    g_sent++
}

make_table()
{
    if (g_tableMade)
        return
    g_tableMade = true
    new sql[512]
    formatex(sql, charsmax(sql), "CREATE TABLE IF NOT EXISTS `%s` (steamid VARCHAR(48) NOT NULL PRIMARY KEY, name VARCHAR(96) NOT NULL, distance FLOAT NOT NULL, pre FLOAT NOT NULL, date DATETIME NOT NULL, KEY (distance)) DEFAULT CHARSET=utf8mb4", g_table)
    send_query(sql)
}

public on_query(failstate, Handle:query, const error[], errnum, const data[], size, Float:queuetime)
{
    if (failstate == TQUERY_SUCCESS)
    {
        g_ok++
        return
    }
    g_errors++
    /* A query that failed to connect makes the table again next time. */
    if (failstate == TQUERY_CONNECT_FAILED)
        g_tableMade = false
    new Float:now = get_gametime()
    if (now - g_lastErrorLog >= ERROR_QUIET)
    {
        if (g_quietErrors)
            log_amx("Database error %d: %s (and %d more since the last report)", errnum, error, g_quietErrors)
        else
            log_amx("Database error %d: %s", errnum, error)
        g_lastErrorLog = now
        g_quietErrors = 0
    }
    else
        g_quietErrors++
}

/* `key name distance pre unix-time` as one row of an INSERT. */
row_values(const key[], const name[], Float:distance, Float:pre, stamp, out[], len)
{
    new qkey[KEY_LEN * 2 + 2], qname[96 * 2 + 2]
    SQL_QuoteString(Empty_Handle, qkey, charsmax(qkey), key)
    SQL_QuoteString(Empty_Handle, qname, charsmax(qname), name)
    formatex(out, len, "('%s','%s',%.2f,%.0f,FROM_UNIXTIME(%d))", qkey, qname, distance, pre, stamp)
}

/* ------------------------------------------------------------------ new records */

player_key(id, out[], len)
{
    /* As the statistics plugin does: bots share one auth id, so they go by name. */
    if (is_user_bot(id))
    {
        new name[32]
        get_user_name(id, name, charsmax(name))
        formatex(out, len, "BOT:%s", name)
    }
    else
        get_user_authid(id, out, len)
}

public poll()
{
    if (g_vault == INVALID_HANDLE)
        return
    new key[KEY_LEN], vkey[KEY_LEN + 4], value[64], stamp
    for (new id = 1; id <= MaxClients; id++)
    {
        if (!is_user_connected(id) || is_user_hltv(id))
            continue
        player_key(id, key, charsmax(key))
        formatex(vkey, charsmax(vkey), "pb:%s", key)
        if (!nvault_lookup(g_vault, vkey, value, charsmax(value), stamp))
        {
            value[0] = EOS
            stamp = 0
        }
        if (!g_seen[id])
        {
            /* What the player had when they came: not new. */
            g_seen[id] = true
            copy(g_seenValue[id], charsmax(g_seenValue[]), value)
            g_seenTime[id] = stamp
            continue
        }
        if (!value[0] || (stamp == g_seenTime[id] && equal(value, g_seenValue[id])))
            continue
        copy(g_seenValue[id], charsmax(g_seenValue[]), value)
        g_seenTime[id] = stamp
        new dist[16], pre[16]
        parse(value, dist, charsmax(dist), pre, charsmax(pre))
        new name[32]
        get_user_name(id, name, charsmax(name))
        upload(key, name, str_to_float(dist), str_to_float(pre), stamp)
    }
}

upload(const key[], const name[], Float:distance, Float:pre, stamp)
{
    if (!config_ok())
        return
    make_table()
    new values[256], sql[512]
    row_values(key, name, distance, pre, stamp, values, charsmax(values))
    formatex(sql, charsmax(sql), "INSERT INTO `%s` (steamid, name, distance, pre, date) VALUES %s ON DUPLICATE KEY UPDATE name = VALUES(name), distance = VALUES(distance), pre = VALUES(pre), date = VALUES(date)", g_table, values)
    send_query(sql)
}

/* ------------------------------------------------------------------ admin */

public cmd_sync(id, level, cid)
{
    if (!cmd_access(id, level, cid, 1))
        return PLUGIN_HANDLED
    if (g_vault == INVALID_HANDLE)
    {
        console_print(id, "[LJWeb] The nVault olds_ljs is not open.")
        return PLUGIN_HANDLED
    }
    if (!config_ok())
    {
        console_print(id, "[LJWeb] Set olds_ljw_host, olds_ljw_db and a valid olds_ljw_table first.")
        return PLUGIN_HANDLED
    }
    static data[MAX_TOP * 96], rest[MAX_TOP * 96]
    new stamp
    if (!nvault_lookup(g_vault, "top", data, charsmax(data), stamp))
        data[0] = EOS
    make_table()
    new sql[600]
    formatex(sql, charsmax(sql), "DELETE FROM `%s`", g_table)
    send_query(sql)
    /* One INSERT per record: each fits in a query buffer, and the queue keeps the order. */
    new entry[96], part[5][KEY_LEN], rows
    while (data[0])
    {
        strtok2(data, entry, charsmax(entry), rest, charsmax(rest), ';')
        copy(data, charsmax(data), rest)
        if (!entry[0] || explode_string(entry, "|", part, 5, KEY_LEN - 1) != 5)
            continue
        new pbKey[KEY_LEN + 4], value[64], pbStamp
        formatex(pbKey, charsmax(pbKey), "pb:%s", part[0])
        if (!nvault_lookup(g_vault, pbKey, value, charsmax(value), pbStamp))
            pbStamp = stamp
        new values[256]
        row_values(part[0], part[1], str_to_float(part[2]), str_to_float(part[3]), pbStamp, values, charsmax(values))
        formatex(sql, charsmax(sql), "INSERT INTO `%s` (steamid, name, distance, pre, date) VALUES %s", g_table, values)
        send_query(sql)
        rows++
    }
    console_print(id, "[LJWeb] Table %s rewritten: %d record(s) queued.", g_table, rows)
    log_amx("amx_ljwebsync: %d record(s) queued for %s", rows, g_table)
    return PLUGIN_HANDLED
}

public cmd_status(id, level, cid)
{
    if (!cmd_access(id, level, cid, 1))
        return PLUGIN_HANDLED
    console_print(id, "[LJWeb] queries sent %d, succeeded %d, failed %d (%d not logged yet), table %s valid %d",
        g_sent, g_ok, g_errors, g_quietErrors, g_table, table_ok())
    console_print(id, "[LJWeb] last query: %s", g_lastQuery)
    return PLUGIN_HANDLED
}

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.