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

543 lines
19KB

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