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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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->prepared_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->prepared_query().
  67. Example:
  68. $FoodRS = $DB->prepared_query("
  69. SELECT *
  70. FROM food");
  71. $DB->prepared_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. /**
  81. * db_string
  82. *
  83. * Handles escaping.
  84. */
  85. function db_string($String, $DisableWildcards = false)
  86. {
  87. global $DB;
  88. $DB->connect(0);
  89. # Connect and mysqli_real_escape_string()
  90. # Previously called $DB->escape_str, now below
  91. # todo: Fix the bad escapes everywhere; see below
  92. #if (!is_string($String)) { # This is the correct way,
  93. if (is_array($String)) { # but this prevents errors
  94. error('Attempted to escape non-string.', $NoHTML = true);
  95. $String = '';
  96. } else {
  97. $String = mysqli_real_escape_string($DB->LinkID, $String);
  98. }
  99. // Remove user input wildcards
  100. if ($DisableWildcards) {
  101. $String = str_replace(array('%','_'), array('\%','\_'), $String);
  102. }
  103. return $String;
  104. }
  105. /**
  106. * db_array
  107. */
  108. function db_array($Array, $DontEscape = [], $Quote = false)
  109. {
  110. foreach ($Array as $Key => $Val) {
  111. if (!in_array($Key, $DontEscape)) {
  112. if ($Quote) {
  113. $Array[$Key] = '\''.db_string(trim($Val)).'\'';
  114. } else {
  115. $Array[$Key] = db_string(trim($Val));
  116. }
  117. }
  118. }
  119. return $Array;
  120. }
  121. class DB_MYSQL
  122. {
  123. public $LinkID = false;
  124. protected $QueryID = false;
  125. protected $StatementID = false;
  126. protected $PreparedQuery = false;
  127. protected $Record = [];
  128. protected $Row;
  129. protected $Errno = 0;
  130. protected $Error = '';
  131. public $Queries = [];
  132. public $Time = 0.0;
  133. protected $Database = '';
  134. protected $Server = '';
  135. protected $User = '';
  136. protected $Pass = '';
  137. protected $Port = 0;
  138. protected $Socket = '';
  139. protected $Key = '';
  140. protected $Cert = '';
  141. protected $CA = '';
  142. /**
  143. * __construct
  144. */
  145. public function __construct(
  146. $Database = null,
  147. $User = null,
  148. $Pass = null,
  149. $Server = null,
  150. $Port = null,
  151. $Socket = null,
  152. $Key = null,
  153. $Cert = null,
  154. $CA = null
  155. ) {
  156. $ENV = ENV::go();
  157. $this->Database = $ENV->getPriv('SQLDB');
  158. $this->User = $ENV->getPriv('SQLLOGIN');
  159. $this->Pass = $ENV->getPriv('SQLPASS');
  160. $this->Server = $ENV->getPriv('SQLHOST');
  161. $this->Port = $ENV->getPriv('SQLPORT');
  162. $this->Socket = $ENV->getPriv('SQLSOCK');
  163. $this->Key = $ENV->getPriv('SQL_KEY');
  164. $this->Cert = $ENV->getPriv('SQL_CERT');
  165. $this->CA = $ENV->getPriv('SQL_CA');
  166. }
  167. /**
  168. * halt
  169. */
  170. public function halt($Msg)
  171. {
  172. global $Debug, $argv;
  173. $DBError = 'MySQL: '.strval($Msg).' SQL error: '.strval($this->Errno).' ('.strval($this->Error).')';
  174. if ($this->Errno === 1194) {
  175. send_irc(ADMIN_CHAN, $this->Error);
  176. }
  177. $Debug->analysis('!dev DB Error', $DBError, 3600 * 24);
  178. if (DEBUG_MODE || check_perms('site_debug') || isset($argv[1])) {
  179. echo '<pre>'.display_str($DBError).'</pre>';
  180. if (DEBUG_MODE || check_perms('site_debug')) {
  181. print_r($this->Queries);
  182. }
  183. error(400, $NoHTML = true);
  184. } else {
  185. error(-1, $NoHTML = true);
  186. }
  187. }
  188. /**
  189. * connect
  190. */
  191. public function connect()
  192. {
  193. if (!$this->LinkID) {
  194. $this->LinkID = mysqli_init();
  195. mysqli_ssl_set(
  196. $this->LinkID,
  197. $this->Key,
  198. $this->Cert,
  199. $this->CA,
  200. null,
  201. null
  202. );
  203. mysqli_real_connect(
  204. $this->LinkID,
  205. $this->Server,
  206. $this->User,
  207. $this->Pass,
  208. $this->Database,
  209. $this->Port,
  210. $this->Socket,
  211. # Needed for self-signed certs
  212. MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT
  213. );
  214. if (!$this->LinkID) {
  215. $this->Errno = mysqli_connect_errno();
  216. $this->Error = mysqli_connect_error();
  217. $this->halt('Connection failed (host:'.$this->Server.':'.$this->Port.')');
  218. }
  219. }
  220. mysqli_set_charset($this->LinkID, "utf8mb4");
  221. }
  222. /**
  223. * Prepare and execute a prepared query returning the result set.
  224. *
  225. * Utility function that wraps DB_MYSQL::prepare and DB_MYSQL::execute
  226. * as most times, the query is going to be one-off and this will save
  227. * on keystrokes. If you do plan to be executing a prepared query
  228. * multiple times with different bound parameters, you'll want to call
  229. * the two functions separately instead of this function.
  230. *
  231. * @param $Query
  232. * @param mixed ...$Parameters
  233. * @return bool|mysqli_result
  234. */
  235. public function prepared_query($Query, ...$Parameters) {
  236. $this->prepare($Query);
  237. return $this->execute(...$Parameters);
  238. }
  239. /**
  240. * prepare
  241. */
  242. public function prepare($Query, &...$BindVars)
  243. {
  244. $this->connect();
  245. $this->StatementID = mysqli_prepare($this->LinkID, $Query);
  246. if (!empty($BindVars)) {
  247. $Types = '';
  248. $TypeMap = ['string'=>'s', 'double'=>'d', 'integer'=>'i', 'boolean'=>'i'];
  249. foreach ($BindVars as $BindVar) {
  250. $Types .= $TypeMap[gettype($BindVar)] ?? 'b';
  251. }
  252. mysqli_stmt_bind_param($this->StatementID, $Types, ...$BindVars);
  253. }
  254. $this->PreparedQuery = $Query;
  255. return $this->StatementID;
  256. }
  257. # Compatibility function for the old name
  258. public function prepare_query($Query, &...$BindVars)
  259. {
  260. return $this->prepare($Query, $BindVars);
  261. }
  262. /**
  263. * execute
  264. */
  265. public function execute()
  266. {
  267. $QueryStartTime = microtime(true);
  268. mysqli_stmt_execute($this->StatementID);
  269. $this->QueryID = mysqli_stmt_get_result($this->StatementID);
  270. $QueryRunTime = (microtime(true) - $QueryStartTime) * 1000;
  271. $this->Queries[] = [$this->PreppedQuery, $QueryRunTime, null];
  272. $this->Time += $QueryRunTime;
  273. }
  274. # Compatibility function for the old name
  275. public function exec_prepared_query()
  276. {
  277. return $this->execute();
  278. }
  279. /**
  280. * Runs a raw query assuming pre-sanitized input. However, attempting to self sanitize (such
  281. * as via db_string) is still not as safe for using prepared statements so for queries
  282. * involving user input, you really should not use this function (instead opting for
  283. * prepared_query) {@See DB_MYSQL::prepared_query}
  284. *
  285. * When running a batch of queries using the same statement
  286. * with a variety of inputs, it's more performant to reuse the statement
  287. * with {@see DB_MYSQL::prepare} and {@see DB_MYSQL::execute}
  288. *
  289. * @return mysqli_result|bool Returns a mysqli_result object
  290. * for successful SELECT queries,
  291. * or TRUE for other successful DML queries
  292. * or FALSE on failure.
  293. *
  294. * @param $Query
  295. * @param int $AutoHandle
  296. * @return mysqli_result|bool
  297. */
  298. public function query($Query, &...$BindVars)
  299. {
  300. /**
  301. * If there was a previous query, we store the warnings. We cannot do
  302. * this immediately after mysqli_query because mysqli_insert_id will
  303. * break otherwise due to mysqli_get_warnings sending a SHOW WARNINGS;
  304. * query. When sending a query, however, we're sure that we won't call
  305. * mysqli_insert_id (or any similar function, for that matter) later on,
  306. * so we can safely get the warnings without breaking things.
  307. * Note that this means that we have to call $this->warnings manually
  308. * for the last query!
  309. */
  310. global $Debug;
  311. if ($this->QueryID) {
  312. $this->warnings();
  313. }
  314. $QueryStartTime = microtime(true);
  315. $this->connect();
  316. // In the event of a MySQL deadlock, we sleep allowing MySQL time to unlock, then attempt again for a maximum of 5 tries
  317. for ($i = 1; $i < 6; $i++) {
  318. $this->StatementID = mysqli_prepare($this->LinkID, $Query);
  319. if (!empty($BindVars)) {
  320. $Types = '';
  321. $TypeMap = ['string'=>'s', 'double'=>'d', 'integer'=>'i', 'boolean'=>'i'];
  322. foreach ($BindVars as $BindVar) {
  323. $Types .= $TypeMap[gettype($BindVar)] ?? 'b';
  324. }
  325. mysqli_stmt_bind_param($this->StatementID, $Types, ...$BindVars);
  326. }
  327. mysqli_stmt_execute($this->StatementID);
  328. $this->QueryID = mysqli_stmt_get_result($this->StatementID);
  329. if (DEBUG_MODE) {
  330. // In DEBUG_MODE, return the full trace on a SQL error (super useful
  331. // For debugging). do not attempt to retry to query
  332. if (!$this->QueryID) {
  333. echo '<pre>' . mysqli_error($this->LinkID) . '<br><br>';
  334. debug_print_backtrace();
  335. echo '</pre>';
  336. error();
  337. }
  338. }
  339. if (!in_array(mysqli_errno($this->LinkID), array(1213, 1205))) {
  340. break;
  341. }
  342. $Debug->analysis('Non-Fatal Deadlock:', $Query, 3600 * 24);
  343. trigger_error("Database deadlock, attempt $i");
  344. sleep($i * rand(2, 5)); // Wait longer as attempts increase
  345. }
  346. $QueryEndTime = microtime(true);
  347. $this->Queries[] = array($Query, ($QueryEndTime - $QueryStartTime) * 1000, null);
  348. $this->Time += ($QueryEndTime - $QueryStartTime) * 1000;
  349. if (!$this->QueryID && !$this->StatementID) {
  350. $this->Errno = mysqli_errno($this->LinkID);
  351. $this->Error = mysqli_error($this->LinkID);
  352. $this->halt("Invalid Query: $Query");
  353. }
  354. $this->Row = 0;
  355. return $this->QueryID;
  356. }
  357. /**
  358. * inserted_id
  359. */
  360. public function inserted_id()
  361. {
  362. if ($this->LinkID) {
  363. return mysqli_insert_id($this->LinkID);
  364. }
  365. }
  366. /**
  367. * next_record
  368. */
  369. public function next_record($Type = MYSQLI_BOTH, $Escape = true)
  370. { // $Escape can be true, false, or an array of keys to not escape
  371. if ($this->LinkID) {
  372. $this->Record = mysqli_fetch_array($this->QueryID, $Type);
  373. $this->Row++;
  374. if (!is_array($this->Record)) {
  375. $this->QueryID = false;
  376. } elseif ($Escape !== false) {
  377. $this->Record = Misc::display_array($this->Record, $Escape);
  378. }
  379. return $this->Record;
  380. }
  381. }
  382. /**
  383. * close
  384. */
  385. public function close()
  386. {
  387. if ($this->LinkID) {
  388. if (!mysqli_close($this->LinkID)) {
  389. $this->halt('Cannot close connection or connection did not open.');
  390. }
  391. $this->LinkID = false;
  392. }
  393. }
  394. /**
  395. * Returns an integer with the number of rows found
  396. * Returns a string if the number of rows found exceeds MAXINT
  397. */
  398. public function record_count()
  399. {
  400. if ($this->QueryID) {
  401. return mysqli_num_rows($this->QueryID);
  402. }
  403. }
  404. /**
  405. * Returns true if the query exists and there were records found
  406. * Returns false if the query does not exist or if there were 0 records returned
  407. */
  408. public function has_results()
  409. {
  410. return ($this->QueryID && $this->record_count() !== 0);
  411. }
  412. /**
  413. * affected_rows
  414. */
  415. public function affected_rows()
  416. {
  417. if ($this->LinkID) {
  418. return mysqli_affected_rows($this->LinkID);
  419. }
  420. }
  421. /**
  422. * info
  423. */
  424. public function info()
  425. {
  426. return mysqli_get_host_info($this->LinkID);
  427. }
  428. // Creates an array from a result set
  429. // If $Key is set, use the $Key column in the result set as the array key
  430. // Otherwise, use an integer
  431. public function to_array($Key = false, $Type = MYSQLI_BOTH, $Escape = true)
  432. {
  433. $Return = [];
  434. while ($Row = mysqli_fetch_array($this->QueryID, $Type)) {
  435. if ($Escape !== false) {
  436. $Row = Misc::display_array($Row, $Escape);
  437. }
  438. if ($Key !== false) {
  439. $Return[$Row[$Key]] = $Row;
  440. } else {
  441. $Return[] = $Row;
  442. }
  443. }
  444. mysqli_data_seek($this->QueryID, 0);
  445. return $Return;
  446. }
  447. // Loops through the result set, collecting the $ValField column into an array with $KeyField as keys
  448. public function to_pair($KeyField, $ValField, $Escape = true)
  449. {
  450. $Return = [];
  451. while ($Row = mysqli_fetch_array($this->QueryID)) {
  452. if ($Escape) {
  453. $Key = display_str($Row[$KeyField]);
  454. $Val = display_str($Row[$ValField]);
  455. } else {
  456. $Key = $Row[$KeyField];
  457. $Val = $Row[$ValField];
  458. }
  459. $Return[$Key] = $Val;
  460. }
  461. mysqli_data_seek($this->QueryID, 0);
  462. return $Return;
  463. }
  464. // Loops through the result set, collecting the $Key column into an array
  465. public function collect($Key, $Escape = true)
  466. {
  467. $Return = [];
  468. while ($Row = mysqli_fetch_array($this->QueryID)) {
  469. $Return[] = $Escape ? display_str($Row[$Key]) : $Row[$Key];
  470. }
  471. mysqli_data_seek($this->QueryID, 0);
  472. return $Return;
  473. }
  474. /**
  475. * Useful extras from OPS
  476. */
  477. /**
  478. * Runs a prepared_query using placeholders and returns the matched row.
  479. * Stashes the current query id so that this can be used within a block
  480. * that is looping over an active resultset.
  481. *
  482. * @param string $sql The parameterized query to run
  483. * @param mixed $args The values of the placeholders
  484. * @return array resultset or null
  485. */
  486. public function row($Query, &...$BindVars)
  487. {
  488. $qid = $this->get_query_id();
  489. $this->query($Query, ...$BindVars);
  490. $result = $this->next_record(MYSQLI_NUM, false);
  491. $this->set_query_id($qid);
  492. return $result;
  493. }
  494. /**
  495. * Runs a prepared_query using placeholders and returns the first element
  496. * of the first row.
  497. * Stashes the current query id so that this can be used within a block
  498. * that is looping over an active resultset.
  499. *
  500. * @param string $sql The parameterized query to run
  501. * @param mixed $args The values of the placeholders
  502. * @return mixed value or null
  503. */
  504. public function scalar($Query, &...$BindVars)
  505. {
  506. $qid = $this->get_query_id();
  507. $this->query($Query, ...$BindVars);
  508. $result = $this->has_results() ? $this->next_record(MYSQLI_NUM, false) : [null];
  509. $this->set_query_id($qid);
  510. return $result[0];
  511. }
  512. # End OPS additions
  513. /**
  514. * set_query_id
  515. */
  516. public function set_query_id(&$ResultSet)
  517. {
  518. $this->QueryID = $ResultSet;
  519. $this->Row = 0;
  520. }
  521. /**
  522. * get_query_id
  523. */
  524. public function get_query_id()
  525. {
  526. return $this->QueryID;
  527. }
  528. /**
  529. * beginning
  530. */
  531. public function beginning()
  532. {
  533. mysqli_data_seek($this->QueryID, 0);
  534. $this->Row = 0;
  535. }
  536. /**
  537. * This function determines whether the last query caused warning messages
  538. * and stores them in $this->Queries
  539. */
  540. public function warnings()
  541. {
  542. $Warnings = [];
  543. if (!is_bool($this->LinkID) && mysqli_warning_count($this->LinkID)) {
  544. $e = mysqli_get_warnings($this->LinkID);
  545. do {
  546. if ($e->errno === 1592) {
  547. // 1592: Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT
  548. continue;
  549. }
  550. $Warnings[] = 'Code ' . $e->errno . ': ' . display_str($e->message);
  551. } while ($e->next());
  552. }
  553. $this->Queries[count($this->Queries) - 1][2] = $Warnings;
  554. }
  555. }