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

692 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 = mysqli_error($this->linkID);
  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 = MYSQLI_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. $rs = $this->result[$id]->fetchArray($acctype);
  317. if (!$rs) {
  318. $this->result[$id] = 0;
  319. return false;
  320. }
  321. return $rs;
  322. }
  323. }
  324. function GetObject($id = "me")
  325. {
  326. if (!isset($this->_fixObject[$id])) {
  327. $this->_fixObject[$id] = array();
  328. while ($row = $this->result[$id]->fetchArray(SQLITE3_ASSOC)) {
  329. $this->_fixObject[$id][] = (object)$row;
  330. }
  331. $this->result[$id]->reset();
  332. }
  333. return array_shift($this->_fixObject[$id]);
  334. }
  335. //检测是否存在某数据表
  336. function IsTable($tbname)
  337. {
  338. global $dsqlite;
  339. if (!$dsqlite->isInit) {
  340. $this->Init($this->pconnect);
  341. }
  342. $prefix = "#@__";
  343. $tbname = str_replace($prefix, $GLOBALS['cfg_dbprefix'], $tbname);
  344. $row = $this->linkID->querySingle("PRAGMA table_info({$tbname});");
  345. if ($row !== null) {
  346. return TRUE;
  347. }
  348. return FALSE;
  349. }
  350. //获得MySql的版本号
  351. function GetVersion($isformat = TRUE)
  352. {
  353. global $dsqlite;
  354. if (!$dsqlite->isInit) {
  355. $this->Init($this->pconnect);
  356. }
  357. if ($dsqlite->isClose) {
  358. $this->Open(FALSE);
  359. $dsqlite->isClose = FALSE;
  360. }
  361. $rs = $this->linkID->querySingle("select sqlite_version();");
  362. $sqlite_version = $rs;
  363. if ($isformat) {
  364. $sqlite_versions = explode(".", trim($sqlite_version));
  365. $sqlite_version = number_format($sqlite_versions[0].".".$sqlite_versions[1], 2);
  366. }
  367. return $sqlite_version;
  368. }
  369. //获取特定表的信息
  370. function GetTableFields($tbname, $id = "me")
  371. {
  372. global $dsqlite;
  373. if (!$dsqlite->isInit) {
  374. $this->Init($this->pconnect);
  375. }
  376. $prefix = "#@__";
  377. $tbname = str_replace($prefix, $GLOBALS['cfg_dbprefix'], $tbname);
  378. $query = "SELECT * FROM {$tbname} LIMIT 0,1";
  379. $this->result[$id] = $this->linkID->query($query);
  380. }
  381. //获取字段详细信息
  382. function GetFieldObject($id = "me")
  383. {
  384. $cols = $this->result[$id]->numColumns();
  385. $fields = array();
  386. while ($row = $this->result[$id]->fetchArray()) {
  387. for ($i = 1; $i < $cols; $i++) {
  388. $fields[] = $this->result[$id]->columnName($i);
  389. }
  390. }
  391. return (object)$fields;
  392. }
  393. //获得查询的总记录数
  394. function GetTotalRow($id = "me")
  395. {
  396. $queryString = preg_replace("/SELECT(.*)FROM/isU", 'SELECT count(*) as dd FROM', $this->queryString);
  397. $rs = $this->linkID->query($queryString);
  398. $row = $rs->fetchArray();
  399. return $row['dd'];
  400. }
  401. //获取上一步INSERT操作产生的ID
  402. function GetLastID()
  403. {
  404. //如果 AUTO_INCREMENT 的列的类型是 BIGINT,则 mysqli_insert_id() 返回的值将不正确。
  405. //可以在 SQL 查询中用 MySQL 内部的 SQL 函数 LAST_INSERT_ID() 来替代。
  406. //$rs = mysqli_query($this->linkID, "Select LAST_INSERT_ID() as lid");
  407. //$row = mysqli_fetch_array($rs);
  408. //return $row["lid"];
  409. return $this->linkID->lastInsertRowID();
  410. }
  411. //释放记录集占用的资源
  412. function FreeResult($id = "me")
  413. {
  414. if ($this->result[$id]) {
  415. @$this->result[$id]->reset();
  416. }
  417. }
  418. function FreeResultAll()
  419. {
  420. if (!is_array($this->result)) {
  421. return '';
  422. }
  423. foreach ($this->result as $kk => $vv) {
  424. if ($vv) {
  425. @$vv->reset();
  426. }
  427. }
  428. }
  429. //设置SQL语句,会自动把SQL语句里的#@__替换为$this->dbPrefix(在配置文件中为$cfg_dbprefix)
  430. function SetQuery($sql)
  431. {
  432. $prefix = "#@__";
  433. $sql = str_replace($prefix, $GLOBALS['cfg_dbprefix'], $sql);
  434. $this->queryString = $sql;
  435. //$this->queryString = preg_replace("/CONCAT\(',', arc.typeid2, ','\)/i","printf(',%s,', arc.typeid2)",$this->queryString);
  436. if (preg_match("/CONCAT\(([^\)]*?)\)/i", $this->queryString, $matches)) {
  437. $this->queryString = preg_replace("/CONCAT\(([^\)]*?)\)/i", str_replace(",", "||", $matches[1]), $this->queryString);
  438. $this->queryString = str_replace("'||'", "','", $this->queryString);
  439. }
  440. $this->queryString = preg_replace("/FIND_IN_SET\('([\w]+)', arc.flag\)>0/i", "(',' || arc.flag || ',') LIKE '%,\\1,%'", $this->queryString);
  441. $this->queryString = preg_replace("/FIND_IN_SET\('([\w]+)', arc.flag\)<1/i", "(',' || arc.flag || ',') NOT LIKE '%,\\1,%'", $this->queryString);
  442. if (preg_match("/CREATE TABLE/i", $this->queryString)) {
  443. $this->queryString = preg_replace("/[\r\n]/", '', $this->queryString);
  444. $this->queryString = preg_replace('/character set (.*?) /i', '', $this->queryString);
  445. $this->queryString = preg_replace('/unsigned/i', '', $this->queryString);
  446. $this->queryString = str_replace('TYPE=MyISAM', '', $this->queryString);
  447. $this->queryString = preg_replace('/TINYINT\(([\d]+)\)/i', 'INTEGER', $this->queryString);
  448. $this->queryString = preg_replace('/mediumint\(([\d]+)\)/i', 'INTEGER', $this->queryString);
  449. $this->queryString = preg_replace('/smallint\(([\d]+)\)/i', 'INTEGER', $this->queryString);
  450. $this->queryString = preg_replace('/int\(([\d]+)\)/i', 'INTEGER', $this->queryString);
  451. $this->queryString = preg_replace('/auto_increment/i', 'PRIMARY KEY AUTOINCREMENT', $this->queryString);
  452. $this->queryString = preg_replace('/, KEY(.*?)MyISAM;/i', '', $this->queryString);
  453. $this->queryString = preg_replace('/, KEY(.*?);/i', ');', $this->queryString);
  454. $this->queryString = preg_replace('/, UNIQUE KEY(.*?);/i', ');', $this->queryString);
  455. $this->queryString = preg_replace('/set\(([^\)]*?)\)/', 'varchar', $this->queryString);
  456. $this->queryString = preg_replace('/enum\(([^\)]*?)\)/', 'varchar', $this->queryString);
  457. if (preg_match("/PRIMARY KEY AUTOINCREMENT/", $this->queryString)) {
  458. $this->queryString = preg_replace('/,([\t\s ]+)PRIMARY KEY \(`([0-9a-zA-Z]+)`\)/i', '', $this->queryString);
  459. $this->queryString = str_replace(', PRIMARY KEY (`id`)', '', $this->queryString);
  460. }
  461. }
  462. $this->queryString = preg_replace("/SHOW fields FROM `([\w]+)`/i", "PRAGMA table_info('\\1') ", $this->queryString);
  463. $this->queryString = preg_replace("/SHOW CREATE TABLE .([\w]+)/i", "SELECT 0,sql FROM sqlite_master WHERE name='\\1'; ", $this->queryString);
  464. //var_dump($this->queryString);
  465. $this->queryString = preg_replace("/Show Tables/i", "SELECT name FROM sqlite_master WHERE type = \"table\"", $this->queryString);
  466. $this->queryString = str_replace("\'", "\"", $this->queryString);
  467. $this->queryString = str_replace('\t\n', "", $this->queryString);
  468. //var_dump($this->queryString);
  469. }
  470. function SetSql($sql)
  471. {
  472. $this->SetQuery($sql);
  473. }
  474. function RecordLog($runtime = 0)
  475. {
  476. $RecordLogFile = dirname(__FILE__).'/../data/mysqli_record_log.inc';
  477. $url = $this->GetCurUrl();
  478. $savemsg = <<<EOT
  479. ------------------------------------------
  480. SQL:{$this->queryString}
  481. Page:$url
  482. Runtime:$runtime
  483. EOT;
  484. $fp = @fopen($RecordLogFile, 'a');
  485. @fwrite($fp, $savemsg);
  486. @fclose($fp);
  487. }
  488. //显示数据链接错误信息
  489. function DisplayError($msg)
  490. {
  491. $errorTrackFile = dirname(__FILE__).'/../data/mysqli_error_trace.inc';
  492. if (file_exists(dirname(__FILE__).'/../data/mysqli_error_trace.php')) {
  493. @unlink(dirname(__FILE__).'/../data/mysqli_error_trace.php');
  494. }
  495. if ($this->showError) {
  496. $emsg = '';
  497. $emsg .= "<div><h3>DedeBIZ Error Warning!</h3>\r\n";
  498. $emsg .= "<div><a href='https://www.dedebiz.com' target='_blank' style='color:red'>Technical Support: https://www.dedebiz.com</a></div>";
  499. $emsg .= "<div style='line-helght:160%;font-size:14px;color:green'>\r\n";
  500. $emsg .= "<div style='color:blue'><br>Error page: <span style='color:#dc3545'>".$this->GetCurUrl()."</span></div>\r\n";
  501. $emsg .= "<div>Error infos: {$msg}</div>\r\n";
  502. $emsg .= "<br></div></div>\r\n";
  503. echo $emsg;
  504. }
  505. $savemsg = 'Page: '.$this->GetCurUrl()."\r\nError: ".$msg."\r\nTime".date('Y-m-d H:i:s');
  506. //保存MySql错误日志
  507. $fp = @fopen($errorTrackFile, 'a');
  508. @fwrite($fp, '<'.'?php exit();'."\r\n/*\r\n{$savemsg}\r\n*/\r\n?".">\r\n");
  509. @fclose($fp);
  510. }
  511. //获得当前的脚本网址
  512. function GetCurUrl()
  513. {
  514. if (!empty($_SERVER["REQUEST_URI"])) {
  515. $scriptName = $_SERVER["REQUEST_URI"];
  516. $nowurl = $scriptName;
  517. } else {
  518. $scriptName = $_SERVER["PHP_SELF"];
  519. if (empty($_SERVER["QUERY_STRING"])) {
  520. $nowurl = $scriptName;
  521. } else {
  522. $nowurl = $scriptName."?".$_SERVER["QUERY_STRING"];
  523. }
  524. }
  525. return $nowurl;
  526. }
  527. }
  528. //复制一个对象副本
  529. function CopySQLiPoint(&$ndsql)
  530. {
  531. $GLOBALS['dsqlite'] = $ndsql;
  532. }
  533. //SQL语句过滤程序,由80sec提供,这里作了适当的修改
  534. if (!function_exists('CheckSql')) {
  535. function CheckSql($db_string, $querytype = 'select')
  536. {
  537. global $cfg_cookie_encode;
  538. $clean = '';
  539. $error = '';
  540. $old_pos = 0;
  541. $pos = -1;
  542. $log_file = DEDEINC.'/../data/'.md5($cfg_cookie_encode).'_safe.txt';
  543. $userIP = GetIP();
  544. $getUrl = GetCurUrl();
  545. //如果是普通查询语句,直接过滤一些特殊语法
  546. if ($querytype == 'select') {
  547. $notallow1 = "[^0-9a-z@\._-]{1,}(union|sleep|benchmark|load_file|outfile)[^0-9a-z@\.-]{1,}";
  548. //$notallow2 = "--|/\*";
  549. if (preg_match("/".$notallow1."/i", $db_string)) {
  550. fputs(fopen($log_file, 'a+'), "$userIP||$getUrl||$db_string||SelectBreak\r\n");
  551. exit("<span>Safe Alert: Request Error step 1 !</span>");
  552. }
  553. }
  554. //完整的SQL检查
  555. while (TRUE) {
  556. $pos = strpos($db_string, '\'', $pos + 1);
  557. if ($pos === FALSE) {
  558. break;
  559. }
  560. $clean .= substr($db_string, $old_pos, $pos - $old_pos);
  561. while (TRUE) {
  562. $pos1 = strpos($db_string, '\'', $pos + 1);
  563. $pos2 = strpos($db_string, '\\', $pos + 1);
  564. if ($pos1 === FALSE) {
  565. break;
  566. } elseif ($pos2 == FALSE || $pos2 > $pos1) {
  567. $pos = $pos1;
  568. break;
  569. }
  570. $pos = $pos2 + 1;
  571. }
  572. $clean .= '$s$';
  573. $old_pos = $pos + 1;
  574. }
  575. $clean .= substr($db_string, $old_pos);
  576. $clean = trim(strtolower(preg_replace(array('~\s+~s'), array(' '), $clean)));
  577. if (
  578. strpos($clean, '@') !== FALSE or strpos($clean, 'char(') !== FALSE or strpos($clean, '"') !== FALSE
  579. or strpos($clean, '$s$$s$') !== FALSE
  580. ) {
  581. $fail = TRUE;
  582. if (preg_match("#^create table#i", $clean)) $fail = FALSE;
  583. $error = "unusual character";
  584. }
  585. //老版本的Mysql并不支持union,常用的程序里也不使用union,但是一些黑客使用它,所以检查它
  586. if (strpos($clean, 'union') !== FALSE && preg_match('~(^|[^a-z])union($|[^[a-z])~s', $clean) != 0) {
  587. $fail = TRUE;
  588. $error = "union detect";
  589. }
  590. //发布版本的程序可能比较少包括--,#这样的注释,但是黑客经常使用它们
  591. elseif (strpos($clean, '/*') > 2 || strpos($clean, '--') !== FALSE || strpos($clean, '#') !== FALSE) {
  592. $fail = TRUE;
  593. $error = "comment detect";
  594. }
  595. //这些函数不会被使用,但是黑客会用它来操作文件,down掉数据库
  596. elseif (strpos($clean, 'sleep') !== FALSE && preg_match('~(^|[^a-z])sleep($|[^[a-z])~s', $clean) != 0) {
  597. $fail = TRUE;
  598. $error = "slown down detect";
  599. } elseif (strpos($clean, 'benchmark') !== FALSE && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0) {
  600. $fail = TRUE;
  601. $error = "slown down detect";
  602. } elseif (strpos($clean, 'load_file') !== FALSE && preg_match('~(^|[^a-z])load_file($|[^[a-z])~s', $clean) != 0) {
  603. $fail = TRUE;
  604. $error = "file fun detect";
  605. } elseif (strpos($clean, 'into outfile') !== FALSE && preg_match('~(^|[^a-z])into\s+outfile($|[^[a-z])~s', $clean) != 0) {
  606. $fail = TRUE;
  607. $error = "file fun detect";
  608. }
  609. //老版本的MYSQL不支持子查询,我们的程序里可能也用得少,但是黑客可以使用它来查询数据库敏感信息
  610. elseif (preg_match('~\([^)]*?select~s', $clean) != 0) {
  611. $fail = TRUE;
  612. $error = "sub select detect";
  613. }
  614. if (!empty($fail)) {
  615. fputs(fopen($log_file, 'a+'), "$userIP||$getUrl||$db_string||$error\r\n");
  616. exit("<span>Safe Alert: Request Error step 2!</span>");
  617. } else {
  618. return $db_string;
  619. }
  620. }
  621. }