BioTorrents.de’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 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. <?php
  2. #declare(strict_types = 1);
  3. //-----------------------------------------------------------------------------------
  4. /////////////////////////////////////////////////////////////////////////////////////
  5. /*//-- MySQL wrapper class ----------------------------------------------------------
  6. This class provides an interface to mysqli. You should always use this class instead
  7. of the mysql/mysqli functions, because this class provides debugging features and a
  8. bunch of other cool stuff.
  9. Everything returned by this class is automatically escaped for output. This can be
  10. turned off by setting $Escape to false in next_record or to_array.
  11. //--------- Basic usage -------------------------------------------------------------
  12. * Creating the object.
  13. require(SERVER_ROOT.'/classes/mysql.class.php');
  14. $DB = NEW DB_MYSQL;
  15. -----
  16. * Making a query
  17. $DB->query("
  18. SELECT *
  19. FROM table...");
  20. Is functionally equivalent to using mysqli_query("SELECT * FROM table...")
  21. Stores the result set in $this->QueryID
  22. Returns the result set, so you can save it for later (see set_query_id())
  23. -----
  24. * Getting data from a query
  25. $array = $DB->next_record();
  26. Is functionally equivalent to using mysqli_fetch_array($ResultSet)
  27. You do not need to specify a result set - it uses $this-QueryID
  28. -----
  29. * Escaping a string
  30. db_string($str);
  31. Is a wrapper for mysqli_real_escape_string().
  32. USE THIS FUNCTION EVERY TIME YOU QUERY USER-SUPPLIED INPUT!
  33. //--------- Advanced usage ---------------------------------------------------------
  34. * The conventional way of retrieving a row from a result set is as follows:
  35. list($All, $Columns, $That, $You, $Select) = $DB->next_record();
  36. -----
  37. * This is how you loop over the result set:
  38. while (list($All, $Columns, $That, $You, $Select) = $DB->next_record()) {
  39. echo "Do stuff with $All of the ".$Columns.$That.$You.$Select;
  40. }
  41. -----
  42. * There are also a couple more mysqli functions that have been wrapped. They are:
  43. record_count()
  44. Wrapper to mysqli_num_rows()
  45. affected_rows()
  46. Wrapper to mysqli_affected_rows()
  47. inserted_id()
  48. Wrapper to mysqli_insert_id()
  49. close
  50. Wrapper to mysqli_close()
  51. -----
  52. * And, of course, a few handy custom functions.
  53. to_array($Key = false)
  54. Transforms an entire result set into an array (useful in situations where you
  55. can't order the rows properly in the query).
  56. If $Key is set, the function uses $Key as the index (good for looking up a
  57. field). Otherwise, it uses an iterator.
  58. For an example of this function in action, check out forum.php.
  59. collect($Key)
  60. Loops over the result set, creating an array from one of the fields ($Key).
  61. For an example, see forum.php.
  62. set_query_id($ResultSet)
  63. This class can only hold one result set at a time. Using set_query_id allows
  64. you to set the result set that the class is using to the result set in
  65. $ResultSet. This result set should have been obtained earlier by using
  66. $DB->query().
  67. Example:
  68. $FoodRS = $DB->query("
  69. SELECT *
  70. FROM food");
  71. $DB->query("
  72. SELECT *
  73. FROM drink");
  74. $Drinks = $DB->next_record();
  75. $DB->set_query_id($FoodRS);
  76. $Food = $DB->next_record();
  77. Of course, this example is contrived, but you get the point.
  78. -------------------------------------------------------------------------------------
  79. *///---------------------------------------------------------------------------------
  80. if (!extension_loaded('mysqli')) {
  81. error('Mysqli Extension not loaded.');
  82. }
  83. /**
  84. * db_string
  85. * Handles escaping
  86. */
  87. function db_string($String, $DisableWildcards = false)
  88. {
  89. global $DB;
  90. $DB->connect(0);
  91. # Connect and mysqli_real_escape_string()
  92. # Previously called $DB->escape_str, now below
  93. # todo: Fix the bad escapes everywhere; see below
  94. #if (!is_string($String)) { # This is the correct way,
  95. if (is_array($String)) { # but this prevents errors
  96. error('Attempted to escape non-string.', $NoHTML = true);
  97. $String = '';
  98. } else {
  99. $String = mysqli_real_escape_string($DB->LinkID, $String);
  100. }
  101. // Remove user input wildcards
  102. if ($DisableWildcards) {
  103. $String = str_replace(array('%','_'), array('\%','\_'), $String);
  104. }
  105. return $String;
  106. }
  107. /**
  108. * db_array
  109. */
  110. function db_array($Array, $DontEscape = [], $Quote = false)
  111. {
  112. foreach ($Array as $Key => $Val) {
  113. if (!in_array($Key, $DontEscape)) {
  114. if ($Quote) {
  115. $Array[$Key] = '\''.db_string(trim($Val)).'\'';
  116. } else {
  117. $Array[$Key] = db_string(trim($Val));
  118. }
  119. }
  120. }
  121. return $Array;
  122. }
  123. class DB_MYSQL
  124. {
  125. public $LinkID = false;
  126. protected $QueryID = false;
  127. protected $StatementID = false;
  128. protected $PreparedQuery = false;
  129. protected $Record = [];
  130. protected $Row;
  131. protected $Errno = 0;
  132. protected $Error = '';
  133. public $Queries = [];
  134. public $Time = 0.0;
  135. protected $Database = '';
  136. protected $Server = '';
  137. protected $User = '';
  138. protected $Pass = '';
  139. protected $Port = 0;
  140. protected $Socket = '';
  141. protected $Key = '';
  142. protected $Cert = '';
  143. protected $CA = '';
  144. /**
  145. * __construct
  146. */
  147. public function __construct(
  148. $Database = null,
  149. $User = null,
  150. $Pass = null,
  151. $Server = null,
  152. $Port = null,
  153. $Socket = null,
  154. $Key = null,
  155. $Cert = null,
  156. $CA = null
  157. ) {
  158. $ENV = ENV::go();
  159. $this->Database = $ENV->getPriv('SQLDB');
  160. $this->User = $ENV->getPriv('SQLLOGIN');
  161. $this->Pass = $ENV->getPriv('SQLPASS');
  162. $this->Server = $ENV->getPriv('SQLHOST');
  163. $this->Port = $ENV->getPriv('SQLPORT');
  164. $this->Socket = $ENV->getPriv('SQLSOCK');
  165. $this->Key = $ENV->getPriv('SQL_KEY');
  166. $this->Cert = $ENV->getPriv('SQL_CERT');
  167. $this->CA = $ENV->getPriv('SQL_CA');
  168. }
  169. /**
  170. * halt
  171. */
  172. public function halt($Msg)
  173. {
  174. global $Debug, $argv;
  175. $DBError = 'MySQL: '.strval($Msg).' SQL error: '.strval($this->Errno).' ('.strval($this->Error).')';
  176. if ($this->Errno === 1194) {
  177. send_irc(ADMIN_CHAN, $this->Error);
  178. }
  179. $Debug->analysis('!dev DB Error', $DBError, 3600 * 24);
  180. if (DEBUG_MODE || check_perms('site_debug') || isset($argv[1])) {
  181. echo '<pre>'.display_str($DBError).'</pre>';
  182. if (DEBUG_MODE || check_perms('site_debug')) {
  183. print_r($this->Queries);
  184. }
  185. error(400, $NoHTML = true);
  186. } else {
  187. error(-1, $NoHTML = true);
  188. }
  189. }
  190. /**
  191. * connect
  192. */
  193. public function connect()
  194. {
  195. if (!$this->LinkID) {
  196. $this->LinkID = mysqli_init();
  197. mysqli_ssl_set(
  198. $this->LinkID,
  199. $this->Key,
  200. $this->Cert,
  201. $this->CA,
  202. null,
  203. null
  204. );
  205. mysqli_real_connect(
  206. $this->LinkID,
  207. $this->Server,
  208. $this->User,
  209. $this->Pass,
  210. $this->Database,
  211. $this->Port,
  212. $this->Socket,
  213. MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT
  214. );
  215. if (!$this->LinkID) {
  216. $this->Errno = mysqli_connect_errno();
  217. $this->Error = mysqli_connect_error();
  218. $this->halt('Connection failed (host:'.$this->Server.':'.$this->Port.')');
  219. }
  220. }
  221. mysqli_set_charset($this->LinkID, "utf8mb4");
  222. }
  223. /**
  224. * prepare_query
  225. */
  226. public function prepare_query($Query, &...$BindVars)
  227. {
  228. $this->connect();
  229. $this->StatementID = mysqli_prepare($this->LinkID, $Query);
  230. if (!empty($BindVars)) {
  231. $Types = '';
  232. $TypeMap = ['string'=>'s', 'double'=>'d', 'integer'=>'i', 'boolean'=>'i'];
  233. foreach ($BindVars as $BindVar) {
  234. $Types .= $TypeMap[gettype($BindVar)] ?? 'b';
  235. }
  236. mysqli_stmt_bind_param($this->StatementID, $Types, ...$BindVars);
  237. }
  238. $this->PreparedQuery = $Query;
  239. return $this->StatementID;
  240. }
  241. /**
  242. * exec_prepared_query
  243. */
  244. public function exec_prepared_query()
  245. {
  246. $QueryStartTime = microtime(true);
  247. mysqli_stmt_execute($this->StatementID);
  248. $this->QueryID = mysqli_stmt_get_result($this->StatementID);
  249. $QueryRunTime = (microtime(true) - $QueryStartTime) * 1000;
  250. $this->Queries[] = [$this->PreppedQuery, $QueryRunTime, null];
  251. $this->Time += $QueryRunTime;
  252. }
  253. /**
  254. * Runs a raw query assuming pre-sanitized input. However, attempting to self sanitize (such
  255. * as via db_string) is still not as safe for using prepared statements so for queries
  256. * involving user input, you really should not use this function (instead opting for
  257. * prepared_query) {@See DB_MYSQL::prepared_query}
  258. *
  259. * When running a batch of queries using the same statement
  260. * with a variety of inputs, it's more performant to reuse the statement
  261. * with {@see DB_MYSQL::prepare} and {@see DB_MYSQL::execute}
  262. *
  263. * @return mysqli_result|bool Returns a mysqli_result object
  264. * for successful SELECT queries,
  265. * or TRUE for other successful DML queries
  266. * or FALSE on failure.
  267. *
  268. * @param $Query
  269. * @param int $AutoHandle
  270. * @return mysqli_result|bool
  271. */
  272. public function query($Query, &...$BindVars)
  273. {
  274. /**
  275. * If there was a previous query, we store the warnings. We cannot do
  276. * this immediately after mysqli_query because mysqli_insert_id will
  277. * break otherwise due to mysqli_get_warnings sending a SHOW WARNINGS;
  278. * query. When sending a query, however, we're sure that we won't call
  279. * mysqli_insert_id (or any similar function, for that matter) later on,
  280. * so we can safely get the warnings without breaking things.
  281. * Note that this means that we have to call $this->warnings manually
  282. * for the last query!
  283. */
  284. global $Debug;
  285. if ($this->QueryID) {
  286. $this->warnings();
  287. }
  288. $QueryStartTime = microtime(true);
  289. $this->connect();
  290. // In the event of a MySQL deadlock, we sleep allowing MySQL time to unlock, then attempt again for a maximum of 5 tries
  291. for ($i = 1; $i < 6; $i++) {
  292. $this->StatementID = mysqli_prepare($this->LinkID, $Query);
  293. if (!empty($BindVars)) {
  294. $Types = '';
  295. $TypeMap = ['string'=>'s', 'double'=>'d', 'integer'=>'i', 'boolean'=>'i'];
  296. foreach ($BindVars as $BindVar) {
  297. $Types .= $TypeMap[gettype($BindVar)] ?? 'b';
  298. }
  299. mysqli_stmt_bind_param($this->StatementID, $Types, ...$BindVars);
  300. }
  301. mysqli_stmt_execute($this->StatementID);
  302. $this->QueryID = mysqli_stmt_get_result($this->StatementID);
  303. if (DEBUG_MODE) {
  304. // In DEBUG_MODE, return the full trace on a SQL error (super useful
  305. // For debugging). do not attempt to retry to query
  306. if (!$this->QueryID) {
  307. echo '<pre>' . mysqli_error($this->LinkID) . '<br><br>';
  308. debug_print_backtrace();
  309. echo '</pre>';
  310. error();
  311. }
  312. }
  313. if (!in_array(mysqli_errno($this->LinkID), array(1213, 1205))) {
  314. break;
  315. }
  316. $Debug->analysis('Non-Fatal Deadlock:', $Query, 3600 * 24);
  317. trigger_error("Database deadlock, attempt $i");
  318. sleep($i * rand(2, 5)); // Wait longer as attempts increase
  319. }
  320. $QueryEndTime = microtime(true);
  321. $this->Queries[] = array($Query, ($QueryEndTime - $QueryStartTime) * 1000, null);
  322. $this->Time += ($QueryEndTime - $QueryStartTime) * 1000;
  323. if (!$this->QueryID && !$this->StatementID) {
  324. $this->Errno = mysqli_errno($this->LinkID);
  325. $this->Error = mysqli_error($this->LinkID);
  326. $this->halt("Invalid Query: $Query");
  327. }
  328. $this->Row = 0;
  329. return $this->QueryID;
  330. }
  331. /**
  332. * inserted_id
  333. */
  334. public function inserted_id()
  335. {
  336. if ($this->LinkID) {
  337. return mysqli_insert_id($this->LinkID);
  338. }
  339. }
  340. /**
  341. * next_record
  342. */
  343. public function next_record($Type = MYSQLI_BOTH, $Escape = true)
  344. { // $Escape can be true, false, or an array of keys to not escape
  345. if ($this->LinkID) {
  346. $this->Record = mysqli_fetch_array($this->QueryID, $Type);
  347. $this->Row++;
  348. if (!is_array($this->Record)) {
  349. $this->QueryID = false;
  350. } elseif ($Escape !== false) {
  351. $this->Record = Misc::display_array($this->Record, $Escape);
  352. }
  353. return $this->Record;
  354. }
  355. }
  356. /**
  357. * close
  358. */
  359. public function close()
  360. {
  361. if ($this->LinkID) {
  362. if (!mysqli_close($this->LinkID)) {
  363. $this->halt('Cannot close connection or connection did not open.');
  364. }
  365. $this->LinkID = false;
  366. }
  367. }
  368. /**
  369. * Returns an integer with the number of rows found
  370. * Returns a string if the number of rows found exceeds MAXINT
  371. */
  372. public function record_count()
  373. {
  374. if ($this->QueryID) {
  375. return mysqli_num_rows($this->QueryID);
  376. }
  377. }
  378. /**
  379. * Returns true if the query exists and there were records found
  380. * Returns false if the query does not exist or if there were 0 records returned
  381. */
  382. public function has_results()
  383. {
  384. return ($this->QueryID && $this->record_count() !== 0);
  385. }
  386. /**
  387. * affected_rows
  388. */
  389. public function affected_rows()
  390. {
  391. if ($this->LinkID) {
  392. return mysqli_affected_rows($this->LinkID);
  393. }
  394. }
  395. /**
  396. * info
  397. */
  398. public function info()
  399. {
  400. return mysqli_get_host_info($this->LinkID);
  401. }
  402. // Creates an array from a result set
  403. // If $Key is set, use the $Key column in the result set as the array key
  404. // Otherwise, use an integer
  405. public function to_array($Key = false, $Type = MYSQLI_BOTH, $Escape = true)
  406. {
  407. $Return = [];
  408. while ($Row = mysqli_fetch_array($this->QueryID, $Type)) {
  409. if ($Escape !== false) {
  410. $Row = Misc::display_array($Row, $Escape);
  411. }
  412. if ($Key !== false) {
  413. $Return[$Row[$Key]] = $Row;
  414. } else {
  415. $Return[] = $Row;
  416. }
  417. }
  418. mysqli_data_seek($this->QueryID, 0);
  419. return $Return;
  420. }
  421. // Loops through the result set, collecting the $ValField column into an array with $KeyField as keys
  422. public function to_pair($KeyField, $ValField, $Escape = true)
  423. {
  424. $Return = [];
  425. while ($Row = mysqli_fetch_array($this->QueryID)) {
  426. if ($Escape) {
  427. $Key = display_str($Row[$KeyField]);
  428. $Val = display_str($Row[$ValField]);
  429. } else {
  430. $Key = $Row[$KeyField];
  431. $Val = $Row[$ValField];
  432. }
  433. $Return[$Key] = $Val;
  434. }
  435. mysqli_data_seek($this->QueryID, 0);
  436. return $Return;
  437. }
  438. // Loops through the result set, collecting the $Key column into an array
  439. public function collect($Key, $Escape = true)
  440. {
  441. $Return = [];
  442. while ($Row = mysqli_fetch_array($this->QueryID)) {
  443. $Return[] = $Escape ? display_str($Row[$Key]) : $Row[$Key];
  444. }
  445. mysqli_data_seek($this->QueryID, 0);
  446. return $Return;
  447. }
  448. /**
  449. * Useful extras from OPS
  450. */
  451. /**
  452. * Runs a prepared_query using placeholders and returns the matched row.
  453. * Stashes the current query id so that this can be used within a block
  454. * that is looping over an active resultset.
  455. *
  456. * @param string $sql The parameterized query to run
  457. * @param mixed $args The values of the placeholders
  458. * @return array resultset or null
  459. */
  460. public function row($Query, &...$BindVars)
  461. {
  462. $qid = $this->get_query_id();
  463. $this->query($Query, ...$BindVars);
  464. $result = $this->next_record(MYSQLI_NUM, false);
  465. $this->set_query_id($qid);
  466. return $result;
  467. }
  468. /**
  469. * Runs a prepared_query using placeholders and returns the first element
  470. * of the first row.
  471. * Stashes the current query id so that this can be used within a block
  472. * that is looping over an active resultset.
  473. *
  474. * @param string $sql The parameterized query to run
  475. * @param mixed $args The values of the placeholders
  476. * @return mixed value or null
  477. */
  478. public function scalar($Query, &...$BindVars)
  479. {
  480. $qid = $this->get_query_id();
  481. $this->query($Query, ...$BindVars);
  482. $result = $this->has_results() ? $this->next_record(MYSQLI_NUM, false) : [null];
  483. $this->set_query_id($qid);
  484. return $result[0];
  485. }
  486. # End OPS additions
  487. /**
  488. * set_query_id
  489. */
  490. public function set_query_id(&$ResultSet)
  491. {
  492. $this->QueryID = $ResultSet;
  493. $this->Row = 0;
  494. }
  495. /**
  496. * get_query_id
  497. */
  498. public function get_query_id()
  499. {
  500. return $this->QueryID;
  501. }
  502. /**
  503. * beginning
  504. */
  505. public function beginning()
  506. {
  507. mysqli_data_seek($this->QueryID, 0);
  508. $this->Row = 0;
  509. }
  510. /**
  511. * This function determines whether the last query caused warning messages
  512. * and stores them in $this->Queries
  513. */
  514. public function warnings()
  515. {
  516. $Warnings = [];
  517. if (!is_bool($this->LinkID) && mysqli_warning_count($this->LinkID)) {
  518. $e = mysqli_get_warnings($this->LinkID);
  519. do {
  520. if ($e->errno === 1592) {
  521. // 1592: Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT
  522. continue;
  523. }
  524. $Warnings[] = 'Code ' . $e->errno . ': ' . display_str($e->message);
  525. } while ($e->next());
  526. }
  527. $this->Queries[count($this->Queries) - 1][2] = $Warnings;
  528. }
  529. }