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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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. # Needed for self-signed certs
  215. MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT
  216. );
  217. if (!$this->LinkID) {
  218. $this->Errno = mysqli_connect_errno();
  219. $this->Error = mysqli_connect_error();
  220. $this->halt('Connection failed (host:'.$this->Server.':'.$this->Port.')');
  221. }
  222. }
  223. mysqli_set_charset($this->LinkID, "utf8mb4");
  224. }
  225. /**
  226. * prepare_query
  227. */
  228. public function prepare_query($Query, &...$BindVars)
  229. {
  230. $this->connect();
  231. $this->StatementID = mysqli_prepare($this->LinkID, $Query);
  232. if (!empty($BindVars)) {
  233. $Types = '';
  234. $TypeMap = ['string'=>'s', 'double'=>'d', 'integer'=>'i', 'boolean'=>'i'];
  235. foreach ($BindVars as $BindVar) {
  236. $Types .= $TypeMap[gettype($BindVar)] ?? 'b';
  237. }
  238. mysqli_stmt_bind_param($this->StatementID, $Types, ...$BindVars);
  239. }
  240. $this->PreparedQuery = $Query;
  241. return $this->StatementID;
  242. }
  243. /**
  244. * exec_prepared_query
  245. */
  246. public function exec_prepared_query()
  247. {
  248. $QueryStartTime = microtime(true);
  249. mysqli_stmt_execute($this->StatementID);
  250. $this->QueryID = mysqli_stmt_get_result($this->StatementID);
  251. $QueryRunTime = (microtime(true) - $QueryStartTime) * 1000;
  252. $this->Queries[] = [$this->PreppedQuery, $QueryRunTime, null];
  253. $this->Time += $QueryRunTime;
  254. }
  255. /**
  256. * Runs a raw query assuming pre-sanitized input. However, attempting to self sanitize (such
  257. * as via db_string) is still not as safe for using prepared statements so for queries
  258. * involving user input, you really should not use this function (instead opting for
  259. * prepared_query) {@See DB_MYSQL::prepared_query}
  260. *
  261. * When running a batch of queries using the same statement
  262. * with a variety of inputs, it's more performant to reuse the statement
  263. * with {@see DB_MYSQL::prepare} and {@see DB_MYSQL::execute}
  264. *
  265. * @return mysqli_result|bool Returns a mysqli_result object
  266. * for successful SELECT queries,
  267. * or TRUE for other successful DML queries
  268. * or FALSE on failure.
  269. *
  270. * @param $Query
  271. * @param int $AutoHandle
  272. * @return mysqli_result|bool
  273. */
  274. public function query($Query, &...$BindVars)
  275. {
  276. /**
  277. * If there was a previous query, we store the warnings. We cannot do
  278. * this immediately after mysqli_query because mysqli_insert_id will
  279. * break otherwise due to mysqli_get_warnings sending a SHOW WARNINGS;
  280. * query. When sending a query, however, we're sure that we won't call
  281. * mysqli_insert_id (or any similar function, for that matter) later on,
  282. * so we can safely get the warnings without breaking things.
  283. * Note that this means that we have to call $this->warnings manually
  284. * for the last query!
  285. */
  286. global $Debug;
  287. if ($this->QueryID) {
  288. $this->warnings();
  289. }
  290. $QueryStartTime = microtime(true);
  291. $this->connect();
  292. // In the event of a MySQL deadlock, we sleep allowing MySQL time to unlock, then attempt again for a maximum of 5 tries
  293. for ($i = 1; $i < 6; $i++) {
  294. $this->StatementID = mysqli_prepare($this->LinkID, $Query);
  295. if (!empty($BindVars)) {
  296. $Types = '';
  297. $TypeMap = ['string'=>'s', 'double'=>'d', 'integer'=>'i', 'boolean'=>'i'];
  298. foreach ($BindVars as $BindVar) {
  299. $Types .= $TypeMap[gettype($BindVar)] ?? 'b';
  300. }
  301. mysqli_stmt_bind_param($this->StatementID, $Types, ...$BindVars);
  302. }
  303. mysqli_stmt_execute($this->StatementID);
  304. $this->QueryID = mysqli_stmt_get_result($this->StatementID);
  305. if (DEBUG_MODE) {
  306. // In DEBUG_MODE, return the full trace on a SQL error (super useful
  307. // For debugging). do not attempt to retry to query
  308. if (!$this->QueryID) {
  309. echo '<pre>' . mysqli_error($this->LinkID) . '<br><br>';
  310. debug_print_backtrace();
  311. echo '</pre>';
  312. error();
  313. }
  314. }
  315. if (!in_array(mysqli_errno($this->LinkID), array(1213, 1205))) {
  316. break;
  317. }
  318. $Debug->analysis('Non-Fatal Deadlock:', $Query, 3600 * 24);
  319. trigger_error("Database deadlock, attempt $i");
  320. sleep($i * rand(2, 5)); // Wait longer as attempts increase
  321. }
  322. $QueryEndTime = microtime(true);
  323. $this->Queries[] = array($Query, ($QueryEndTime - $QueryStartTime) * 1000, null);
  324. $this->Time += ($QueryEndTime - $QueryStartTime) * 1000;
  325. if (!$this->QueryID && !$this->StatementID) {
  326. $this->Errno = mysqli_errno($this->LinkID);
  327. $this->Error = mysqli_error($this->LinkID);
  328. $this->halt("Invalid Query: $Query");
  329. }
  330. $this->Row = 0;
  331. return $this->QueryID;
  332. }
  333. /**
  334. * inserted_id
  335. */
  336. public function inserted_id()
  337. {
  338. if ($this->LinkID) {
  339. return mysqli_insert_id($this->LinkID);
  340. }
  341. }
  342. /**
  343. * next_record
  344. */
  345. public function next_record($Type = MYSQLI_BOTH, $Escape = true)
  346. { // $Escape can be true, false, or an array of keys to not escape
  347. if ($this->LinkID) {
  348. $this->Record = mysqli_fetch_array($this->QueryID, $Type);
  349. $this->Row++;
  350. if (!is_array($this->Record)) {
  351. $this->QueryID = false;
  352. } elseif ($Escape !== false) {
  353. $this->Record = Misc::display_array($this->Record, $Escape);
  354. }
  355. return $this->Record;
  356. }
  357. }
  358. /**
  359. * close
  360. */
  361. public function close()
  362. {
  363. if ($this->LinkID) {
  364. if (!mysqli_close($this->LinkID)) {
  365. $this->halt('Cannot close connection or connection did not open.');
  366. }
  367. $this->LinkID = false;
  368. }
  369. }
  370. /**
  371. * Returns an integer with the number of rows found
  372. * Returns a string if the number of rows found exceeds MAXINT
  373. */
  374. public function record_count()
  375. {
  376. if ($this->QueryID) {
  377. return mysqli_num_rows($this->QueryID);
  378. }
  379. }
  380. /**
  381. * Returns true if the query exists and there were records found
  382. * Returns false if the query does not exist or if there were 0 records returned
  383. */
  384. public function has_results()
  385. {
  386. return ($this->QueryID && $this->record_count() !== 0);
  387. }
  388. /**
  389. * affected_rows
  390. */
  391. public function affected_rows()
  392. {
  393. if ($this->LinkID) {
  394. return mysqli_affected_rows($this->LinkID);
  395. }
  396. }
  397. /**
  398. * info
  399. */
  400. public function info()
  401. {
  402. return mysqli_get_host_info($this->LinkID);
  403. }
  404. // Creates an array from a result set
  405. // If $Key is set, use the $Key column in the result set as the array key
  406. // Otherwise, use an integer
  407. public function to_array($Key = false, $Type = MYSQLI_BOTH, $Escape = true)
  408. {
  409. $Return = [];
  410. while ($Row = mysqli_fetch_array($this->QueryID, $Type)) {
  411. if ($Escape !== false) {
  412. $Row = Misc::display_array($Row, $Escape);
  413. }
  414. if ($Key !== false) {
  415. $Return[$Row[$Key]] = $Row;
  416. } else {
  417. $Return[] = $Row;
  418. }
  419. }
  420. mysqli_data_seek($this->QueryID, 0);
  421. return $Return;
  422. }
  423. // Loops through the result set, collecting the $ValField column into an array with $KeyField as keys
  424. public function to_pair($KeyField, $ValField, $Escape = true)
  425. {
  426. $Return = [];
  427. while ($Row = mysqli_fetch_array($this->QueryID)) {
  428. if ($Escape) {
  429. $Key = display_str($Row[$KeyField]);
  430. $Val = display_str($Row[$ValField]);
  431. } else {
  432. $Key = $Row[$KeyField];
  433. $Val = $Row[$ValField];
  434. }
  435. $Return[$Key] = $Val;
  436. }
  437. mysqli_data_seek($this->QueryID, 0);
  438. return $Return;
  439. }
  440. // Loops through the result set, collecting the $Key column into an array
  441. public function collect($Key, $Escape = true)
  442. {
  443. $Return = [];
  444. while ($Row = mysqli_fetch_array($this->QueryID)) {
  445. $Return[] = $Escape ? display_str($Row[$Key]) : $Row[$Key];
  446. }
  447. mysqli_data_seek($this->QueryID, 0);
  448. return $Return;
  449. }
  450. /**
  451. * Useful extras from OPS
  452. */
  453. /**
  454. * Runs a prepared_query using placeholders and returns the matched row.
  455. * Stashes the current query id so that this can be used within a block
  456. * that is looping over an active resultset.
  457. *
  458. * @param string $sql The parameterized query to run
  459. * @param mixed $args The values of the placeholders
  460. * @return array resultset or null
  461. */
  462. public function row($Query, &...$BindVars)
  463. {
  464. $qid = $this->get_query_id();
  465. $this->query($Query, ...$BindVars);
  466. $result = $this->next_record(MYSQLI_NUM, false);
  467. $this->set_query_id($qid);
  468. return $result;
  469. }
  470. /**
  471. * Runs a prepared_query using placeholders and returns the first element
  472. * of the first row.
  473. * Stashes the current query id so that this can be used within a block
  474. * that is looping over an active resultset.
  475. *
  476. * @param string $sql The parameterized query to run
  477. * @param mixed $args The values of the placeholders
  478. * @return mixed value or null
  479. */
  480. public function scalar($Query, &...$BindVars)
  481. {
  482. $qid = $this->get_query_id();
  483. $this->query($Query, ...$BindVars);
  484. $result = $this->has_results() ? $this->next_record(MYSQLI_NUM, false) : [null];
  485. $this->set_query_id($qid);
  486. return $result[0];
  487. }
  488. # End OPS additions
  489. /**
  490. * set_query_id
  491. */
  492. public function set_query_id(&$ResultSet)
  493. {
  494. $this->QueryID = $ResultSet;
  495. $this->Row = 0;
  496. }
  497. /**
  498. * get_query_id
  499. */
  500. public function get_query_id()
  501. {
  502. return $this->QueryID;
  503. }
  504. /**
  505. * beginning
  506. */
  507. public function beginning()
  508. {
  509. mysqli_data_seek($this->QueryID, 0);
  510. $this->Row = 0;
  511. }
  512. /**
  513. * This function determines whether the last query caused warning messages
  514. * and stores them in $this->Queries
  515. */
  516. public function warnings()
  517. {
  518. $Warnings = [];
  519. if (!is_bool($this->LinkID) && mysqli_warning_count($this->LinkID)) {
  520. $e = mysqli_get_warnings($this->LinkID);
  521. do {
  522. if ($e->errno === 1592) {
  523. // 1592: Unsafe statement written to the binary log using statement format since BINLOG_FORMAT = STATEMENT
  524. continue;
  525. }
  526. $Warnings[] = 'Code ' . $e->errno . ': ' . display_str($e->message);
  527. } while ($e->next());
  528. }
  529. $this->Queries[count($this->Queries) - 1][2] = $Warnings;
  530. }
  531. }