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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. }
  162. function query($Query, $AutoHandle = 1) {
  163. global $Debug;
  164. /*
  165. * If there was a previous query, we store the warnings. We cannot do
  166. * this immediately after mysqli_query because mysqli_insert_id will
  167. * break otherwise due to mysqli_get_warnings sending a SHOW WARNINGS;
  168. * query. When sending a query, however, we're sure that we won't call
  169. * mysqli_insert_id (or any similar function, for that matter) later on,
  170. * so we can safely get the warnings without breaking things.
  171. * Note that this means that we have to call $this->warnings manually
  172. * for the last query!
  173. */
  174. if ($this->QueryID) {
  175. $this->warnings();
  176. }
  177. $QueryStartTime = microtime(true);
  178. $this->connect();
  179. // In the event of a MySQL deadlock, we sleep allowing MySQL time to unlock, then attempt again for a maximum of 5 tries
  180. for ($i = 1; $i < 6; $i++) {
  181. $this->QueryID = mysqli_query($this->LinkID, $Query);
  182. if (!in_array(mysqli_errno($this->LinkID), array(1213, 1205))) {
  183. break;
  184. }
  185. $Debug->analysis('Non-Fatal Deadlock:', $Query, 3600 * 24);
  186. trigger_error("Database deadlock, attempt $i");
  187. sleep($i * rand(2, 5)); // Wait longer as attempts increase
  188. }
  189. $QueryEndTime = microtime(true);
  190. $this->Queries[] = array($Query, ($QueryEndTime - $QueryStartTime) * 1000, null);
  191. $this->Time += ($QueryEndTime - $QueryStartTime) * 1000;
  192. if (!$this->QueryID) {
  193. $this->Errno = mysqli_errno($this->LinkID);
  194. $this->Error = mysqli_error($this->LinkID);
  195. if ($AutoHandle) {
  196. $this->halt("Invalid Query: $Query");
  197. } else {
  198. return $this->Errno;
  199. }
  200. }
  201. /*
  202. $QueryType = substr($Query, 0, 6);
  203. if ($QueryType === 'DELETE' || $QueryType === 'UPDATE') {
  204. if ($this->affected_rows() > 50) {
  205. $Debug->analysis($this->affected_rows().' rows altered:', $Query, 3600 * 24);
  206. }
  207. }
  208. */
  209. $this->Row = 0;
  210. if ($AutoHandle) {
  211. return $this->QueryID;
  212. }
  213. }
  214. function query_unb($Query) {
  215. $this->connect();
  216. mysqli_real_query($this->LinkID, $Query);
  217. }
  218. function inserted_id() {
  219. if ($this->LinkID) {
  220. return mysqli_insert_id($this->LinkID);
  221. }
  222. }
  223. function next_record($Type = MYSQLI_BOTH, $Escape = true) { // $Escape can be true, false, or an array of keys to not escape
  224. if ($this->LinkID) {
  225. $this->Record = mysqli_fetch_array($this->QueryID, $Type);
  226. $this->Row++;
  227. if (!is_array($this->Record)) {
  228. $this->QueryID = false;
  229. } elseif ($Escape !== false) {
  230. $this->Record = Misc::display_array($this->Record, $Escape);
  231. }
  232. return $this->Record;
  233. }
  234. }
  235. function close() {
  236. if ($this->LinkID) {
  237. if (!mysqli_close($this->LinkID)) {
  238. $this->halt('Cannot close connection or connection did not open.');
  239. }
  240. $this->LinkID = false;
  241. }
  242. }
  243. /*
  244. * returns an integer with the number of rows found
  245. * returns a string if the number of rows found exceeds MAXINT
  246. */
  247. function record_count() {
  248. if ($this->QueryID) {
  249. return mysqli_num_rows($this->QueryID);
  250. }
  251. }
  252. /*
  253. * returns true if the query exists and there were records found
  254. * returns false if the query does not exist or if there were 0 records returned
  255. */
  256. function has_results() {
  257. return ($this->QueryID && $this->record_count() !== 0);
  258. }
  259. function affected_rows() {
  260. if ($this->LinkID) {
  261. return mysqli_affected_rows($this->LinkID);
  262. }
  263. }
  264. function info() {
  265. return mysqli_get_host_info($this->LinkID);
  266. }
  267. // You should use db_string() instead.
  268. function escape_str($Str) {
  269. $this->connect(0);
  270. if (is_array($Str)) {
  271. trigger_error('Attempted to escape array.');
  272. return '';
  273. }
  274. return mysqli_real_escape_string($this->LinkID, $Str);
  275. }
  276. // Creates an array from a result set
  277. // If $Key is set, use the $Key column in the result set as the array key
  278. // Otherwise, use an integer
  279. function to_array($Key = false, $Type = MYSQLI_BOTH, $Escape = true) {
  280. $Return = array();
  281. while ($Row = mysqli_fetch_array($this->QueryID, $Type)) {
  282. if ($Escape !== false) {
  283. $Row = Misc::display_array($Row, $Escape);
  284. }
  285. if ($Key !== false) {
  286. $Return[$Row[$Key]] = $Row;
  287. } else {
  288. $Return[] = $Row;
  289. }
  290. }
  291. mysqli_data_seek($this->QueryID, 0);
  292. return $Return;
  293. }
  294. // Loops through the result set, collecting the $ValField column into an array with $KeyField as keys
  295. function to_pair($KeyField, $ValField, $Escape = true) {
  296. $Return = array();
  297. while ($Row = mysqli_fetch_array($this->QueryID)) {
  298. if ($Escape) {
  299. $Key = display_str($Row[$KeyField]);
  300. $Val = display_str($Row[$ValField]);
  301. } else {
  302. $Key = $Row[$KeyField];
  303. $Val = $Row[$ValField];
  304. }
  305. $Return[$Key] = $Val;
  306. }
  307. mysqli_data_seek($this->QueryID, 0);
  308. return $Return;
  309. }
  310. // Loops through the result set, collecting the $Key column into an array
  311. function collect($Key, $Escape = true) {
  312. $Return = array();
  313. while ($Row = mysqli_fetch_array($this->QueryID)) {
  314. $Return[] = $Escape ? display_str($Row[$Key]) : $Row[$Key];
  315. }
  316. mysqli_data_seek($this->QueryID, 0);
  317. return $Return;
  318. }
  319. function set_query_id(&$ResultSet) {
  320. $this->QueryID = $ResultSet;
  321. $this->Row = 0;
  322. }
  323. function get_query_id() {
  324. return $this->QueryID;
  325. }
  326. function beginning() {
  327. mysqli_data_seek($this->QueryID, 0);
  328. $this->Row = 0;
  329. }
  330. /**
  331. * This function determines whether the last query caused warning messages
  332. * and stores them in $this->Queries.
  333. */
  334. function warnings() {
  335. $Warnings = array();
  336. if (!is_bool($this->LinkID) && mysqli_warning_count($this->LinkID)) {
  337. $e = mysqli_get_warnings($this->LinkID);
  338. do {
  339. if ($e->errno == 1592) {
  340. // 1592: Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT.
  341. continue;
  342. }
  343. $Warnings[] = 'Code ' . $e->errno . ': ' . display_str($e->message);
  344. } while ($e->next());
  345. }
  346. $this->Queries[count($this->Queries) - 1][2] = $Warnings;
  347. }
  348. }
  349. ?>