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

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