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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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 = array(), $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 $Record = array();
  113. protected $Row;
  114. protected $Errno = 0;
  115. protected $Error = '';
  116. public $Queries = array();
  117. public $Time = 0.0;
  118. protected $Database = '';
  119. protected $Server = '';
  120. protected $User = '';
  121. protected $Pass = '';
  122. protected $Port = 0;
  123. protected $Socket = '';
  124. function __construct($Database = SQLDB, $User = SQLLOGIN, $Pass = SQLPASS, $Server = SQLHOST, $Port = SQLPORT, $Socket = SQLSOCK) {
  125. $this->Database = $Database;
  126. $this->Server = $Server;
  127. $this->User = $User;
  128. $this->Pass = $Pass;
  129. $this->Port = $Port;
  130. $this->Socket = $Socket;
  131. }
  132. function halt($Msg) {
  133. global $Debug, $argv;
  134. $DBError = 'MySQL: '.strval($Msg).' SQL error: '.strval($this->Errno).' ('.strval($this->Error).')';
  135. if ($this->Errno == 1194) {
  136. send_irc('PRIVMSG '.ADMIN_CHAN.' :'.$this->Error);
  137. }
  138. /*if ($this->Errno == 1194) {
  139. preg_match("Table '(\S+)' is marked as crashed and should be repaired", $this->Error, $Matches);
  140. } */
  141. $Debug->analysis('!dev DB Error', $DBError, 3600 * 24);
  142. if (DEBUG_MODE || check_perms('site_debug') || isset($argv[1])) {
  143. echo '<pre>'.display_str($DBError).'</pre>';
  144. if (DEBUG_MODE || check_perms('site_debug')) {
  145. print_r($this->Queries);
  146. }
  147. die();
  148. } else {
  149. error('-1');
  150. }
  151. }
  152. function connect() {
  153. if (!$this->LinkID) {
  154. $this->LinkID = mysqli_connect($this->Server, $this->User, $this->Pass, $this->Database, $this->Port, $this->Socket); // defined in config.php
  155. if (!$this->LinkID) {
  156. $this->Errno = mysqli_connect_errno();
  157. $this->Error = mysqli_connect_error();
  158. $this->halt('Connection failed (host:'.$this->Server.':'.$this->Port.')');
  159. }
  160. }
  161. mysqli_set_charset($this->LinkID, "utf8");
  162. }
  163. function query($Query, $AutoHandle = 1) {
  164. global $Debug;
  165. /*
  166. * If there was a previous query, we store the warnings. We cannot do
  167. * this immediately after mysqli_query because mysqli_insert_id will
  168. * break otherwise due to mysqli_get_warnings sending a SHOW WARNINGS;
  169. * query. When sending a query, however, we're sure that we won't call
  170. * mysqli_insert_id (or any similar function, for that matter) later on,
  171. * so we can safely get the warnings without breaking things.
  172. * Note that this means that we have to call $this->warnings manually
  173. * for the last query!
  174. */
  175. if ($this->QueryID) {
  176. $this->warnings();
  177. }
  178. $QueryStartTime = microtime(true);
  179. $this->connect();
  180. if (DEBUG_MODE) {
  181. $this->QueryID = mysqli_query($this->LinkID, $Query);
  182. // in DEBUG_MODE, return the full trace on a SQL error (super useful for debugging).
  183. // do not attempt to retry to query
  184. if (!$this->QueryID) {
  185. echo '<pre>' . mysqli_error($this->LinkID) . '<br><br>';
  186. debug_print_backtrace();
  187. echo '</pre>';
  188. die();
  189. }
  190. } else {
  191. // In the event of a MySQL deadlock, we sleep allowing MySQL time to unlock, then attempt again for a maximum of 5 tries
  192. for ($i = 1; $i < 6; $i++) {
  193. $this->QueryID = mysqli_query($this->LinkID, $Query);
  194. if (!in_array(mysqli_errno($this->LinkID), array(1213, 1205))) {
  195. break;
  196. }
  197. $Debug->analysis('Non-Fatal Deadlock:', $Query, 3600 * 24);
  198. trigger_error("Database deadlock, attempt $i");
  199. sleep($i * rand(2, 5)); // Wait longer as attempts increase
  200. }
  201. }
  202. $QueryEndTime = microtime(true);
  203. $this->Queries[] = array($Query, ($QueryEndTime - $QueryStartTime) * 1000, null);
  204. $this->Time += ($QueryEndTime - $QueryStartTime) * 1000;
  205. if (!$this->QueryID) {
  206. $this->Errno = mysqli_errno($this->LinkID);
  207. $this->Error = mysqli_error($this->LinkID);
  208. if ($AutoHandle) {
  209. $this->halt("Invalid Query: $Query");
  210. } else {
  211. return $this->Errno;
  212. }
  213. }
  214. /*
  215. $QueryType = substr($Query, 0, 6);
  216. if ($QueryType === 'DELETE' || $QueryType === 'UPDATE') {
  217. if ($this->affected_rows() > 50) {
  218. $Debug->analysis($this->affected_rows().' rows altered:', $Query, 3600 * 24);
  219. }
  220. }
  221. */
  222. $this->Row = 0;
  223. if ($AutoHandle) {
  224. return $this->QueryID;
  225. }
  226. }
  227. function query_unb($Query) {
  228. $this->connect();
  229. mysqli_real_query($this->LinkID, $Query);
  230. }
  231. function inserted_id() {
  232. if ($this->LinkID) {
  233. return mysqli_insert_id($this->LinkID);
  234. }
  235. }
  236. function next_record($Type = MYSQLI_BOTH, $Escape = true) { // $Escape can be true, false, or an array of keys to not escape
  237. if ($this->LinkID) {
  238. $this->Record = mysqli_fetch_array($this->QueryID, $Type);
  239. $this->Row++;
  240. if (!is_array($this->Record)) {
  241. $this->QueryID = false;
  242. } elseif ($Escape !== false) {
  243. $this->Record = Misc::display_array($this->Record, $Escape);
  244. }
  245. return $this->Record;
  246. }
  247. }
  248. function close() {
  249. if ($this->LinkID) {
  250. if (!mysqli_close($this->LinkID)) {
  251. $this->halt('Cannot close connection or connection did not open.');
  252. }
  253. $this->LinkID = false;
  254. }
  255. }
  256. /*
  257. * returns an integer with the number of rows found
  258. * returns a string if the number of rows found exceeds MAXINT
  259. */
  260. function record_count() {
  261. if ($this->QueryID) {
  262. return mysqli_num_rows($this->QueryID);
  263. }
  264. }
  265. /*
  266. * returns true if the query exists and there were records found
  267. * returns false if the query does not exist or if there were 0 records returned
  268. */
  269. function has_results() {
  270. return ($this->QueryID && $this->record_count() !== 0);
  271. }
  272. function affected_rows() {
  273. if ($this->LinkID) {
  274. return mysqli_affected_rows($this->LinkID);
  275. }
  276. }
  277. function info() {
  278. return mysqli_get_host_info($this->LinkID);
  279. }
  280. // You should use db_string() instead.
  281. function escape_str($Str) {
  282. $this->connect(0);
  283. if (is_array($Str)) {
  284. trigger_error('Attempted to escape array.');
  285. return '';
  286. }
  287. return mysqli_real_escape_string($this->LinkID, $Str);
  288. }
  289. // Creates an array from a result set
  290. // If $Key is set, use the $Key column in the result set as the array key
  291. // Otherwise, use an integer
  292. function to_array($Key = false, $Type = MYSQLI_BOTH, $Escape = true) {
  293. $Return = array();
  294. while ($Row = mysqli_fetch_array($this->QueryID, $Type)) {
  295. if ($Escape !== false) {
  296. $Row = Misc::display_array($Row, $Escape);
  297. }
  298. if ($Key !== false) {
  299. $Return[$Row[$Key]] = $Row;
  300. } else {
  301. $Return[] = $Row;
  302. }
  303. }
  304. mysqli_data_seek($this->QueryID, 0);
  305. return $Return;
  306. }
  307. // Loops through the result set, collecting the $ValField column into an array with $KeyField as keys
  308. function to_pair($KeyField, $ValField, $Escape = true) {
  309. $Return = array();
  310. while ($Row = mysqli_fetch_array($this->QueryID)) {
  311. if ($Escape) {
  312. $Key = display_str($Row[$KeyField]);
  313. $Val = display_str($Row[$ValField]);
  314. } else {
  315. $Key = $Row[$KeyField];
  316. $Val = $Row[$ValField];
  317. }
  318. $Return[$Key] = $Val;
  319. }
  320. mysqli_data_seek($this->QueryID, 0);
  321. return $Return;
  322. }
  323. // Loops through the result set, collecting the $Key column into an array
  324. function collect($Key, $Escape = true) {
  325. $Return = array();
  326. while ($Row = mysqli_fetch_array($this->QueryID)) {
  327. $Return[] = $Escape ? display_str($Row[$Key]) : $Row[$Key];
  328. }
  329. mysqli_data_seek($this->QueryID, 0);
  330. return $Return;
  331. }
  332. function set_query_id(&$ResultSet) {
  333. $this->QueryID = $ResultSet;
  334. $this->Row = 0;
  335. }
  336. function get_query_id() {
  337. return $this->QueryID;
  338. }
  339. function beginning() {
  340. mysqli_data_seek($this->QueryID, 0);
  341. $this->Row = 0;
  342. }
  343. /**
  344. * This function determines whether the last query caused warning messages
  345. * and stores them in $this->Queries.
  346. */
  347. function warnings() {
  348. $Warnings = array();
  349. if (!is_bool($this->LinkID) && mysqli_warning_count($this->LinkID)) {
  350. $e = mysqli_get_warnings($this->LinkID);
  351. do {
  352. if ($e->errno == 1592) {
  353. // 1592: Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT.
  354. continue;
  355. }
  356. $Warnings[] = 'Code ' . $e->errno . ': ' . display_str($e->message);
  357. } while ($e->next());
  358. }
  359. $this->Queries[count($this->Queries) - 1][2] = $Warnings;
  360. }
  361. }
  362. ?>