国内流行的内容管理系统(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.

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