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

554 lines
20KB

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