国内流行的内容管理系统(CMS)多端全媒体解决方案 https://www.dedebiz.com
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.

698 lines
24KB

  1. <?php
  2. if (!defined('DEDEINC')) exit('dedebiz');
  3. /**
  4. * 数据库类
  5. * 说明:系统底层数据库核心类
  6. * 调用这个类前,请先设定这些外部变量
  7. * $GLOBALS['cfg_dbhost'];
  8. * $GLOBALS['cfg_dbuser'];
  9. * $GLOBALS['cfg_dbpwd'];
  10. * $GLOBALS['cfg_dbname'];
  11. * $GLOBALS['cfg_dbprefix'];
  12. *
  13. * @version $Id: dedesqli.class.php 1 15:00 2011-1-21 tianya $
  14. * @package DedeBIZ.Libraries
  15. * @copyright Copyright (c) 2022, DedeBIZ.COM
  16. * @license https://www.dedebiz.com/license
  17. * @link https://www.dedebiz.com
  18. */
  19. @set_time_limit(0);
  20. // 在工程所有文件中均不需要单独初始化这个类,可直接用 $dsql 或 $db 进行操作
  21. // 为了防止错误,操作完后不必关闭数据库
  22. $dsql = $dsqlitete = $db = new DedeSqlite(FALSE);
  23. /**
  24. * Dede MySQLi数据库类
  25. *
  26. * @package DedeSqli
  27. * @subpackage DedeBIZ.Libraries
  28. * @link https://www.dedebiz.com
  29. */
  30. if (!defined('MYSQL_BOTH')) {
  31. define('MYSQL_BOTH', MYSQLI_BOTH);
  32. }
  33. if (!defined('MYSQL_ASSOC')) {
  34. define('MYSQL_ASSOC', SQLITE3_ASSOC);
  35. }
  36. class DedeSqlite
  37. {
  38. var $linkID;
  39. var $dbHost;
  40. var $dbUser;
  41. var $dbPwd;
  42. var $dbName;
  43. var $dbPrefix;
  44. var $result;
  45. var $queryString;
  46. var $parameters;
  47. var $isClose;
  48. var $safeCheck;
  49. var $showError = false;
  50. var $recordLog = false; //记录日志到data/mysqli_record_log.inc便于进行调试
  51. var $isInit = false;
  52. var $pconnect = false;
  53. var $_fixObject;
  54. //用外部定义的变量初始类,并连接数据库
  55. function __construct($pconnect = FALSE, $nconnect = FALSE)
  56. {
  57. $this->isClose = FALSE;
  58. $this->safeCheck = TRUE;
  59. $this->pconnect = $pconnect;
  60. if ($nconnect) {
  61. $this->Init($pconnect);
  62. }
  63. }
  64. function DedeSql($pconnect = FALSE, $nconnect = TRUE)
  65. {
  66. $this->__construct($pconnect, $nconnect);
  67. }
  68. function Init($pconnect = FALSE)
  69. {
  70. $this->linkID = 0;
  71. //$this->queryString = '';
  72. //$this->parameters = Array();
  73. $this->dbHost = $GLOBALS['cfg_dbhost'];
  74. $this->dbUser = $GLOBALS['cfg_dbuser'];
  75. $this->dbPwd = $GLOBALS['cfg_dbpwd'];
  76. $this->dbName = $GLOBALS['cfg_dbname'];
  77. $this->dbPrefix = $GLOBALS['cfg_dbprefix'];
  78. $this->result["me"] = 0;
  79. $this->Open($pconnect);
  80. }
  81. //用指定参数初始数据库信息
  82. function SetSource($host, $username, $pwd, $dbname, $dbprefix = "dede_")
  83. {
  84. $this->dbHost = $host;
  85. $this->dbUser = $username;
  86. $this->dbPwd = $pwd;
  87. $this->dbName = $dbname;
  88. $this->dbPrefix = $dbprefix;
  89. $this->result["me"] = 0;
  90. }
  91. //设置SQL里的参数
  92. function SetParameter($key, $value)
  93. {
  94. $this->parameters[$key] = $value;
  95. }
  96. //连接数据库
  97. function Open($pconnect = FALSE)
  98. {
  99. global $dsqlite;
  100. //连接数据库
  101. if ($dsqlite && !$dsqlite->isClose && $dsqlite->isInit) {
  102. $this->linkID = $dsqlite->linkID;
  103. } else {
  104. $this->linkID = new SQLite3(DEDEDATA . '/' . $this->dbName . '.db');
  105. //复制一个对象副本
  106. CopySQLiPoint($this);
  107. }
  108. //处理错误,成功连接则选择数据库
  109. if (!$this->linkID) {
  110. $this->DisplayError("DedeBIZ错误警告:<span style='color:#dc3545'>连接数据库失败,可能数据库密码不对或数据库服务器出错</span>");
  111. exit();
  112. }
  113. $this->isInit = TRUE;
  114. return TRUE;
  115. }
  116. //为了防止采集等需要较长运行时间的程序超时,在运行这类程序时设置系统等待和交互时间
  117. function SetLongLink()
  118. {
  119. // @mysqli_query("SET interactive_timeout=3600, wait_timeout=3600 ;", $this->linkID);
  120. }
  121. //获得错误描述
  122. function GetError()
  123. {
  124. $str = $dsqlite->lastErrorMsg();
  125. return $str;
  126. }
  127. //关闭数据库
  128. //mysql能自动管理非持久连接的连接池
  129. //实际上关闭并无意义并且容易出错,所以取消这函数
  130. function Close($isok = FALSE)
  131. {
  132. $this->FreeResultAll();
  133. if ($isok) {
  134. $this->linkID->close();
  135. $this->isClose = TRUE;
  136. $GLOBALS['dsql'] = NULL;
  137. }
  138. }
  139. //定期清理死连接
  140. function ClearErrLink()
  141. {
  142. }
  143. //关闭指定的数据库连接
  144. function CloseLink($dblink)
  145. {
  146. }
  147. function Esc($_str)
  148. {
  149. return addslashes($_str);
  150. }
  151. //执行一个不返回结果的SQL语句,如update,delete,insert等
  152. function ExecuteNoneQuery($sql = '')
  153. {
  154. global $dsqlite;
  155. if (!$dsqlite->isInit) {
  156. $this->Init($this->pconnect);
  157. }
  158. if ($dsqlite->isClose) {
  159. $this->Open(FALSE);
  160. $dsqlite->isClose = FALSE;
  161. }
  162. if (!empty($sql)) {
  163. $this->SetQuery($sql);
  164. } else {
  165. return FALSE;
  166. }
  167. if (is_array($this->parameters)) {
  168. foreach ($this->parameters as $key => $value) {
  169. $this->queryString = str_replace("@" . $key, "'$value'", $this->queryString);
  170. }
  171. }
  172. //SQL语句安全检查
  173. if ($this->safeCheck) CheckSql($this->queryString, 'update');
  174. $t1 = ExecTime();
  175. $rs = $this->linkID->exec($this->queryString);
  176. //查询性能测试
  177. if ($this->recordLog) {
  178. $queryTime = ExecTime() - $t1;
  179. $this->RecordLog($queryTime);
  180. //echo $this->queryString."--{$queryTime}<hr />\r\n";
  181. }
  182. return $rs;
  183. }
  184. //执行一个返回影响记录条数的SQL语句,如update,delete,insert等
  185. function ExecuteNoneQuery2($sql = '')
  186. {
  187. global $dsqlite;
  188. if (!$dsqlite->isInit) {
  189. $this->Init($this->pconnect);
  190. }
  191. if ($dsqlite->isClose) {
  192. $this->Open(FALSE);
  193. $dsqlite->isClose = FALSE;
  194. }
  195. if (!empty($sql)) {
  196. $this->SetQuery($sql);
  197. }
  198. if (is_array($this->parameters)) {
  199. foreach ($this->parameters as $key => $value) {
  200. $this->queryString = str_replace("@" . $key, "'$value'", $this->queryString);
  201. }
  202. }
  203. $t1 = ExecTime();
  204. $this->linkID->exec($this->queryString);
  205. //查询性能测试
  206. if ($this->recordLog) {
  207. $queryTime = ExecTime() - $t1;
  208. $this->RecordLog($queryTime);
  209. //echo $this->queryString."--{$queryTime}<hr />\r\n";
  210. }
  211. return $this->linkID->changes();
  212. }
  213. function ExecNoneQuery($sql = '')
  214. {
  215. return $this->ExecuteNoneQuery($sql);
  216. }
  217. function GetFetchRow($id = 'me')
  218. {
  219. return $this->result[$id]->numColumns();
  220. }
  221. function GetAffectedRows()
  222. {
  223. return $this->linkID->changes();
  224. }
  225. //执行一个带返回结果的SQL语句,如SELECT,SHOW等
  226. function Execute($id = "me", $sql = '')
  227. {
  228. global $dsqlite;
  229. if (!$dsqlite->isInit) {
  230. $this->Init($this->pconnect);
  231. }
  232. if ($dsqlite->isClose) {
  233. $this->Open(FALSE);
  234. $dsqlite->isClose = FALSE;
  235. }
  236. if (!empty($sql)) {
  237. $this->SetQuery($sql);
  238. }
  239. //SQL语句安全检查
  240. if ($this->safeCheck) {
  241. CheckSql($this->queryString);
  242. }
  243. $t1 = ExecTime();
  244. //var_dump($this->queryString);
  245. $this->result[$id] = $this->linkID->query($this->queryString);
  246. //var_dump(mysql_error());
  247. //查询性能测试
  248. if ($this->recordLog) {
  249. $queryTime = ExecTime() - $t1;
  250. $this->RecordLog($queryTime);
  251. //echo $this->queryString."--{$queryTime}<hr />\r\n";
  252. }
  253. if ($this->result[$id] === FALSE) {
  254. $this->DisplayError($this->linkID->lastErrorMsg() . " <br />Error sql: <span style='color:#dc3545'>" . $this->queryString . "</span>");
  255. }
  256. }
  257. function Query($id = "me", $sql = '')
  258. {
  259. $this->Execute($id, $sql);
  260. }
  261. //执行一个SQL语句,返回前一条记录或仅返回一条记录
  262. function GetOne($sql = '', $acctype = SQLITE3_ASSOC)
  263. {
  264. global $dsqlite;
  265. if (!$dsqlite->isInit) {
  266. $this->Init($this->pconnect);
  267. }
  268. if ($dsqlite->isClose) {
  269. $this->Open(FALSE);
  270. $dsqlite->isClose = FALSE;
  271. }
  272. if (!empty($sql)) {
  273. if (!preg_match("/LIMIT/i", $sql)) $this->SetQuery(preg_replace("/[,;]$/i", '', trim($sql)) . " LIMIT 0,1;");
  274. else $this->SetQuery($sql);
  275. }
  276. $this->Execute("one");
  277. $arr = $this->GetArray("one", $acctype);
  278. if (!is_array($arr)) {
  279. return '';
  280. } else {
  281. $this->result["one"]->reset();
  282. return ($arr);
  283. }
  284. }
  285. //执行一个不与任何表名有关的SQL语句,Create等
  286. function ExecuteSafeQuery($sql, $id = "me")
  287. {
  288. global $dsqlite;
  289. if (!$dsqlite->isInit) {
  290. $this->Init($this->pconnect);
  291. }
  292. if ($dsqlite->isClose) {
  293. $this->Open(FALSE);
  294. $dsqlite->isClose = FALSE;
  295. }
  296. $this->result[$id] = $this->linkID->query($sql);
  297. }
  298. //返回当前的一条记录并把游标移向下一记录
  299. //SQLITE3_ASSOC、SQLITE3_NUM、SQLITE3_BOTH
  300. function GetArray($id = "me", $acctype = SQLITE3_ASSOC)
  301. {
  302. switch ($acctype) {
  303. case MYSQL_ASSOC:
  304. $acctype = SQLITE3_ASSOC;
  305. break;
  306. case MYSQL_NUM:
  307. $acctype = SQLITE3_NUM;
  308. break;
  309. default:
  310. $acctype = SQLITE3_BOTH;
  311. break;
  312. }
  313. if ($this->result[$id] === 0) {
  314. return FALSE;
  315. } else {
  316. if ($this->result[$id]) {
  317. $rs = $this->result[$id]->fetchArray($acctype);
  318. if (!$rs) {
  319. $this->result[$id] = 0;
  320. return false;
  321. }
  322. return $rs;
  323. } else {
  324. return false;
  325. }
  326. }
  327. }
  328. function GetObject($id = "me")
  329. {
  330. if (!isset($this->_fixObject[$id])) {
  331. $this->_fixObject[$id] = array();
  332. if ($this->result[$id]) {
  333. while ($row = $this->result[$id]->fetchArray(SQLITE3_ASSOC)) {
  334. $this->_fixObject[$id][] = (object)$row;
  335. }
  336. $this->result[$id]->reset();
  337. }
  338. }
  339. return array_shift($this->_fixObject[$id]);
  340. }
  341. //检测是否存在某数据表
  342. function IsTable($tbname)
  343. {
  344. global $dsqlite;
  345. if (!$dsqlite->isInit) {
  346. $this->Init($this->pconnect);
  347. }
  348. $prefix = "#@__";
  349. $tbname = str_replace($prefix, $GLOBALS['cfg_dbprefix'], $tbname);
  350. $row = $this->linkID->querySingle("PRAGMA table_info({$tbname});");
  351. if ($row !== null) {
  352. return TRUE;
  353. }
  354. return FALSE;
  355. }
  356. //获得MySql的版本号
  357. function GetVersion($isformat = TRUE)
  358. {
  359. global $dsqlite;
  360. if (!$dsqlite->isInit) {
  361. $this->Init($this->pconnect);
  362. }
  363. if ($dsqlite->isClose) {
  364. $this->Open(FALSE);
  365. $dsqlite->isClose = FALSE;
  366. }
  367. $rs = $this->linkID->querySingle("select sqlite_version();");
  368. $sqlite_version = $rs;
  369. if ($isformat) {
  370. $sqlite_versions = explode(".", trim($sqlite_version));
  371. $sqlite_version = number_format($sqlite_versions[0] . "." . $sqlite_versions[1], 2);
  372. }
  373. return $sqlite_version;
  374. }
  375. //获取特定表的信息
  376. function GetTableFields($tbname, $id = "me")
  377. {
  378. global $dsqlite;
  379. if (!$dsqlite->isInit) {
  380. $this->Init($this->pconnect);
  381. }
  382. $prefix = "#@__";
  383. $tbname = str_replace($prefix, $GLOBALS['cfg_dbprefix'], $tbname);
  384. $query = "SELECT * FROM {$tbname} LIMIT 0,1";
  385. $this->result[$id] = $this->linkID->query($query);
  386. }
  387. //获取字段详细信息
  388. function GetFieldObject($id = "me")
  389. {
  390. $cols = $this->result[$id]->numColumns();
  391. $fields = array();
  392. while ($row = $this->result[$id]->fetchArray()) {
  393. for ($i = 1; $i < $cols; $i++) {
  394. $fields[] = $this->result[$id]->columnName($i);
  395. }
  396. }
  397. return (object)$fields;
  398. }
  399. //获得查询的总记录数
  400. function GetTotalRow($id = "me")
  401. {
  402. $queryString = preg_replace("/SELECT(.*)FROM/isU", 'SELECT count(*) as dd FROM', $this->queryString);
  403. $rs = $this->linkID->query($queryString);
  404. $row = $rs->fetchArray();
  405. return $row['dd'];
  406. }
  407. //获取上一步INSERT操作产生的ID
  408. function GetLastID()
  409. {
  410. //如果 AUTO_INCREMENT 的列的类型是 BIGINT,则 mysqli_insert_id() 返回的值将不正确。
  411. //可以在 SQL 查询中用 MySQL 内部的 SQL 函数 LAST_INSERT_ID() 来替代。
  412. //$rs = mysqli_query($this->linkID, "Select LAST_INSERT_ID() as lid");
  413. //$row = mysqli_fetch_array($rs);
  414. //return $row["lid"];
  415. return $this->linkID->lastInsertRowID();
  416. }
  417. //释放记录集占用的资源
  418. function FreeResult($id = "me")
  419. {
  420. if ($this->result[$id]) {
  421. @$this->result[$id]->reset();
  422. }
  423. }
  424. function FreeResultAll()
  425. {
  426. if (!is_array($this->result)) {
  427. return '';
  428. }
  429. foreach ($this->result as $kk => $vv) {
  430. if ($vv) {
  431. @$vv->reset();
  432. }
  433. }
  434. }
  435. //设置SQL语句,会自动把SQL语句里的#@__替换为$this->dbPrefix(在配置文件中为$cfg_dbprefix)
  436. function SetQuery($sql)
  437. {
  438. $prefix = "#@__";
  439. $sql = str_replace($prefix, $GLOBALS['cfg_dbprefix'], $sql);
  440. $this->queryString = $sql;
  441. //$this->queryString = preg_replace("/CONCAT\(',', arc.typeid2, ','\)/i","printf(',%s,', arc.typeid2)",$this->queryString);
  442. if (preg_match("/CONCAT\(([^\)]*?)\)/i", $this->queryString, $matches)) {
  443. $this->queryString = preg_replace("/CONCAT\(([^\)]*?)\)/i", str_replace(",", "||", $matches[1]), $this->queryString);
  444. $this->queryString = str_replace("'||'", "','", $this->queryString);
  445. }
  446. $this->queryString = preg_replace("/FIND_IN_SET\('([\w]+)', arc.flag\)>0/i", "(',' || arc.flag || ',') LIKE '%,\\1,%'", $this->queryString);
  447. $this->queryString = preg_replace("/FIND_IN_SET\('([\w]+)', arc.flag\)<1/i", "(',' || arc.flag || ',') NOT LIKE '%,\\1,%'", $this->queryString);
  448. if (preg_match("/CREATE TABLE/i", $this->queryString)) {
  449. $this->queryString = preg_replace("/[\r\n]/", '', $this->queryString);
  450. $this->queryString = preg_replace('/character set (.*?) /i', '', $this->queryString);
  451. $this->queryString = preg_replace('/unsigned/i', '', $this->queryString);
  452. $this->queryString = str_replace('TYPE=MyISAM', '', $this->queryString);
  453. $this->queryString = preg_replace('/TINYINT\(([\d]+)\)/i', 'INTEGER', $this->queryString);
  454. $this->queryString = preg_replace('/mediumint\(([\d]+)\)/i', 'INTEGER', $this->queryString);
  455. $this->queryString = preg_replace('/smallint\(([\d]+)\)/i', 'INTEGER', $this->queryString);
  456. $this->queryString = preg_replace('/int\(([\d]+)\)/i', 'INTEGER', $this->queryString);
  457. $this->queryString = preg_replace('/auto_increment/i', 'PRIMARY KEY AUTOINCREMENT', $this->queryString);
  458. $this->queryString = preg_replace('/, KEY(.*?)MyISAM;/i', '', $this->queryString);
  459. $this->queryString = preg_replace('/, KEY(.*?);/i', ');', $this->queryString);
  460. $this->queryString = preg_replace('/, UNIQUE KEY(.*?);/i', ');', $this->queryString);
  461. $this->queryString = preg_replace('/set\(([^\)]*?)\)/', 'varchar', $this->queryString);
  462. $this->queryString = preg_replace('/enum\(([^\)]*?)\)/', 'varchar', $this->queryString);
  463. if (preg_match("/PRIMARY KEY AUTOINCREMENT/", $this->queryString)) {
  464. $this->queryString = preg_replace('/,([\t\s ]+)PRIMARY KEY \(`([0-9a-zA-Z]+)`\)/i', '', $this->queryString);
  465. $this->queryString = str_replace(', PRIMARY KEY (`id`)', '', $this->queryString);
  466. }
  467. }
  468. $this->queryString = preg_replace("/SHOW fields FROM `([\w]+)`/i", "PRAGMA table_info('\\1') ", $this->queryString);
  469. $this->queryString = preg_replace("/SHOW CREATE TABLE .([\w]+)/i", "SELECT 0,sql FROM sqlite_master WHERE name='\\1'; ", $this->queryString);
  470. //var_dump($this->queryString);
  471. $this->queryString = preg_replace("/Show Tables/i", "SELECT name FROM sqlite_master WHERE type = \"table\"", $this->queryString);
  472. $this->queryString = str_replace("\'", "\"", $this->queryString);
  473. $this->queryString = str_replace('\t\n', "", $this->queryString);
  474. //var_dump($this->queryString);
  475. }
  476. function SetSql($sql)
  477. {
  478. $this->SetQuery($sql);
  479. }
  480. function RecordLog($runtime = 0)
  481. {
  482. $RecordLogFile = dirname(__FILE__) . '/../data/mysqli_record_log.inc';
  483. $url = $this->GetCurUrl();
  484. $savemsg = <<<EOT
  485. ------------------------------------------
  486. SQL:{$this->queryString}
  487. Page:$url
  488. Runtime:$runtime
  489. EOT;
  490. $fp = @fopen($RecordLogFile, 'a');
  491. @fwrite($fp, $savemsg);
  492. @fclose($fp);
  493. }
  494. //显示数据链接错误信息
  495. function DisplayError($msg)
  496. {
  497. $errorTrackFile = dirname(__FILE__) . '/../data/mysqli_error_trace.inc';
  498. if (file_exists(dirname(__FILE__) . '/../data/mysqli_error_trace.php')) {
  499. @unlink(dirname(__FILE__) . '/../data/mysqli_error_trace.php');
  500. }
  501. if ($this->showError) {
  502. $emsg = '';
  503. $emsg .= "<div><h3>DedeBIZ Error Warning!</h3>\r\n";
  504. $emsg .= "<div><a href='https://www.dedebiz.com' target='_blank' style='color:#dc3545'>Technical Support: https://www.dedebiz.com</a></div>";
  505. $emsg .= "<div style='line-helght:160%;font-size:14px;color:green'>\r\n";
  506. $emsg .= "<div style='color:blue'><br />Error page: <span style='color:#dc3545'>" . $this->GetCurUrl() . "</span></div>\r\n";
  507. $emsg .= "<div>Error infos: {$msg}</div>\r\n";
  508. $emsg .= "<br /></div></div>\r\n";
  509. echo $emsg;
  510. }
  511. $savemsg = 'Page: ' . $this->GetCurUrl() . "\r\nError: " . $msg . "\r\nTime" . date('Y-m-d H:i:s');
  512. //保存MySql错误日志
  513. $fp = @fopen($errorTrackFile, 'a');
  514. @fwrite($fp, '<' . '?php exit();' . "\r\n/*\r\n{$savemsg}\r\n*/\r\n?" . ">\r\n");
  515. @fclose($fp);
  516. }
  517. //获得当前的脚本网址
  518. function GetCurUrl()
  519. {
  520. if (!empty($_SERVER["REQUEST_URI"])) {
  521. $scriptName = $_SERVER["REQUEST_URI"];
  522. $nowurl = $scriptName;
  523. } else {
  524. $scriptName = $_SERVER["PHP_SELF"];
  525. if (empty($_SERVER["QUERY_STRING"])) {
  526. $nowurl = $scriptName;
  527. } else {
  528. $nowurl = $scriptName . "?" . $_SERVER["QUERY_STRING"];
  529. }
  530. }
  531. return $nowurl;
  532. }
  533. }
  534. //复制一个对象副本
  535. function CopySQLiPoint(&$ndsql)
  536. {
  537. $GLOBALS['dsqlite'] = $ndsql;
  538. }
  539. //SQL语句过滤程序,由80sec提供,这里作了适当的修改
  540. if (!function_exists('CheckSql')) {
  541. function CheckSql($db_string, $querytype = 'select')
  542. {
  543. global $cfg_cookie_encode;
  544. $clean = '';
  545. $error = '';
  546. $old_pos = 0;
  547. $pos = -1;
  548. $log_file = DEDEINC . '/../data/' . md5($cfg_cookie_encode) . '_safe.txt';
  549. $userIP = GetIP();
  550. $getUrl = GetCurUrl();
  551. //如果是普通查询语句,直接过滤一些特殊语法
  552. if ($querytype == 'select') {
  553. $notallow1 = "[^0-9a-z@\._-]{1,}(union|sleep|benchmark|load_file|outfile)[^0-9a-z@\.-]{1,}";
  554. //$notallow2 = "--|/\*";
  555. if (preg_match("/" . $notallow1 . "/i", $db_string)) {
  556. fputs(fopen($log_file, 'a+'), "$userIP||$getUrl||$db_string||SelectBreak\r\n");
  557. exit("<span style='color:#dc3545'>Safe Alert: Request Error step 1 !</span>");
  558. }
  559. }
  560. //完整的SQL检查
  561. while (TRUE) {
  562. $pos = strpos($db_string, '\'', $pos + 1);
  563. if ($pos === FALSE) {
  564. break;
  565. }
  566. $clean .= substr($db_string, $old_pos, $pos - $old_pos);
  567. while (TRUE) {
  568. $pos1 = strpos($db_string, '\'', $pos + 1);
  569. $pos2 = strpos($db_string, '\\', $pos + 1);
  570. if ($pos1 === FALSE) {
  571. break;
  572. } elseif ($pos2 == FALSE || $pos2 > $pos1) {
  573. $pos = $pos1;
  574. break;
  575. }
  576. $pos = $pos2 + 1;
  577. }
  578. $clean .= '$s$';
  579. $old_pos = $pos + 1;
  580. }
  581. $clean .= substr($db_string, $old_pos);
  582. $clean = trim(strtolower(preg_replace(array('~\s+~s'), array(' '), $clean)));
  583. if (
  584. strpos($clean, '@') !== FALSE or strpos($clean, 'char(') !== FALSE or strpos($clean, '"') !== FALSE
  585. or strpos($clean, '$s$$s$') !== FALSE
  586. ) {
  587. $fail = TRUE;
  588. if (preg_match("#^create table#i", $clean)) $fail = FALSE;
  589. $error = "unusual character";
  590. }
  591. //老版本的Mysql并不支持union,常用的程序里也不使用union,但是一些黑客使用它,所以检查它
  592. if (strpos($clean, 'union') !== FALSE && preg_match('~(^|[^a-z])union($|[^[a-z])~s', $clean) != 0) {
  593. $fail = TRUE;
  594. $error = "union detect";
  595. }
  596. //发布版本的程序可能比较少包括--,#这样的注释,但是黑客经常使用它们
  597. elseif (strpos($clean, '/*') > 2 || strpos($clean, '--') !== FALSE || strpos($clean, '#') !== FALSE) {
  598. $fail = TRUE;
  599. $error = "comment detect";
  600. }
  601. //这些函数不会被使用,但是黑客会用它来操作文件,down掉数据库
  602. elseif (strpos($clean, 'sleep') !== FALSE && preg_match('~(^|[^a-z])sleep($|[^[a-z])~s', $clean) != 0) {
  603. $fail = TRUE;
  604. $error = "slown down detect";
  605. } elseif (strpos($clean, 'benchmark') !== FALSE && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0) {
  606. $fail = TRUE;
  607. $error = "slown down detect";
  608. } elseif (strpos($clean, 'load_file') !== FALSE && preg_match('~(^|[^a-z])load_file($|[^[a-z])~s', $clean) != 0) {
  609. $fail = TRUE;
  610. $error = "file fun detect";
  611. } elseif (strpos($clean, 'into outfile') !== FALSE && preg_match('~(^|[^a-z])into\s+outfile($|[^[a-z])~s', $clean) != 0) {
  612. $fail = TRUE;
  613. $error = "file fun detect";
  614. }
  615. //老版本的MYSQL不支持子查询,我们的程序里可能也用得少,但是黑客可以使用它来查询数据库敏感信息
  616. elseif (preg_match('~\([^)]*?select~s', $clean) != 0) {
  617. $fail = TRUE;
  618. $error = "sub select detect";
  619. }
  620. if (!empty($fail)) {
  621. fputs(fopen($log_file, 'a+'), "$userIP||$getUrl||$db_string||$error\r\n");
  622. exit("<span>Safe Alert: Request Error step 2!</span>");
  623. } else {
  624. return $db_string;
  625. }
  626. }
  627. }