Oppaitime's version of Gazelle
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mysql.class.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. <?
  2. //-----------------------------------------------------------------------------------
  3. /////////////////////////////////////////////////////////////////////////////////////
  4. /*//-- MySQL wrapper class ----------------------------------------------------------
  5. This class provides an interface to mysqli. You should always use this class instead
  6. of the mysql/mysqli functions, because this class provides debugging features and a
  7. bunch of other cool stuff.
  8. Everything returned by this class is automatically escaped for output. This can be
  9. turned off by setting $Escape to false in next_record or to_array.
  10. //--------- Basic usage -------------------------------------------------------------
  11. * Creating the object.
  12. require(SERVER_ROOT.'/classes/mysql.class.php');
  13. $DB = NEW DB_MYSQL;
  14. -----
  15. * Making a query
  16. $DB->query("
  17. SELECT *
  18. FROM table...");
  19. Is functionally equivalent to using mysqli_query("SELECT * FROM table...")
  20. Stores the result set in $this->QueryID
  21. Returns the result set, so you can save it for later (see set_query_id())
  22. -----
  23. * Getting data from a query
  24. $array = $DB->next_record();
  25. Is functionally equivalent to using mysqli_fetch_array($ResultSet)
  26. You do not need to specify a result set - it uses $this-QueryID
  27. -----
  28. * Escaping a string
  29. db_string($str);
  30. Is a wrapper for $DB->escape_str(), which is a wrapper for
  31. mysqli_real_escape_string(). The db_string() function exists so that you
  32. don't have to keep calling $DB->escape_str().
  33. USE THIS FUNCTION EVERY TIME YOU USE AN UNVALIDATED USER-SUPPLIED VALUE IN
  34. A DATABASE QUERY!
  35. //--------- Advanced usage ---------------------------------------------------------
  36. * The conventional way of retrieving a row from a result set is as follows:
  37. list($All, $Columns, $That, $You, $Select) = $DB->next_record();
  38. -----
  39. * This is how you loop over the result set:
  40. while (list($All, $Columns, $That, $You, $Select) = $DB->next_record()) {
  41. echo "Do stuff with $All of the ".$Columns.$That.$You.$Select;
  42. }
  43. -----
  44. * There are also a couple more mysqli functions that have been wrapped. They are:
  45. record_count()
  46. Wrapper to mysqli_num_rows()
  47. affected_rows()
  48. Wrapper to mysqli_affected_rows()
  49. inserted_id()
  50. Wrapper to mysqli_insert_id()
  51. close
  52. Wrapper to mysqli_close()
  53. -----
  54. * And, of course, a few handy custom functions.
  55. to_array($Key = false)
  56. Transforms an entire result set into an array (useful in situations where you
  57. can't order the rows properly in the query).
  58. If $Key is set, the function uses $Key as the index (good for looking up a
  59. field). Otherwise, it uses an iterator.
  60. For an example of this function in action, check out forum.php.
  61. collect($Key)
  62. Loops over the result set, creating an array from one of the fields ($Key).
  63. For an example, see forum.php.
  64. set_query_id($ResultSet)
  65. This class can only hold one result set at a time. Using set_query_id allows
  66. you to set the result set that the class is using to the result set in
  67. $ResultSet. This result set should have been obtained earlier by using
  68. $DB->query().
  69. Example:
  70. $FoodRS = $DB->query("
  71. SELECT *
  72. FROM food");
  73. $DB->query("
  74. SELECT *
  75. FROM drink");
  76. $Drinks = $DB->next_record();
  77. $DB->set_query_id($FoodRS);
  78. $Food = $DB->next_record();
  79. Of course, this example is contrived, but you get the point.
  80. -------------------------------------------------------------------------------------
  81. *///---------------------------------------------------------------------------------
  82. if (!extension_loaded('mysqli')) {
  83. die('Mysqli Extension not loaded.');
  84. }
  85. //Handles escaping
  86. function db_string($String, $DisableWildcards = false) {
  87. global $DB;
  88. //Escape
  89. $String = $DB->escape_str($String);
  90. //Remove user input wildcards
  91. if ($DisableWildcards) {
  92. $String = str_replace(array('%','_'), array('\%','\_'), $String);
  93. }
  94. return $String;
  95. }
  96. function db_array($Array, $DontEscape = [], $Quote = false) {
  97. foreach ($Array as $Key => $Val) {
  98. if (!in_array($Key, $DontEscape)) {
  99. if ($Quote) {
  100. $Array[$Key] = '\''.db_string(trim($Val)).'\'';
  101. } else {
  102. $Array[$Key] = db_string(trim($Val));
  103. }
  104. }
  105. }
  106. return $Array;
  107. }
  108. //TODO: revisit access levels once Drone is replaced by ZeRobot
  109. class DB_MYSQL {
  110. public $LinkID = false;
  111. protected $QueryID = false;
  112. protected $StatementID = false;
  113. protected $PreparedQuery = false;
  114. protected $Record = [];
  115. protected $Row;
  116. protected $Errno = 0;
  117. protected $Error = '';
  118. public $Queries = [];
  119. public $Time = 0.0;
  120. protected $Database = '';
  121. protected $Server = '';
  122. protected $User = '';
  123. protected $Pass = '';
  124. protected $Port = 0;
  125. protected $Socket = '';
  126. function __construct($Database = SQLDB, $User = SQLLOGIN, $Pass = SQLPASS, $Server = SQLHOST, $Port = SQLPORT, $Socket = SQLSOCK) {
  127. $this->Database = $Database;
  128. $this->Server = $Server;
  129. $this->User = $User;
  130. $this->Pass = $Pass;
  131. $this->Port = $Port;
  132. $this->Socket = $Socket;
  133. }
  134. function halt($Msg) {
  135. global $Debug, $argv;
  136. $DBError = 'MySQL: '.strval($Msg).' SQL error: '.strval($this->Errno).' ('.strval($this->Error).')';
  137. if ($this->Errno == 1194) {
  138. send_irc('PRIVMSG '.ADMIN_CHAN.' :'.$this->Error);
  139. }
  140. $Debug->analysis('!dev DB Error', $DBError, 3600 * 24);
  141. if (DEBUG_MODE || check_perms('site_debug') || isset($argv[1])) {
  142. echo '<pre>'.display_str($DBError).'</pre>';
  143. if (DEBUG_MODE || check_perms('site_debug')) {
  144. print_r($this->Queries);
  145. }
  146. die();
  147. } else {
  148. error('-1');
  149. }
  150. }
  151. function connect() {
  152. if (!$this->LinkID) {
  153. $this->LinkID = mysqli_connect($this->Server, $this->User, $this->Pass, $this->Database, $this->Port, $this->Socket); // defined in config.php
  154. if (!$this->LinkID) {
  155. $this->Errno = mysqli_connect_errno();
  156. $this->Error = mysqli_connect_error();
  157. $this->halt('Connection failed (host:'.$this->Server.':'.$this->Port.')');
  158. }
  159. }
  160. mysqli_set_charset($this->LinkID, "utf8mb4");
  161. }
  162. function prepare_query($Query, &...$BindVars) {
  163. $this->connect();
  164. $this->StatementID = mysqli_prepare($this->LinkID, $Query);
  165. if (!empty($BindVars)) {
  166. $Types = '';
  167. $TypeMap = ['string'=>'s', 'double'=>'d', 'integer'=>'i', 'boolean'=>'i'];
  168. foreach ($BindVars as $BindVar) {
  169. $Types .= $TypeMap[gettype($BindVar)] ?? 'b';
  170. }
  171. mysqli_stmt_bind_param($this->StatementID, $Types, ...$BindVars);
  172. }
  173. $this->PreparedQuery = $Query;
  174. return $this->StatementID;
  175. }
  176. function exec_prepared_query() {
  177. $QueryStartTime = microtime(true);
  178. mysqli_stmt_execute($this->StatementID);
  179. $this->QueryID = mysqli_stmt_get_result($this->StatementID);
  180. $QueryRunTime = (microtime(true) - $QueryStartTime) * 1000;
  181. $this->Queries[] = [$this->PreppedQuery, $QueryRunTime, null];
  182. $this->Time += $QueryRunTime;
  183. }
  184. function query($Query, &...$BindVars) {
  185. global $Debug;
  186. /*
  187. * If there was a previous query, we store the warnings. We cannot do
  188. * this immediately after mysqli_query because mysqli_insert_id will
  189. * break otherwise due to mysqli_get_warnings sending a SHOW WARNINGS;
  190. * query. When sending a query, however, we're sure that we won't call
  191. * mysqli_insert_id (or any similar function, for that matter) later on,
  192. * so we can safely get the warnings without breaking things.
  193. * Note that this means that we have to call $this->warnings manually
  194. * for the last query!
  195. */
  196. if ($this->QueryID) {
  197. $this->warnings();
  198. }
  199. $QueryStartTime = microtime(true);
  200. $this->connect();
  201. // In the event of a MySQL deadlock, we sleep allowing MySQL time to unlock, then attempt again for a maximum of 5 tries
  202. for ($i = 1; $i < 6; $i++) {
  203. $this->StatementID = mysqli_prepare($this->LinkID, $Query);
  204. if (!empty($BindVars)) {
  205. $Types = '';
  206. $TypeMap = ['string'=>'s', 'double'=>'d', 'integer'=>'i', 'boolean'=>'i'];
  207. foreach ($BindVars as $BindVar) {
  208. $Types .= $TypeMap[gettype($BindVar)] ?? 'b';
  209. }
  210. mysqli_stmt_bind_param($this->StatementID, $Types, ...$BindVars);
  211. }
  212. mysqli_stmt_execute($this->StatementID);
  213. $this->QueryID = mysqli_stmt_get_result($this->StatementID);
  214. if (DEBUG_MODE) {
  215. // in DEBUG_MODE, return the full trace on a SQL error (super useful
  216. // for debugging). do not attempt to retry to query
  217. if (!$this->QueryID) {
  218. echo '<pre>' . mysqli_error($this->LinkID) . '<br><br>';
  219. debug_print_backtrace();
  220. echo '</pre>';
  221. die();
  222. }
  223. }
  224. if (!in_array(mysqli_errno($this->LinkID), array(1213, 1205))) {
  225. break;
  226. }
  227. $Debug->analysis('Non-Fatal Deadlock:', $Query, 3600 * 24);
  228. trigger_error("Database deadlock, attempt $i");
  229. sleep($i * rand(2, 5)); // Wait longer as attempts increase
  230. }
  231. $QueryEndTime = microtime(true);
  232. $this->Queries[] = array($Query, ($QueryEndTime - $QueryStartTime) * 1000, null);
  233. $this->Time += ($QueryEndTime - $QueryStartTime) * 1000;
  234. if (!$this->QueryID && !$this->StatementID) {
  235. $this->Errno = mysqli_errno($this->LinkID);
  236. $this->Error = mysqli_error($this->LinkID);
  237. $this->halt("Invalid Query: $Query");
  238. }
  239. $this->Row = 0;
  240. return $this->QueryID;
  241. }
  242. function query_unb($Query) {
  243. $this->connect();
  244. mysqli_real_query($this->LinkID, $Query);
  245. }
  246. function inserted_id() {
  247. if ($this->LinkID) {
  248. return mysqli_insert_id($this->LinkID);
  249. }
  250. }
  251. function next_record($Type = MYSQLI_BOTH, $Escape = true) { // $Escape can be true, false, or an array of keys to not escape
  252. if ($this->LinkID) {
  253. $this->Record = mysqli_fetch_array($this->QueryID, $Type);
  254. $this->Row++;
  255. if (!is_array($this->Record)) {
  256. $this->QueryID = false;
  257. } elseif ($Escape !== false) {
  258. $this->Record = Misc::display_array($this->Record, $Escape);
  259. }
  260. return $this->Record;
  261. }
  262. }
  263. function close() {
  264. if ($this->LinkID) {
  265. if (!mysqli_close($this->LinkID)) {
  266. $this->halt('Cannot close connection or connection did not open.');
  267. }
  268. $this->LinkID = false;
  269. }
  270. }
  271. /*
  272. * returns an integer with the number of rows found
  273. * returns a string if the number of rows found exceeds MAXINT
  274. */
  275. function record_count() {
  276. if ($this->QueryID) {
  277. return mysqli_num_rows($this->QueryID);
  278. }
  279. }
  280. /*
  281. * returns true if the query exists and there were records found
  282. * returns false if the query does not exist or if there were 0 records returned
  283. */
  284. function has_results() {
  285. return ($this->QueryID && $this->record_count() !== 0);
  286. }
  287. function affected_rows() {
  288. if ($this->LinkID) {
  289. return mysqli_affected_rows($this->LinkID);
  290. }
  291. }
  292. function info() {
  293. return mysqli_get_host_info($this->LinkID);
  294. }
  295. // You should use db_string() instead.
  296. function escape_str($Str) {
  297. $this->connect(0);
  298. if (is_array($Str)) {
  299. trigger_error('Attempted to escape array.');
  300. return '';
  301. }
  302. return mysqli_real_escape_string($this->LinkID, $Str);
  303. }
  304. // Creates an array from a result set
  305. // If $Key is set, use the $Key column in the result set as the array key
  306. // Otherwise, use an integer
  307. function to_array($Key = false, $Type = MYSQLI_BOTH, $Escape = true) {
  308. $Return = [];
  309. while ($Row = mysqli_fetch_array($this->QueryID, $Type)) {
  310. if ($Escape !== false) {
  311. $Row = Misc::display_array($Row, $Escape);
  312. }
  313. if ($Key !== false) {
  314. $Return[$Row[$Key]] = $Row;
  315. } else {
  316. $Return[] = $Row;
  317. }
  318. }
  319. mysqli_data_seek($this->QueryID, 0);
  320. return $Return;
  321. }
  322. // Loops through the result set, collecting the $ValField column into an array with $KeyField as keys
  323. function to_pair($KeyField, $ValField, $Escape = true) {
  324. $Return = [];
  325. while ($Row = mysqli_fetch_array($this->QueryID)) {
  326. if ($Escape) {
  327. $Key = display_str($Row[$KeyField]);
  328. $Val = display_str($Row[$ValField]);
  329. } else {
  330. $Key = $Row[$KeyField];
  331. $Val = $Row[$ValField];
  332. }
  333. $Return[$Key] = $Val;
  334. }
  335. mysqli_data_seek($this->QueryID, 0);
  336. return $Return;
  337. }
  338. // Loops through the result set, collecting the $Key column into an array
  339. function collect($Key, $Escape = true) {
  340. $Return = [];
  341. while ($Row = mysqli_fetch_array($this->QueryID)) {
  342. $Return[] = $Escape ? display_str($Row[$Key]) : $Row[$Key];
  343. }
  344. mysqli_data_seek($this->QueryID, 0);
  345. return $Return;
  346. }
  347. function set_query_id(&$ResultSet) {
  348. $this->QueryID = $ResultSet;
  349. $this->Row = 0;
  350. }
  351. function get_query_id() {
  352. return $this->QueryID;
  353. }
  354. function beginning() {
  355. mysqli_data_seek($this->QueryID, 0);
  356. $this->Row = 0;
  357. }
  358. /**
  359. * This function determines whether the last query caused warning messages
  360. * and stores them in $this->Queries.
  361. */
  362. function warnings() {
  363. $Warnings = [];
  364. if (!is_bool($this->LinkID) && mysqli_warning_count($this->LinkID)) {
  365. $e = mysqli_get_warnings($this->LinkID);
  366. do {
  367. if ($e->errno == 1592) {
  368. // 1592: Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT.
  369. continue;
  370. }
  371. $Warnings[] = 'Code ' . $e->errno . ': ' . display_str($e->message);
  372. } while ($e->next());
  373. }
  374. $this->Queries[count($this->Queries) - 1][2] = $Warnings;
  375. }
  376. }
  377. ?>