PageRenderTime 59ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/draw/lib/pio/pio.sqlite.php

https://github.com/bajibaji/Version-0.15
PHP | 442 lines | 349 code | 52 blank | 41 comment | 67 complexity | 824dd8e0e0a4a2de4d3ea5085a5bd283 MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. /**
  3. * PIO SQLite API
  4. *
  5. * 提供存取以 SQLite 資料庫構成的資料結構後端的物件
  6. *
  7. * @package PMCLibrary
  8. * @version $Id: pio.sqlite.php 880 2013-02-21 12:25:55Z scribe $
  9. * @date $Date: 2013-02-21 20:25:55 +0800 (週四, 21 二月 2013) $
  10. */
  11. class PIOsqlite implements IPIO {
  12. var $ENV, $dbname, $tablename; // Local Constant
  13. var $con, $prepared, $useTransaction; // Local Global
  14. function PIOsqlite($connstr='', $ENV){
  15. $this->ENV = $ENV;
  16. $this->prepared = 0;
  17. if($connstr) $this->dbConnect($connstr);
  18. }
  19. /* private 攔截SQL錯誤 */
  20. function _error_handler(array $errarray, $query=''){
  21. $err = sprintf('%s on line %d.', $errarray[0], $errarray[1]);
  22. $errno = sqlite_last_error($this->con);
  23. if (defined('DEBUG') && DEBUG) {
  24. $err .= sprintf(PHP_EOL."Description: #%d: %s".PHP_EOL.
  25. "SQL: %s", $errno, sqlite_error_string($errno), $query);
  26. }
  27. throw new RuntimeException($err, $errno);
  28. }
  29. /* private 使用SQL字串和SQLite要求 */
  30. function _sqlite_call($query, $errarray=false){
  31. $resource = sqlite_query($this->con, $query);
  32. if(is_array($errarray) && $resource===false) $this->_error_handler($errarray, $query);
  33. else return $resource;
  34. }
  35. /* private SQLite的sqlite_result頂替函數 */
  36. function _sqlite_result($rh, $row, $field){
  37. $currrow = sqlite_fetch_all($rh, SQLITE_NUM);
  38. return $currrow[$row][$field];
  39. }
  40. /* PIO模組版本 */
  41. function pioVersion(){
  42. return '0.6 (v20130221)';
  43. }
  44. /* 處理連線字串/連接 */
  45. function dbConnect($connStr){
  46. // 格式: sqlite://SQLite檔案之位置/資料表/
  47. // 示例: sqlite://pixmicat.db/imglog/
  48. if(preg_match('/^sqlite:\/\/(.*)\/(.*)\/$/i', $connStr, $linkinfos)){
  49. $this->dbname = $linkinfos[1]; // SQLite檔案之位置
  50. $this->tablename = $linkinfos[2]; // 資料表名稱
  51. }
  52. }
  53. /* 初始化 */
  54. function dbInit($isAddInitData=true){
  55. $this->dbPrepare();
  56. if(sqlite_num_rows(sqlite_query($this->con, "SELECT name FROM sqlite_master WHERE name LIKE '".$this->tablename."'"))===0){ // 資料表不存在
  57. $result = 'CREATE TABLE '.$this->tablename.' (
  58. "no" INTEGER NOT NULL PRIMARY KEY,
  59. "resto" INTEGER NOT NULL,
  60. "root" TIMESTAMP DEFAULT \'0\' NOT NULL,
  61. "time" INTEGER NOT NULL,
  62. "md5chksum" VARCHAR(32) NOT NULL,
  63. "category" VARCHAR(255) NOT NULL,
  64. "tim" INTEGER NOT NULL,
  65. "ext" VARCHAR(4) NOT NULL,
  66. "imgw" INTEGER NOT NULL,
  67. "imgh" INTEGER NOT NULL,
  68. "imgsize" VARCHAR(10) NOT NULL,
  69. "tw" INTEGER NOT NULL,
  70. "th" INTEGER NOT NULL,
  71. "pwd" VARCHAR(8) NOT NULL,
  72. "now" VARCHAR(255) NOT NULL,
  73. "name" VARCHAR(255) NOT NULL,
  74. "email" VARCHAR(255) NOT NULL,
  75. "sub" VARCHAR(255) NOT NULL,
  76. "com" TEXT NOT NULL,
  77. "host" VARCHAR(255) NOT NULL,
  78. "status" VARCHAR(255) NOT NULL
  79. );'; // PIO Structure V3
  80. $idx = array('resto', 'root', 'time');
  81. foreach($idx as $x){
  82. $result .= 'CREATE INDEX IDX_'.$this->tablename.'_'.$x.' ON '.$this->tablename.'('.$x.');';
  83. }
  84. $result .= 'CREATE INDEX IDX_'.$this->tablename.'_resto_no ON '.$this->tablename.'(resto,no);';
  85. if($isAddInitData)
  86. $result .= 'INSERT INTO '.$this->tablename.' (resto,root,time,md5chksum,category,tim,ext,imgw,imgh,imgsize,tw,th,pwd,now,name,email,sub,com,host,status) VALUES (0, datetime("now"), 1111111111, "", "", 1111111111111, "", 0, 0, "", 0, 0, "", "05/01/01(六)00:00", "'.$this->ENV['NONAME'].'", "", "'.$this->ENV['NOTITLE'].'", "'.$this->ENV['NOCOMMENT'].'", "", "");';
  87. sqlite_exec($this->con, $result); // 正式新增資料表
  88. $this->dbCommit();
  89. }
  90. }
  91. /* 準備/讀入 */
  92. function dbPrepare($reload=false, $transaction=false){
  93. if($this->prepared) return true;
  94. if(@!$this->con=sqlite_popen($this->dbname, 0666)) $this->_error_handler(array('Open database failed', __LINE__));
  95. $this->useTransaction = $transaction;
  96. if($transaction) @sqlite_exec($this->con, 'BEGIN;'); // 啟動交易性能模式
  97. $this->prepared = 1;
  98. }
  99. /* 提交/儲存 */
  100. function dbCommit(){
  101. if(!$this->prepared) return false;
  102. if($this->useTransaction) @sqlite_exec($this->con, 'COMMIT;'); // 交易性能模式提交
  103. }
  104. /* 資料表維護 */
  105. function dbMaintanence($action, $doit=false){
  106. switch($action) {
  107. case 'optimize':
  108. if($doit){
  109. $this->dbPrepare(false);
  110. if($this->_sqlite_call('VACUUM '.$this->tablename)) return true;
  111. else return false;
  112. }else return true; // 支援最佳化資料表
  113. break;
  114. case 'export':
  115. if($doit){
  116. $this->dbPrepare(false);
  117. $gp = gzopen('piodata.log.gz', 'w9');
  118. gzwrite($gp, $this->dbExport());
  119. gzclose($gp);
  120. return '<a href="piodata.log.gz">下載 piodata.log.gz 中介檔案</a>';
  121. }else return true; // 支援匯出資料
  122. break;
  123. case 'check':
  124. case 'repair':
  125. default: return false; // 不支援
  126. }
  127. }
  128. /* 匯入資料來源 */
  129. function dbImport($data){
  130. $this->dbInit(false); // 僅新增結構不新增資料
  131. $data = explode("\r\n", $data);
  132. $data_count = count($data) - 1;
  133. $replaceComma = create_function('$txt', 'return str_replace("&#44;", ",", $txt);');
  134. for($i = 0; $i < $data_count; $i++){
  135. $line = array_map($replaceComma, explode(',', $data[$i])); // 取代 &#44; 為 ,
  136. $SQL = 'INSERT INTO '.$this->tablename.' (no,resto,root,time,md5chksum,category,tim,ext,imgw,imgh,imgsize,tw,th,pwd,now,name,email,sub,com,host,status) VALUES ('.
  137. $line[0].','.
  138. $line[1].',\''.
  139. $line[2].'\','.
  140. substr($line[5], 0, 10).',\''.
  141. sqlite_escape_string($line[3]).'\',\''.
  142. sqlite_escape_string($line[4]).'\','.
  143. $line[5].',\''.sqlite_escape_string($line[6]).'\','.
  144. $line[7].','.$line[8].',\''.sqlite_escape_string($line[9]).'\','.$line[10].','.$line[11].',\''.
  145. sqlite_escape_string($line[12]).'\',\''.
  146. sqlite_escape_string($line[13]).'\',\''.
  147. sqlite_escape_string($line[14]).'\',\''.
  148. sqlite_escape_string($line[15]).'\',\''.
  149. sqlite_escape_string($line[16]).'\',\''.
  150. sqlite_escape_string($line[17]).'\',\''.
  151. sqlite_escape_string($line[18]).'\',\''.
  152. sqlite_escape_string($line[19]).'\')';
  153. $this->_sqlite_call($SQL, array('Insert a new post failed', __LINE__));
  154. }
  155. $this->dbCommit(); // 送交
  156. return true;
  157. }
  158. /* 匯出資料來源 */
  159. function dbExport(){
  160. if(!$this->prepared) $this->dbPrepare();
  161. $line = $this->_sqlite_call('SELECT no,resto,root,md5chksum,category,tim,ext,imgw,imgh,imgsize,tw,th,pwd,now,name,email,sub,com,host,status FROM '.$this->tablename.' ORDER BY no DESC',
  162. array('Export posts failed', __LINE__));
  163. $data = '';
  164. $replaceComma = create_function('$txt', 'return str_replace(",", "&#44;", $txt);');
  165. while($row = sqlite_fetch_array($line, SQLITE_ASSOC)){
  166. $row = array_map($replaceComma, $row); // 取代 , 為 &#44;
  167. $data .= implode(',', $row).",\r\n";
  168. }
  169. return $data;
  170. }
  171. /* 文章數目 */
  172. function postCount($resno=0){
  173. if(!$this->prepared) $this->dbPrepare();
  174. if($resno){ // 回傳討論串總文章數目
  175. $line = $this->_sqlite_call('SELECT COUNT(no) FROM '.$this->tablename.' WHERE resto = '.intval($resno),
  176. array('Fetch count in thread failed', __LINE__));
  177. $countline = $this->_sqlite_result($line, 0, 0) + 1;
  178. }else{ // 回傳總文章數目
  179. $line = $this->_sqlite_call('SELECT COUNT(no) FROM '.$this->tablename, array('Fetch count of posts failed', __LINE__));
  180. $countline = $this->_sqlite_result($line, 0, 0);
  181. }
  182. return $countline;
  183. }
  184. /* 討論串數目 */
  185. function threadCount(){
  186. if(!$this->prepared) $this->dbPrepare();
  187. $tree = $this->_sqlite_call('SELECT COUNT(no) FROM '.$this->tablename.' WHERE resto = 0',
  188. array('Fetch count of threads failed', __LINE__));
  189. $counttree = $this->_sqlite_result($tree, 0, 0); // 計算討論串目前資料筆數
  190. return $counttree;
  191. }
  192. /* 取得最後文章編號 */
  193. function getLastPostNo($state){
  194. if(!$this->prepared) $this->dbPrepare();
  195. if($state=='afterCommit'){ // 送出後的最後文章編號
  196. $tree = $this->_sqlite_call('SELECT MAX(no) FROM '.$this->tablename, array('Get the last No. failed', __LINE__));
  197. $lastno = $this->_sqlite_result($tree, 0, 0);
  198. return $lastno;
  199. }else return 0; // 其他狀態沒用
  200. }
  201. /* 輸出文章清單 */
  202. function fetchPostList($resno=0, $start=0, $amount=0){
  203. if(!$this->prepared) $this->dbPrepare();
  204. $line = array();
  205. $resno = intval($resno);
  206. if($resno){ // 輸出討論串的結構 (含自己, EX : 1,2,3,4,5,6)
  207. $tmpSQL = 'SELECT no FROM '.$this->tablename.' WHERE no = '.$resno.' OR resto = '.$resno.' ORDER BY no';
  208. }else{ // 輸出所有文章編號,新的在前
  209. $tmpSQL = 'SELECT no FROM '.$this->tablename.' ORDER BY no DESC';
  210. $start = intval($start); $amount = intval($amount);
  211. if($amount) $tmpSQL .= " LIMIT {$start}, {$amount}"; // 有指定數量才用 LIMIT
  212. }
  213. $tree = $this->_sqlite_call($tmpSQL, array('Fetch post list failed', __LINE__));
  214. while($rows = sqlite_fetch_array($tree)) $line[] = $rows[0]; // 迴圈
  215. return $line;
  216. }
  217. /* 輸出討論串清單 */
  218. function fetchThreadList($start=0, $amount=0, $isDESC=false) {
  219. if(!$this->prepared) $this->dbPrepare();
  220. $start = intval($start); $amount = intval($amount);
  221. $treeline = array();
  222. $tmpSQL = 'SELECT no FROM '.$this->tablename.' WHERE resto = 0 ORDER BY '.($isDESC ? 'no' : 'root').' DESC';
  223. if($amount) $tmpSQL .= " LIMIT {$start}, {$amount}"; // 有指定數量才用 LIMIT
  224. $tree = $this->_sqlite_call($tmpSQL, array('Fetch thread list failed', __LINE__));
  225. while($rows = sqlite_fetch_array($tree)) $treeline[] = $rows[0]; // 迴圈
  226. return $treeline;
  227. }
  228. /* 輸出文章 */
  229. function fetchPosts($postlist,$fields='*'){
  230. if(!$this->prepared) $this->dbPrepare();
  231. if(is_array($postlist)){ // 取多串
  232. $pno = implode(',', $postlist); // ID字串
  233. $tmpSQL = 'SELECT '.$fields.' FROM '.$this->tablename.' WHERE no IN ('.$pno.') ORDER BY no';
  234. if(count($postlist) > 1){ if($postlist[0] > $postlist[1]) $tmpSQL .= ' DESC'; } // 由大排到小
  235. }else $tmpSQL = 'SELECT '.$fields.' FROM '.$this->tablename.' WHERE no = '.intval($postlist); // 取單串
  236. $line = $this->_sqlite_call($tmpSQL, array('Fetch the post content failed', __LINE__));
  237. return sqlite_fetch_all($line, SQLITE_ASSOC);
  238. }
  239. /* 刪除舊附件 (輸出附件清單) */
  240. function delOldAttachments($total_size, $storage_max, $warnOnly=true){
  241. $FileIO = PMCLibrary::getFileIOInstance();
  242. if(!$this->prepared) $this->dbPrepare();
  243. $arr_warn = $arr_kill = array(); // 警告 / 即將被刪除標記陣列
  244. $result = $this->_sqlite_call('SELECT no,ext,tim FROM '.$this->tablename.' WHERE ext <> \'\' ORDER BY no',
  245. array('Get the old post failed', __LINE__));
  246. while(list($dno, $dext, $dtim) = sqlite_fetch_array($result)){ // 個別跑舊文迴圈
  247. $dfile = $dtim.$dext; // 附加檔案名稱
  248. $dthumb = $FileIO->resolveThumbName($dtim); // 預覽檔案名稱
  249. if($FileIO->imageExists($dfile)){ $total_size -= $FileIO->getImageFilesize($dfile) / 1024; $arr_kill[] = $dno; $arr_warn[$dno] = 1; } // 標記刪除
  250. if($dthumb && $FileIO->imageExists($dthumb)) $total_size -= $FileIO->getImageFilesize($dthumb) / 1024;
  251. if($total_size < $storage_max) break;
  252. }
  253. return $warnOnly ? $arr_warn : $this->removeAttachments($arr_kill);
  254. }
  255. /* 刪除文章 */
  256. function removePosts($posts){
  257. if(!$this->prepared) $this->dbPrepare();
  258. if(count($posts)==0) return array();
  259. $files = $this->removeAttachments($posts, true); // 先遞迴取得刪除文章及其回應附件清單
  260. $pno = implode(', ', $posts); // ID字串
  261. $this->_sqlite_call('DELETE FROM '.$this->tablename.' WHERE no IN ('.$pno.') OR resto IN('.$pno.')',
  262. array('Delete old posts and replies failed', __LINE__)); // 刪掉文章
  263. return $files;
  264. }
  265. /* 刪除附件 (輸出附件清單) */
  266. function removeAttachments($posts, $recursion=false){
  267. $FileIO = PMCLibrary::getFileIOInstance();
  268. if(!$this->prepared) $this->dbPrepare();
  269. if(count($posts)==0) return array();
  270. $files = array();
  271. $pno = implode(', ', $posts); // ID字串
  272. if($recursion) $tmpSQL = 'SELECT ext,tim FROM '.$this->tablename.' WHERE (no IN ('.$pno.') OR resto IN('.$pno.")) AND ext <> ''"; // 遞迴取出 (含回應附件)
  273. else $tmpSQL = 'SELECT ext,tim FROM '.$this->tablename.' WHERE no IN ('.$pno.") AND ext <> ''"; // 只有指定的編號
  274. $result = $this->_sqlite_call($tmpSQL, array('Get attachments of the post failed', __LINE__));
  275. while(list($dext, $dtim) = sqlite_fetch_array($result)){ // 個別跑迴圈
  276. $dfile = $dtim.$dext; // 附加檔案名稱
  277. $dthumb = $FileIO->resolveThumbName($dtim); // 預覽檔案名稱
  278. if($FileIO->imageExists($dfile)) $files[] = $dfile;
  279. if($dthumb && $FileIO->imageExists($dthumb)) $files[] = $dthumb;
  280. }
  281. return $files;
  282. }
  283. /* 新增文章/討論串 */
  284. function addPost($no, $resto, $md5chksum, $category, $tim, $ext, $imgw, $imgh, $imgsize, $tw, $th, $pwd, $now, $name, $email, $sub, $com, $host, $age=false, $status=''){
  285. if(!$this->prepared) $this->dbPrepare();
  286. $time = (int)substr($tim, 0, -3); // 13位數的數字串是檔名,10位數的才是時間數值
  287. $updatetime = gmdate('Y-m-d H:i:s'); // 更動時間 (UTC)
  288. $resto = intval($resto);
  289. if($resto){ // 新增回應
  290. $root = '0';
  291. if($age){ // 推文
  292. $this->_sqlite_call('UPDATE '.$this->tablename.' SET root = "'.$updatetime.'" WHERE no = '.$resto,
  293. array('Push the post failed', __LINE__)); // 將被回應的文章往上移動
  294. }
  295. }else $root = $updatetime; // 新增討論串, 討論串最後被更新時間
  296. $query = 'INSERT INTO '.$this->tablename.' (resto,root,time,md5chksum,category,tim,ext,imgw,imgh,imgsize,tw,th,pwd,now,name,email,sub,com,host,status) VALUES ('.
  297. $resto.','. // 回應編號
  298. "'$root',". // 最後更新時間
  299. $time.','. // 發文時間數值
  300. "'$md5chksum',". // 附加檔案md5
  301. "'".sqlite_escape_string($category)."',". // 分類標籤
  302. "$tim, '$ext',". // 附加檔名
  303. (int)$imgw.','.(int)$imgh.",'".$imgsize."',".(int)$tw.','.(int)$th.','. // 圖檔長寬及檔案大小;預覽圖長寬
  304. "'".sqlite_escape_string($pwd)."',".
  305. "'$now',". // 時間(含ID)字串
  306. "'".sqlite_escape_string($name)."',".
  307. "'".sqlite_escape_string($email)."',".
  308. "'".sqlite_escape_string($sub)."',".
  309. "'".sqlite_escape_string($com)."',".
  310. "'".sqlite_escape_string($host)."', '".sqlite_escape_string($status)."')";
  311. $this->_sqlite_call($query, array('Insert a new post failed', __LINE__));
  312. }
  313. /* 檢查是否連續投稿 */
  314. function isSuccessivePost($lcount, $com, $timestamp, $pass, $passcookie, $host, $isupload){
  315. $FileIO = PMCLibrary::getFileIOInstance();
  316. if(!$this->prepared) $this->dbPrepare();
  317. if(!$this->ENV['PERIOD.POST']) return false; // 關閉連續投稿檢查
  318. $timestamp = intval($timestamp);
  319. $tmpSQL = 'SELECT pwd,host FROM '.$this->tablename.' WHERE time > '.($timestamp - (int)$this->ENV['PERIOD.POST']); // 一般投稿時間檢查
  320. if($isupload) $tmpSQL .= ' OR time > '.($timestamp - (int)$this->ENV['PERIOD.IMAGEPOST']); // 附加圖檔的投稿時間檢查 (與下者兩者擇一)
  321. else $tmpSQL .= " OR php('md5', com) = '".md5($com)."'"; // 內文一樣的檢查 (與上者兩者擇一) * 此取巧採用了PHP登錄的函式php來叫用md5
  322. $result = $this->_sqlite_call($tmpSQL, array('Get the post to check the succession failed', __LINE__));
  323. while(list($lpwd, $lhost) = sqlite_fetch_array($result)){
  324. // 判斷為同一人發文且符合連續投稿條件
  325. if($host==$lhost || $pass==$lpwd || $passcookie==$lpwd) return true;
  326. }
  327. return false;
  328. }
  329. /* 檢查是否重複貼圖 */
  330. function isDuplicateAttachment($lcount, $md5hash){
  331. $FileIO = PMCLibrary::getFileIOInstance();
  332. if(!$this->prepared) $this->dbPrepare();
  333. $result = $this->_sqlite_call('SELECT tim,ext FROM '.$this->tablename." WHERE ext <> '' AND md5chksum = '$md5hash' ORDER BY no DESC",
  334. array('Get the post to check the duplicate attachment failed', __LINE__));
  335. while(list($ltim, $lext) = sqlite_fetch_array($result)){
  336. if($FileIO->imageExists($ltim.$lext)) return true; // 有相同檔案
  337. }
  338. return false;
  339. }
  340. /* 有此討論串? */
  341. function isThread($no){
  342. if(!$this->prepared) $this->dbPrepare();
  343. $result = $this->_sqlite_call('SELECT no FROM '.$this->tablename.' WHERE no = '.intval($no).' AND resto = 0');
  344. return sqlite_fetch_array($result) ? true : false;
  345. }
  346. /* 搜尋文章 */
  347. function searchPost($keyword, $field, $method){
  348. if(!$this->prepared) $this->dbPrepare();
  349. $keyword_cnt = count($keyword);
  350. $SearchQuery = 'SELECT * FROM '.$this->tablename." WHERE {$field} LIKE '%".sqlite_escape_string($keyword[0])."%'";
  351. if($keyword_cnt > 1){
  352. for($i = 1; $i < $keyword_cnt; $i++){
  353. $SearchQuery .= " {$method} {$field} LIKE '%".sqlite_escape_string($keyword[$i])."%'"; // 多重字串交集 / 聯集搜尋
  354. }
  355. }
  356. $SearchQuery .= ' ORDER BY no DESC'; // 按照號碼大小排序
  357. $line = $this->_sqlite_call($SearchQuery, array('Search the post failed', __LINE__));
  358. return sqlite_fetch_all($line, SQLITE_ASSOC);
  359. }
  360. /* 搜尋類別標籤 */
  361. function searchCategory($category){
  362. if(!$this->prepared) $this->dbPrepare();
  363. $foundPosts = array();
  364. $SearchQuery = 'SELECT no FROM '.$this->tablename." WHERE lower(category) LIKE '%,".strtolower(sqlite_escape_string($category)).",%' ORDER BY no DESC";
  365. $line = $this->_sqlite_call($SearchQuery, array('Search the category failed', __LINE__));
  366. while($rows = sqlite_fetch_array($line)) $foundPosts[] = $rows[0];
  367. return $foundPosts;
  368. }
  369. /* 取得文章屬性 */
  370. function getPostStatus($status){
  371. return new FlagHelper($status); // 回傳 FlagHelper 物件
  372. }
  373. /* 更新文章 */
  374. function updatePost($no, $newValues){
  375. if(!$this->prepared) $this->dbPrepare();
  376. $no = intval($no);
  377. $chk = array('resto', 'md5chksum', 'category', 'tim', 'ext', 'imgw', 'imgh', 'imgsize', 'tw', 'th', 'pwd', 'now', 'name', 'email', 'sub', 'com', 'host', 'status');
  378. foreach($chk as $c){
  379. if(isset($newValues[$c])){
  380. $this->_sqlite_call('UPDATE '.$this->tablename." SET $c = '".sqlite_escape_string($newValues[$c])."' WHERE no = $no",
  381. array('Update the field of the post failed', __LINE__)); // 更新討論串屬性
  382. }
  383. }
  384. }
  385. /* 設定文章屬性 */
  386. function setPostStatus($no, $newStatus){
  387. $this->updatePost($no, array('status' => $newStatus));
  388. }
  389. }
  390. ?>