BeBot - An Anarchy Online and Age Of Conan chat automaton

General => Feedback and Suggestions => Topic started by: Neo-Vortex on February 26, 2007, 08:08:20 am

Title: Smarter, Safer, MySQL.php modification with full Backwards Compatability
Post by: Neo-Vortex on February 26, 2007, 08:08:20 am
Hey, something I've been using on my bots for quite some time now is the use of printf() style args with MySQL.php, this also allows me to automagically escape strings eliminating possible SQL injection vulnerabilities, and best of all, remains backwards compatible, the changes are also quite simple and it would make sql coding in modules (and bebot itself) much nicer to read.

In MySQL.php the following function is added

Code: [Select]
        function smartescape($args)
        {
                if (is_numeric($args)) return $args;
                return mysql_real_escape_string($args);
        }

        function smartargs($args)
        {
                $query = array_shift($args);
                if (empty($args)) return $query;
                $args  = array_map(array($this, 'smartescape'), $args);
                array_unshift($args, $query);
                return call_user_func_array('sprintf', $args);
        }

Then the following line is added at the start of the each SQL function - ie, select(), query(), and returnQuery()

Code: [Select]
$sql = $this -> smartargs(func_get_args());
Then instead of say the following (example pulled from the news module):
Code: [Select]
$this -> bot -> db -> query("INSERT INTO news (type, time, name, news) VALUES ('2' ," . time() .", '" . $name . "', '" . addslashes($msg) . "')");You would do this:
Code: [Select]
$this -> bot -> db -> query("INSERT INTO news (type, time, name, news) VALUES ('2' ,'%d', '%s', '%s')", time(), $name, $msg);Which is much nicer on the eyes, with all escaping done for you automagically :), but best of all, the previous example would work perfectly fine also still, so there is no forced change that would break older modules.

The only potential issue would be if you are using the '%' character to specify a wildcard in which case you would have to escape it by doing '%%' instead or sprintf() would think it should process it, however to eliminate backwards-compatability issues for where '%' has been used unescaped, it will detect if there are any extra arguments parsed, and if there are none (ie, it is just the query itself), it will not process it using printf() to eliminate this :)

Edit: Little change that prevents warnings for if you pass ints to it - old still works, just on rare occasions complains :P
Title: Re: Smarter, Safer, MySQL.php modification with full Backwards Compatability
Post by: Khalem on February 27, 2007, 05:43:35 pm
I've been planning to do this, but not gotten around to it.

Will have a look at this again this weekend.
SimplePortal 2.3.7 © 2008-2024, SimplePortal