From 24df00e1a332670ad10e821e113d4985d35f3719 Mon Sep 17 00:00:00 2001 From: Solareon <769465+solareon@users.noreply.github.com> Date: Fri, 6 Sep 2024 18:09:39 +0200 Subject: [PATCH] feat(bridge/qb): add warnings and disabling of overridden functions * feat(bridge/qb): add warnings and disabling of overridden functions QBCore offered a method to modify player object functions at runtime which can lead to interesting side effects depending on implementation. This adds warnings for when this occurs and adds options to block the behavior as well as disabling the warning in either case. * fix(bridge/qb): rename convars * fix(bridge/qb): fix message * refactor(bridge/qb): use getconvar --- bridge/qb/server/functions.lua | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/bridge/qb/server/functions.lua b/bridge/qb/server/functions.lua index b2bdcea81..a65582ddc 100644 --- a/bridge/qb/server/functions.lua +++ b/bridge/qb/server/functions.lua @@ -2,6 +2,9 @@ require 'server.functions' require 'bridge.qb.server.player' local functions = {} +local allowMethodOverrides = GetConvar('qbx:allowmethodoverrides', 'true') == 'true' +local disableMethodOverrideWarning = GetConvar('qbx:disableoverridewarning', 'false') == 'true' + local createQbExport = require 'bridge.qb.shared.export-function' ---@deprecated use the GetEntityCoords and GetEntityHeading natives directly @@ -391,6 +394,18 @@ functions.RemoveGang = function(gangName) end createQbExport('RemoveGang', RemoveGang) +local function checkExistingMethod(method, methodName) + local methodType = type(method) + if methodType == 'function' then + local warnMessage = allowMethodOverrides and 'A resource is overriding method %s in player class. This can cause unexpected behavior. Disable this warning by setting convar qbx:disableoverridewarning to true' or 'A resource attempted to override method %s in player object and was blocked. Disable this warning by setting convar qbx:disableoverridewarning to true' + if not disableMethodOverrideWarning then + lib.print.warn(warnMessage:format(methodName)) + end + return allowMethodOverrides + end + return true +end + ---Add a new function to the Functions table of the player class ---Use-case: -- [[ @@ -409,12 +424,15 @@ function functions.AddPlayerMethod(ids, methodName, handler) if idType == 'number' then if ids == -1 then for _, v in pairs(QBX.Players) do - v.Functions[methodName] = handler + if checkExistingMethod(v.Functions[methodName], methodName) then + v.Functions[methodName] = handler + end end else if not QBX.Players[ids] then return end - - QBX.Players[ids].Functions[methodName] = handler + if checkExistingMethod(QBX.Players[ids].Functions[methodName], methodName) then + QBX.Players[ids].Functions[methodName] = handler + end end elseif idType == 'table' and table.type(ids) == 'array' then for i = 1, #ids do