]> 4ch.mooo.com Git - test.git/blob - yotsubanome.php
modified: config.php
[test.git] / yotsubanome.php
1 <?php
2 /********************************
3     四葉の芽画像掲示板
4
5 yotsubanome.php*/$ver = "v0.7.8.1.0001 β lot.100404";/*
6
7 これがコアシステムです。 四葉の芽スクリプト
8 このスクリプトはレッツPHP!<http://php.s3.to/>のgazou.phpを改造したものです。
9 配布条件はレッツPHP!に準じます。改造、再配布は自由にどうぞ。
10 このスクリプトに関する質問はレッツPHP!にしないようにお願いします。
11 最新版は<http://4ch.irc.su/+4/script/>で配布しています。
12 ご質問は準備板@四葉の芽<http://4ch.irc.su/+4/test/>までどうぞ。
13
14 --【スパーキー(④ ^ヮ^)】◆FCr.DTJy2k◆◆/ODv/gdbGrBJVTTiLB/IBFugUUM=◆四葉の芽◇ちゃんねる ## 管理者 ##
15 ********************************
16 */
17 define("PIXMICAT_VER", 'yotsubanome '.$ver); // 版本資訊文字
18 /*
19 Pixmicat! : 圖咪貓貼圖版程式
20 http://pixmicat.openfoundry.org/
21 版權所有 © 2005-2009 Pixmicat! Development Team
22
23 版權聲明:
24 此程式是基於レッツPHP!<http://php.s3.to/>的gazou.php、
25 双葉ちゃん<http://www.2chan.net>的futaba.php所改寫之衍生著作程式,屬於自由軟體,
26 以The Clarified Artistic License作為發佈授權條款。
27 您可以遵照The Clarified Artistic License來自由使用、散播、修改或製成衍生著作。
28 更詳細的條款及定義請參考隨附"LICENSE"條款副本。
29
30 發佈這一程式的目的是希望它有用,但沒有任何擔保,甚至沒有適合特定目的而隱含的擔保。
31 關於此程式相關的問題請不要詢問レッツPHP!及双葉ちゃん。
32
33 如果您沒有隨著程式收到一份The Clarified Artistic License副本,
34 請瀏覽http://pixmicat.openfoundry.org/license/以取得一份。
35
36 最低運行需求:
37 PHP 4.3.0 / 27 December 2002
38 GD Version 2.0.28 / 21 July 2004
39
40 建議運行環境:
41 PHP 4.4.9 或更高版本並開啟 GD 和 Zlib 支援,如支援 ImageMagick 建議使用
42 安裝 PHP 編譯快取套件 (如eAccelerator, XCache, APC) 或其他快取套件 (如memcached) 更佳
43 如伺服器支援 SQLite, MySQL, PostgreSQL 等請盡量使用
44
45 設置方法:
46 根目錄的權限請設為777,
47 首先將pixmicat.php執行過一遍,必要的檔案和資料夾權限皆會自動設定,
48 自動設定完成後請刪除或註解起來此檔案底部之init(); // ←■■!程式環境初始化(略)一行,
49 然後再執行一遍pixmicat.php,即完成初始化程序,可以開始使用。
50
51 細部的設定請打開config.php參考註解修改,另有 Wiki (http://pixmicat.wikidot.com/pmcuse:config)
52 說明條目可資參考。
53 */
54
55 error_reporting(E_ALL); // show all errors for debugging
56
57 /* Enviorment Settings */
58 // Do not change unless you renamed the directories
59 define("PHP_DIRECTORY", '../test/'); // yotsubanome "C:\windows\system\"
60 define("DATA_DIR", PHP_DIRECTORY.'data/'); // data directory
61 define("CSS_DIR", DATA_DIR.'css/'); // CSS directory
62 define("ICON_DIR", DATA_DIR.'icon/'); // icon directory [Graphics of the software go here]
63 define("TEMP_DIR", PHP_DIRECTORY.'temp/'); // upload content temperary directory
64 define("TPLT_DIR", DATA_DIR.'tplt/'); // template directory
65 define("JS_DIR", DATA_DIR.'js/'); // javascript directory
66 define("SALTFILE", DATA_DIR.'salt.php'); // saltfile for secure t. codes
67
68 include_once(PHP_DIRECTORY.'config.php'); // 引入設定檔
69 include_once(PHP_DIRECTORY.'lib/lib_language.php'); // 引入語系
70 include_once(PHP_DIRECTORY.'lib/lib_common.php'); // 引入共通函式檔案
71 include_once(PHP_DIRECTORY.'lib/lib_fileio.php'); // 引入FileIO
72 include_once(PHP_DIRECTORY.'lib/lib_pio.php'); // 引入PIO
73 include_once(PHP_DIRECTORY.'lib/lib_pms.php'); // 引入PMS
74 include_once(PHP_DIRECTORY.'lib/lib_pte.php'); // 引入PTE外部函式庫
75
76 $PTE = new PTELibrary(TEMPLATE_FILE); // PTE Library
77
78 /* Lockdown [prevents posting] */
79 if(file_exists(PHP_DIRECTORY.'lockdown')){
80         if($_POST['mode'] == 'usrdel' || $_GET['mode'] == 'latest' || $_GET['res']){
81                 echo "";
82         }else{
83                 die('Posting temporarily disabled. Come back later!<br/>&mdash;四葉の芽チーム');
84         }
85 }
86
87 /* 更新記錄檔檔案/輸出討論串 */
88 /* ログの全体更新 */
89 function updatelog($resno=0,$page_num=-1,$single_page=false){
90         global $PIO, $FileIO, $PTE, $PMS, $language, $LIMIT_SENSOR, $style_bar;
91
92         $adminMode = adminAuthenticate('check') && $page_num != -1 && !$single_page; // 前端管理模式
93         $adminFunc = ''; // 前端管理選擇
94         if($adminMode){
95                 $adminFunc = '<select name="func"><option value="delete">'._T('admin_delete').'</option>';
96                 $funclist = array();
97                 $PMS->useModuleMethods('AdminFunction', array('add', &$funclist, null, null)); // "AdminFunction" Hook Point
98                 foreach($funclist as $f) $adminFunc .= '<option value="'.$f[0].'">'.$f[1].'</option>'."\n";
99                 $adminFunc .= '</select>';
100         }
101         $resno = intval($resno); // 編號數字化
102         $page_start = $page_end = 0; // 靜態頁面編號
103         $inner_for_count = 1; // 內部迴圈執行次數
104         $RES_start = $RES_amount = $hiddenReply = $tree_count = $hiddenImage = $hiddenImagP = 0;
105         $hiddenImagRP = 1; // o++
106         $kill_sensor = $old_sensor = false; // 預測系統啟動旗標
107         $arr_kill = $arr_old = array(); // 過舊編號陣列
108         $pte_vals = array('{$THREADFRONT}'=>'','{$THREADREAR}'=>'','{$SELF}'=>PHP_SELF,
109                 '{$DEL_HEAD_TEXT}' => '<input type="hidden" name="mode" value="usrdel" />'._T('del_head'),
110                 '{$DEL_IMG_ONLY_FIELD}' => '<input type="checkbox" name="onlyimgdel" id="onlyimgdel" value="on" />',
111                 '{$DEL_IMG_ONLY_TEXT}' => _T('del_img_only'),
112                 '{$DEL_PASS_TEXT}' => ($adminMode ? $adminFunc : '')._T('del_pass'),
113                 '{$DEL_PASS_FIELD}' => '<input class="inputtext" type="password" name="pwd" size="8" value="" />',
114                 '{$DEL_SUBMIT_BTN}' => '<input type="submit" value="'._T('del_btn').'" />');
115         if(is_file(DATA_DIR.CSV_SS)) $pte_vals += array('{$STYLE_BAR}' => '<br />Style '.$style_bar);
116
117         if($resno) $pte_vals['{$RESTO}'] = $resno;
118
119         if(!$resno){
120                 if($page_num==-1){ // remake模式 (PHP動態輸出多頁份)
121                         $threads = $PIO->fetchThreadList(); // 取得全討論串列表
122                         $PMS->useModuleMethods('ThreadOrder', array($resno,$page_num,$single_page,&$threads)); // "ThreadOrder" Hook Point
123                         $threads_count = count($threads);
124                         $inner_for_count = $threads_count > PAGE_DEF ? PAGE_DEF : $threads_count;
125                         $page_end = ceil($threads_count / PAGE_DEF) - 1; // 頁面編號最後值
126                 }else{ // 討論串分頁模式 (PHP動態輸出一頁份)
127                         $threads_count = $PIO->threadCount(); // 討論串個數
128                         if($page_num < 0 || ($page_num * PAGE_DEF) >= $threads_count) error(_T('page_not_found')); // $page_num超過範圍
129                         $page_start = $page_end = $page_num; // 設定靜態頁面編號
130                         $threads = $PIO->fetchThreadList($page_num * PAGE_DEF, PAGE_DEF); // 取出分頁後的討論串首篇列表
131                         $PMS->useModuleMethods('ThreadOrder', array($resno,$page_num,$single_page,&$threads)); // "ThreadOrder" Hook Point
132                         $inner_for_count = count($threads); // 討論串個數就是迴圈次數
133                 }
134         }else{
135                 if(!$PIO->isThread($resno)){ error(_T('thread_not_found')); }
136                 $AllRes = isset($_GET['page_num']) && $_GET['page_num']=='all'; // 是否使用 ALL 全部輸出
137
138                 // 計算回應分頁範圍
139                 $tree_count = $PIO->postCount($resno) - 1; // 討論串回應個數
140                 if($tree_count && RE_PAGE_DEF){ // 有回應且RE_PAGE_DEF > 0才做分頁動作
141                         if($page_num==='all'){ // show all
142                                 $page_num = 0;
143                                 $RES_start = 1;
144                                 $RES_amount = $tree_count;
145                         }else{
146                                 if($page_num==='RE_PAGE_MAX') $page_num = ceil($tree_count / RE_PAGE_DEF) - 1; // 特殊值:最末頁
147                                 if($page_num < 0) $page_num = 0; // 負數
148                                 if($page_num * RE_PAGE_DEF >= $tree_count) error(_T('page_not_found'));
149                                 $RES_start = $page_num * RE_PAGE_DEF + 1; // 開始
150                                 $RES_amount = RE_PAGE_DEF; // 取幾個
151                         }
152                 }elseif($page_num > 0) error(_T('page_not_found')); // 沒有回應的情況只允許page_num = 0 或負數
153                 else{ $RES_start = 1; $RES_amount = $tree_count; $page_num = 0; } // 輸出全部回應
154
155                 if(USE_RE_CACHE && !$adminMode){ // 檢查快取是否仍可使用 / 頁面有無更動
156                         $cacheETag = md5(($AllRes ? 'all' : $page_num).'-'.$tree_count); // 最新狀態快取用 ETag
157                         $cacheFile = './cache/'.$resno.'-'.($AllRes ? 'all' : $page_num).'.'; // 暫存快取檔位置
158                         $cacheGzipPrefix = extension_loaded('zlib') ? 'compress.zlib://' : ''; // 支援 Zlib Compression Stream 就使用
159                         $cacheControl = isset($_SERVER['HTTP_CACHE_CONTROL']) ? $_SERVER['HTTP_CACHE_CONTROL'] : ''; // 瀏覽器快取控制
160                         if(isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == '"'.$cacheETag.'"'){ // 再度瀏覽而快取無更動
161                                 header('HTTP/1.1 304 Not Modified');
162                                 header('ETag: "'.$cacheETag.'"');
163                                 return;
164                         }elseif(file_exists($cacheFile.$cacheETag) && $cacheControl != 'no-cache'){ // 有(更新的)暫存快取檔存在 (未強制no-cache)
165                                 header('X-Cache: HIT from Pixmicat');
166                                 header('ETag: "'.$cacheETag.'"');
167                                 header('Connection: close');
168                                 readfile($cacheGzipPrefix.$cacheFile.$cacheETag); return;
169                         }else{
170                                 header('X-Cache: MISS from Pixmicat');
171                         }
172                 }
173         }
174
175         // 預測過舊文章和將被刪除檔案
176         if(PIOSensor::check('predict', $LIMIT_SENSOR)){ // 是否需要預測
177                 $old_sensor = true; // 標記打開
178                 $arr_old = array_flip(PIOSensor::listee('predict', $LIMIT_SENSOR)); // 過舊文章陣列
179         }
180         $tmp_total_size = total_size(); // 目前附加圖檔使用量
181         $tmp_STORAGE_MAX = STORAGE_MAX * (($tmp_total_size >= STORAGE_MAX) ? 1 : 0.96); // 預估上限值
182         if(STORAGE_LIMIT && STORAGE_MAX > 0 && ($tmp_total_size >= $tmp_STORAGE_MAX)){
183                 $kill_sensor = true; // 標記打開
184                 $arr_kill = $PIO->delOldAttachments($tmp_total_size, $tmp_STORAGE_MAX); // 過舊附檔陣列
185         }
186
187         $PMS->useModuleMethods('ThreadFront', array(&$pte_vals['{$THREADFRONT}'], $resno)); // "ThreadFront" Hook Point
188         $PMS->useModuleMethods('ThreadRear', array(&$pte_vals['{$THREADREAR}'], $resno)); // "ThreadRear" Hook Point
189
190         // 生成靜態頁面一頁份內容
191         for($page = $page_start; $page <= $page_end; $page++){
192                 $dat = ''; $pte_vals['{$THREADS}'] = '';
193                 head($dat, $resno);
194                 form($dat, $resno);
195                 // 輸出討論串內容
196                 for($i = 0; $i < $inner_for_count; $i++){
197                         // 取出討論串編號
198                         if($resno) $tID = $resno; // 單討論串輸出 (回應模式)
199                         else{
200                                 if($page_num == -1 && ($page * PAGE_DEF + $i) >= $threads_count) break; // remake 超出索引代表已全部完成
201                                 $tID = ($page_start==$page_end) ? $threads[$i] : $threads[$page * PAGE_DEF + $i]; // 一頁內容 (一般模式) / 多頁內容 (remake模式)
202                                 $tree_count = $PIO->postCount($tID) - 1; // 討論串回應個數
203                                 $RES_start = $tree_count - RE_DEF + 1; if($RES_start < 1) $RES_start = 1; // 開始
204                                 $RES_amount = RE_DEF; // 取幾個
205                                 $hiddenReply = $RES_start - 1; // 被隱藏回應數
206                         }
207
208                         // $RES_start, $RES_amount 拿去算新討論串結構 (分頁後, 部分回應隱藏)
209                         $tree = $PIO->fetchPostList($tID); // 整個討論串樹狀結構
210                         $tree_cut = array_slice($tree, $RES_start, $RES_amount); array_unshift($tree_cut, $tID); // 取出特定範圍回應
211                         $posts = $PIO->fetchPosts($tree_cut); // 取得文章架構內容
212                         $posts_img = $PIO->fetchPosts($tree); // o++
213                         $pte_vals['{$THREADS}'] .= arrangeThread($PTE, $tree, $tree_cut, $posts, $hiddenReply, $resno, $arr_kill, $arr_old, $kill_sensor, $old_sensor, true, $adminMode, $hiddenImage, $hiddenImagP, $hiddenImagRP, $posts_img); // 交給這個函式去搞討論串印出
214                 }
215                 $pte_vals['{$PAGENAV}'] = '<div id="page_switch">';
216
217                 // 換頁判斷
218                 $prev = ($resno ? $page_num : $page) - 1;
219                 $next = ($resno ? $page_num : $page) + 1;
220                 if($resno){ // 回應分頁
221                         if(RE_PAGE_DEF > 0){ // 回應分頁開啟
222                                 $pte_vals['{$PAGENAV}'] .= '<table class="pages" border="1"><tr><td style="white-space: nowrap;">';
223                                 $pte_vals['{$PAGENAV}'] .= ($prev >= 0) ? '<a href="'.PHP_SELF.'?res='.$resno.'&amp;page_num='.$prev.'">'._T('prev_page').'</a>' : _T('first_page');
224                                 $pte_vals['{$PAGENAV}'] .= "</td><td>";
225                                 if($tree_count==0) $pte_vals['{$PAGENAV}'] .= '[<b>0</b>] '; // 無回應
226                                 else{
227                                         for($i = 0, $len = $tree_count / RE_PAGE_DEF; $i < $len; $i++){
228                                                 if(!$AllRes && $page_num==$i) $pte_vals['{$PAGENAV}'] .= '[<b>'.$i.'</b>] ';
229                                                 else $pte_vals['{$PAGENAV}'] .= '[<a href="'.PHP_SELF.'?res='.$resno.'&amp;page_num='.$i.'">'.$i.'</a>] ';
230                                         }
231                                         $pte_vals['{$PAGENAV}'] .= $AllRes ? '[<b>'._T('all_pages').'</b>] ' : ($tree_count > RE_PAGE_DEF ? '[<a href="'.PHP_SELF.'?res='.$resno.'&amp;page_num=all">'._T('all_pages').'</a>] ' : '');
232                                 }
233                                 $pte_vals['{$PAGENAV}'] .= '</td><td style="white-space: nowrap;">';
234                                 $pte_vals['{$PAGENAV}'] .= (!$AllRes && $tree_count > $next * RE_PAGE_DEF) ? '<a href="'.PHP_SELF.'?res='.$resno.'&amp;page_num='.$next.'">'._T('next_page').'</a>' : _T('last_page');
235                                 $pte_vals['{$PAGENAV}'] .= '</td></tr></table>'."\n";
236                         }
237                 }else{ // 一般分頁
238                         $pte_vals['{$PAGENAV}'] .= '<table class="pages" border="1"><tr>';
239                         if($prev >= 0){
240                                 if(!$adminMode && $prev==0) $pte_vals['{$PAGENAV}'] .= '<td><form action="'.PHP_SELF2.'" method="get">';
241                                 else{
242                                         if($adminMode || (STATIC_HTML_UNTIL != -1) && ($prev > STATIC_HTML_UNTIL)) $pte_vals['{$PAGENAV}'] .= '<td><form action="'.PHP_SELF.'?page_num='.$prev.'" method="post">';
243                                         else $pte_vals['{$PAGENAV}'] .= '<td><form action="'.$prev.PHP_EXT.'" method="get">';
244                                 }
245                                 $pte_vals['{$PAGENAV}'] .= '<div><input type="submit" value="'._T('prev_page').'" /></div></form></td>';
246                         }else $pte_vals['{$PAGENAV}'] .= '<td style="white-space: nowrap;">'._T('first_page').'</td>';
247                         $pte_vals['{$PAGENAV}'] .= '<td>';
248                         for($i = 0, $len = $threads_count / PAGE_DEF; $i < $len; $i++){
249                                 if($page==$i) $pte_vals['{$PAGENAV}'] .= "[<b>".$i."</b>] ";
250                                 else{
251                                         $pageNext = ($i==$next) ? ' rel="next"' : '';
252                                         if(!$adminMode && $i==0) $pte_vals['{$PAGENAV}'] .= '[<a href="'.PHP_SELF2.'?">0</a>] ';
253                                         elseif($adminMode || (STATIC_HTML_UNTIL != -1 && $i > STATIC_HTML_UNTIL)) $pte_vals['{$PAGENAV}'] .= '[<a href="'.PHP_SELF.'?page_num='.$i.'"'.$pageNext.'>'.$i.'</a>] ';
254                                         else $pte_vals['{$PAGENAV}'] .= '[<a href="'.$i.PHP_EXT.'?"'.$pageNext.'>'.$i.'</a>] ';
255                                 }
256                         }
257                         $pte_vals['{$PAGENAV}'] .= '</td>';
258                         if($threads_count > $next * PAGE_DEF){
259                                 if($adminMode || (STATIC_HTML_UNTIL != -1) && ($next > STATIC_HTML_UNTIL)) $pte_vals['{$PAGENAV}'] .= '<td><form action="'.PHP_SELF.'?page_num='.$next.'" method="post">';
260                                 else $pte_vals['{$PAGENAV}'] .= '<td><form action="'.$next.PHP_EXT.'" method="get">';
261                                 $pte_vals['{$PAGENAV}'] .= '<div><input type="submit" value="'._T('next_page').'" /></div></form></td>';
262                         }else $pte_vals['{$PAGENAV}'] .= '<td style="white-space: nowrap;">'._T('last_page').'</td>';
263                         $pte_vals['{$PAGENAV}'] .= '</tr></table>'."\n";
264                 }
265                 $pte_vals['{$PAGENAV}'] .= '<br style="clear: left;" />
266 </div>';
267                 $dat .= $PTE->ParseBlock('MAIN', $pte_vals);
268                 foot($dat);
269
270                 // 存檔 / 輸出
271                 if($single_page || ($page_num == -1 && !$resno)){ // 靜態快取頁面生成
272                         if($page==0) $logfilename = PHP_SELF2;
273                         else $logfilename = $page.PHP_EXT;
274                         $fp = fopen($logfilename, 'w');
275                         stream_set_write_buffer($fp, 0);
276                         fwrite($fp, $dat);
277                         fclose($fp);
278                         @chmod($logfilename, 0666);
279                         if(STATIC_HTML_UNTIL != -1 && STATIC_HTML_UNTIL==$page) break; // 頁面數目限制
280                 }else{ // PHP 輸出 (回應模式/一般動態輸出)
281                         if(USE_RE_CACHE && !$adminMode && $resno && !isset($_GET['upseries'])){ // 更新快取
282                                 if($oldCaches = glob($cacheFile.'*')){
283                                         foreach($oldCaches as $o) unlink($o); // 刪除舊快取
284                                 }
285                                 $fp = fopen($cacheGzipPrefix.$cacheFile.$cacheETag, 'w');
286                                 fwrite($fp, $dat);
287                                 fclose($fp);
288                                 @chmod($cacheFile.$cacheETag, 0666);
289                                 header('ETag: "'.$cacheETag.'"');
290                                 header('Connection: close');
291                         }
292                         echo $dat;
293                         break;
294                 }
295         }
296 }
297
298 /* 輸出討論串架構 */
299 function arrangeThread($PTE, $tree, $tree_cut, $posts, $hiddenReply, $resno=0, $arr_kill, $arr_old, $kill_sensor, $old_sensor, $showquotelink=true, $adminMode=false, $hiddenImage, $hiddenImagP, $hiddenImagRP, $posts_img){
300         global $PIO, $FileIO, $PMS, $language;
301
302         $thdat = ''; // 討論串輸出碼
303         $posts_count = count($posts); // 迴圈次數
304         if($hiddenReply) $posts_img_count = count($posts_img); // o++
305         if(gettype($tree_cut) == 'array') $tree_cut = array_flip($tree_cut); // array_flip + isset 搜尋法
306         if(gettype($tree) == 'array') $tree_clone = array_flip($tree);
307         if($hiddenReply){ // o++
308                 // $o = 0 (首篇), $o = 1~n (回應) //++++----\r             for($o = 0; $o < $posts_img_count; $o++){ // o++
309                         extract($posts_img[$o]); // o++
310                         if($ext && $FileIO->imageExists($tim.$ext)) $hiddenImage++; // o++ all images in thread
311                 }
312                 // $oo = 0 (首篇), $oo = 1~n (回應) //++++----
313                 for($oo = 0; $oo < $posts_count; $oo++){ // o++
314                         extract($posts[$oo]); // o++
315                         if($oo) if($ext && $FileIO->imageExists($tim.$ext)) $hiddenImagP++; // o++ reply images in index
316                         elseif(!$ext && !$FileIO->imageExists($tim.$ext)) $hiddenImagRP = 0; // o++ opening thread image in index
317                 }
318
319                 // A little math is done to get the total number of omitted images
320                 $hiddenImgs = ($hiddenImage - $hiddenImagP) - $hiddenImagRP; // o++
321         }
322
323         // Actually beginning the REAL post extraction
324         // $i = 0 (首篇), $i = 1~n (回應)
325         for($i = 0; $i < $posts_count; $i++){
326                 $imgsrc = $img_thumb = $imgwh_bar = $imgfn_bar = '';
327                 $IMG_BAR = $REPLYBTN = $QUOTEBTN = $WARN_OLD = $WARN_BEKILL = $WARN_ENDREPLY = $WARN_HIDEPOST = '';
328                 extract($posts[$i]); // 取出討論串文章內容設定變數
329
330                 if($no == 0) break; // Do not display post 0
331
332                 // 設定欄位值
333                 $name = str_replace('&'.TRIP_KEY, '&amp;'.TRIP_KEY, $name); // 避免 &#xxxx; 後面被視為 Trip 留下 & 造成解析錯誤
334                 if(CLEAR_SAGE) $email = preg_replace('/^sage( *)/i', '', trim($email)); // 清除E-mail中的「sage」關鍵字
335                 //Tripcode indicator // t++ //++++----
336                 $tripkeycount = substr_count($name, TRIP_KEY);
337                 if(ALLOW_NONAME==2){ // 強制砍名
338                         if($tripkeycount==1) $name = preg_match('/(\\'.TRIP_KEY.'.{10})/', $name, $matches) ? '<span class="postertrip">'.$matches[1].'</span>' : '';
339                         if($tripkeycount==2) $name = preg_match('/(\\'.TRIP_KEY.TRIP_KEY.'.{16})/', $name, $matches) ? '<span class="postertrip">'.$matches[1].'</span>' : '';
340                         if($tripkeycount==3) $name = preg_match('/(\\'.TRIP_KEY.'.{32})/', $name, $matches) ? '<span class="postertrip">'.$matches[1].'</span>' : '';
341                         if($email) $now = "<a href=\"mailto:$email\" class=\"linkmail\">$now</a>";
342                 }else{
343                         if($tripkeycount==1) $name = preg_replace('/(\\'.TRIP_KEY.'.{10})/', '<span class="postertrip">$1</span>', $name); // Trip取消粗體
344                         if($tripkeycount==2) $name = preg_replace('/(\\'.TRIP_KEY.TRIP_KEY.'.{16})/', '<span class="postertrip">$1</span>', $name); // Trip取消粗體
345                         if($tripkeycount==3) $name = preg_replace('/(\\'.TRIP_KEY.'.{32})/', '<span class="postertrip">$1</span>', $name); // Trip取消粗體
346                         if($email) $name = "<a href=\"mailto:$email\" class=\"linkmail\">$name</a>";
347                 }
348
349                 if(AUTO_LINK) $com = auto_link($com);
350                 $com = quoteLight($com);
351                 $com = quoteLight2($com);
352                 if(!$resno && MAX_LINES) list($com, $abbreviated) = abbreviate($com, MAX_LINES);
353                 if(isset($abbreviated) && $abbreviated && MAX_LINES) $com .= '<br /><span class="abbrev">'._T('long_comment').'<a href="'.PHP_SELF.'?res='.$tree[0].'#r'.$no.'">'._T('long_here').'</a>'._T('long_see').'</span>';
354
355                 if(USE_QUOTESYSTEM && $i){ // 啟用引用瀏覽系統
356                         if(preg_match_all('/((?:&gt;|>)+)(?:No\.)?(\d+)/i', $com, $matches, PREG_SET_ORDER)){ // 找尋>>No.xxx
357                                 $matches_unique = array();
358                                 foreach($matches as $val){ if(!in_array($val, $matches_unique)) array_push($matches_unique, $val); }
359                                 foreach($matches_unique as $val){
360                                         if(isset($tree_clone[$val[2]])){
361                                                 $r_page = $tree_clone[$val[2]]; // 引用回應在整體討論串中的位置
362                                                 // 在此頁顯示區間內,輸出錨點即可
363                                                 if(isset($tree_cut[$val[2]])) $com = str_replace($val[0], '<span class="reflink"><a class="qlink" href="#r'.$val[2].'" onclick="replyhl('.$val[2].');">'.$val[0].'</a></span>', $com);
364                                                 // 非此頁顯示區間,輸出完整頁面位置
365                                                 else $com = str_replace($val[0], '<span class="reflink"><a class="qlink" href="'.PHP_SELF.'?res='.$tree[0].(RE_PAGE_DEF ? '&amp;page_num='.floor(($r_page - 1) / RE_PAGE_DEF) : '').'#r'.$val[2].'">'.$val[0].'</a></span>', $com);
366                                         }
367                                 }
368                         }
369                 }
370
371                 // 設定附加圖檔顯示
372                 if($ext && !$FileIO->imageExists($tim.$ext)){
373                         $imgsrc = '<img src="'.ICON_DIR.'filedeleted.gif" class="img" alt="'.$imgsize.'" title="'.$imgsize.'" />';
374                 }elseif($ext && $FileIO->imageExists($tim.$ext)){
375                         $imageURL = $FileIO->getImageURL($tim.$ext); // image URL
376                         $thumbURL = $FileIO->getImageURL($tim.'s.jpg'); // thumb URL
377
378                         //----$imgsrc = '<a href="'.$imageURL.'" rel="_blank"><img src="'.ICON_DIR.'nothumb.gif" class="img" alt="'.$imgsize.'" title="'.$imgsize.'" /></a>'; // 預設顯示圖樣式 (無預覽圖時)
379                         $imgsrc = '<a href="'.$imageURL.'" rel="_blank"><span class="tn_reply" title="'.$imgsize.'">'._T('nothumb').'</span></a>'; // 預設顯示圖樣式 (無預覽圖時)
380                         if($tw && $th){
381                                 if($FileIO->imageExists($tim.'s.jpg')){ // 有預覽圖
382                                         $img_thumb = '<br /><small><span class="thumbnailmsg">'._T('img_sample').'</span></small>';
383                                         $imgsrc = '<a href="'.$imageURL.'" rel="_blank"><img src="'.$thumbURL.'" style="width: '.$tw.'px; height: '.$th.'px;" class="img" alt="'.$imgsize.'" title="'.$imgsize.'" /></a>';
384                                 }elseif($ext=='.swf') $imgsrc = ''; // swf檔案不需預覽圖
385                         }
386                         if(SHOW_IMGWH) $imgwh_bar = ', '.$imgw.'x'.$imgh; // 顯示附加圖檔之原檔長寬尺寸
387                         if(SHOW_FILENAME){
388                                 $longname = $shortname = '';
389                                 if($filename){
390                                         $longname = $filename.$ext;
391                                         if(strlen($filename) > 40) $shortname = substr($filename, 0, 40).'(....)'.$ext;
392                                         else $shortname = $longname;
393                                 }
394                         }
395                         if($longname) $imgfn_bar = ', <span title="'.$longname.'">'.$shortname.'</span>';
396                         $IMG_BAR = '<span class="filesize">'._T('img_filename').'<a href="'.$imageURL.'" rel="_blank">'.$tim.$ext.'</a>-('.$imgsize.$imgwh_bar.$imgfn_bar.')</span>'.$img_thumb;
397                 }
398
399                 // 設定回應 / 引用連結
400                 if($resno){ // 回應模式
401                         if($showquotelink) $QUOTEBTN = '<span class="reflink"><a href="'.PHP_SELF.'?res='.$tree[0].'#r'.$no.'" onclick="return replyhl('.$no.');">No.</a><a href="javascript:quote('.$no.');" class="qlink">'.$no.'</a></span>';
402                         else $QUOTEBTN = '<span class="reflink"><a href="'.PHP_SELF.'?res='.$tree[0].'#r'.$no.'" onclick="return replyhl('.$no.');">No.</a><a href="'.PHP_SELF.'?res='.$tree.'&amp;page_num=all#r'.$no.'" class="qlink">'.$no.'</a></span>';
403                 }else{
404                         if(!$i) $REPLYBTN = '[<a href="'.PHP_SELF.'?res='.$no.'">'._T('reply_btn').'</a>]'; // 首篇
405                         $QUOTEBTN = '<span class="reflink"><a href="'.PHP_SELF.'?res='.$tree[0].'#r'.$no.'">No.</a><a href="'.PHP_SELF.'?res='.$tree[0].'#q'.$no.'" class="qlink">'.$no.'</a></span>';
406                 }
407                 if($adminMode){ // 前端管理模式
408                         $modFunc = '';
409                         $PMS->useModuleMethods('AdminList', array(&$modFunc, $posts[$i], $resto)); // "AdminList" Hook Point
410                         $QUOTEBTN .= $modFunc;
411                 }
412
413                 // 設定討論串屬性
414                 if(STORAGE_LIMIT && $kill_sensor) if(isset($arr_kill[$no])) $WARN_BEKILL = '<span class="warn_txt">'._T('warn_sizelimit').'</span><br />'."\n"; // 預測刪除過大檔
415                 if(!$i){ // 首篇 Only
416                         if($old_sensor) if(isset($arr_old[$no])) $WARN_OLD = '<span class="oldpost">'._T('warn_oldthread').'</span><br />'."\n"; // 快要被刪除的提示
417                         $flgh = $PIO->getPostStatus($status);
418                         if($flgh->exists('TS')) $WARN_ENDREPLY = '<span class="warn_txt">'._T('warn_locked').'</span><br />'."\n"; // 被標記為禁止回應
419                         if($hiddenReply) $WARN_HIDEPOST = '<span class="omittedposts">'._res($hiddenReply, $hiddenImgs)._T('notice_omitted_reply').'</span><br />'."\n"; // 有隱藏的回應
420                 }
421                 // 對類別標籤作自動連結
422                 if(USE_CATEGORY){
423                         $ary_category = explode(',', str_replace('&#44;', ',', $category)); $ary_category = array_map('trim', $ary_category);
424                         $ary_category_count = count($ary_category);
425                         $ary_category2 = array();
426                         for($p = 0; $p < $ary_category_count; $p++){
427                                 if($c = $ary_category[$p]) $ary_category2[] = '<a href="'.PHP_SELF.'?mode=category&amp;c='.urlencode($c).'">'.$c.'</a>';
428                         }
429                         $category = implode(', ', $ary_category2);
430                 }else $category = '';
431
432                 // 最終輸出處
433                 if($i){ // 回應
434                         $arrLabels = array('{$NO}'=>$no, '{$SUB}'=>$sub, '{$NAME}'=>$name, '{$NOW}'=>$now, '{$COM}'=>$com, '{$CATEGORY}'=>$category, '{$QUOTEBTN}'=>$QUOTEBTN, '{$IMG_BAR}'=>$IMG_BAR, '{$IMG_SRC}'=>$imgsrc, '{$WARN_BEKILL}'=>$WARN_BEKILL, '{$QUOTEBTN}'=>$QUOTEBTN, '{$NAME_TEXT}'=>_T('post_name'), '{$CATEGORY_TEXT}'=>_T('post_category'), '{$SELF}'=>PHP_SELF);
435                         if($resno) $arrLabels['{$RESTO}']=$resno;
436                         $PMS->useModuleMethods('ThreadReply', array(&$arrLabels, $posts[$i], $resno)); // "ThreadReply" Hook Point
437                         $thdat .= $PTE->ParseBlock('REPLY',$arrLabels);
438                 }else{ // 首篇
439                         $arrLabels = array('{$NO}'=>$no, '{$SUB}'=>$sub, '{$NAME}'=>$name, '{$NOW}'=>$now, '{$COM}'=>$com, '{$CATEGORY}'=>$category, '{$QUOTEBTN}'=>$QUOTEBTN, '{$REPLYBTN}'=>$REPLYBTN, '{$IMG_BAR}'=>$IMG_BAR, '{$IMG_SRC}'=>$imgsrc, '{$WARN_OLD}'=>$WARN_OLD, '{$WARN_BEKILL}'=>$WARN_BEKILL, '{$WARN_ENDREPLY}'=>$WARN_ENDREPLY, '{$WARN_HIDEPOST}'=>$WARN_HIDEPOST, '{$NAME_TEXT}'=>_T('post_name'), '{$CATEGORY_TEXT}'=>_T('post_category'), '{$SELF}'=>PHP_SELF);
440                         if($resno) $arrLabels['{$RESTO}']=$resno;
441                         $PMS->useModuleMethods('ThreadPost', array(&$arrLabels, $posts[$i], $resno)); // "ThreadPost" Hook Point
442                         $thdat .= $PTE->ParseBlock('THREAD',$arrLabels);
443                 }
444         }
445         $thdat .= $PTE->ParseBlock('THREADSEPARATE',($resno)?array('{$RESTO}'=>$resno):array());
446         return $thdat;
447 }
448
449 /* 寫入記錄檔 */
450 /* 記事書き込み */
451 function regist(){
452         global $PIO, $FileIO, $PMS, $language, $BAD_STRING, $BAD_FILEMD5, $BAD_IPADDR, $LIMIT_SENSOR;
453         $dest = ''; $mes = ''; $up_incomplete = 0; $is_admin = false;
454         $path = realpath('.').DIRECTORY_SEPARATOR; // 此目錄的絕對位置
455
456         if($_SERVER['REQUEST_METHOD'] != 'POST') error(_T('regist_notpost')); // 非正規POST方式
457         // 欄位陷阱
458         $FTname = isset($_POST['name']) ? $_POST['name'] : '';
459         $FTemail = isset($_POST['email']) ? $_POST['email'] : '';
460         $FTsub = isset($_POST['sub']) ? $_POST['sub'] : '';
461         $FTcom = isset($_POST['com']) ? $_POST['com'] : '';
462         $FTreply = isset($_POST['reply']) ? $_POST['reply'] : '';
463         if($FTname != 'spammer' || $FTemail != 'foo@foo.bar' || $FTsub != 'DO NOT FIX THIS' || $FTcom != 'EID OG SMAPS' || $FTreply != '') error(_T('regist_nospam'));
464
465         $name = isset($_POST[FT_NAME]) ? CleanStr($_POST[FT_NAME]) : '';
466         $email = isset($_POST[FT_EMAIL]) ? CleanStr($_POST[FT_EMAIL]) : '';
467         $sub = isset($_POST[FT_SUBJECT]) ? CleanStr($_POST[FT_SUBJECT]) : '';
468         $com = isset($_POST[FT_COMMENT]) ? $_POST[FT_COMMENT] : '';
469         $pwd = isset($_POST['pwd']) ? $_POST['pwd'] : '';
470         $category = isset($_POST['category']) ? CleanStr($_POST['category']) : '';
471         $resto = isset($_POST['resto']) ? intval($_POST['resto']) : 0;
472         $upfile = isset($_FILES['upfile']['tmp_name']) ? $_FILES['upfile']['tmp_name'] : '';
473         $upfile_path = isset($_POST['upfile_path']) ? $_POST['upfile_path'] : '';
474         $upfile_name = isset($_FILES['upfile']['name']) ? $_FILES['upfile']['name'] : false;
475         $ext_ = ereg_replace("^.*\\.", ".", $upfile_name); // filename extention
476         $basename = basename($upfile_name, $ext_); // filename
477         $filename = isset($basename) ? CleanStr($basename) : ''; // cleaned filename
478         $upfile_status = isset($_FILES['upfile']['error']) ? $_FILES['upfile']['error'] : 4;
479         $pwdc = isset($_COOKIE['pwdc']) ? $_COOKIE['pwdc'] : '';
480         $ip = getREMOTE_ADDR(); $host = gethostbyaddr($ip);
481
482         $PMS->useModuleMethods('RegistBegin', array(&$name, &$email, &$sub, &$com, array('file'=>&$upfile, 'path'=>&$upfile_path, 'name'=>&$upfile_name, 'status'=>&$upfile_status), array('ip'=>$ip, 'host'=>$host), $resto)); // "RegistBegin" Hook Point
483         // 封鎖:IP/Hostname/DNSBL 檢查機能
484         $baninfo = '';
485         if(BanIPHostDNSBLCheck($ip, $host, $baninfo)) error(_T('regist_ipfiltered', $baninfo));
486         // 封鎖:限制出現之文字
487         foreach($BAD_STRING as $value){
488                 if(strpos($com, $value)!==false || strpos($sub, $value)!==false || strpos($name, $value)!==false || strpos($email, $value)!==false){
489                         error(_T('regist_wordfiltered'));
490                 }
491         }
492
493         // 檢查是否輸入櫻花日文假名
494         foreach(array($name, $email, $sub, $com) as $anti) if(anti_sakura($anti)) error(_T('regist_sakuradetected'));
495
496         // 時間
497         $time = time();
498         $tim = $time.substr(microtime(),2,3);
499         $tome = time()+0*60*60;
500
501         // 判斷上傳狀態
502         switch($upfile_status){
503                 case 1:
504                         error(_T('regist_upload_exceedphp'));
505                         break;
506                 case 2:
507                         error(_T('regist_upload_exceedcustom'));
508                         break;
509                 case 3:
510                         error(_T('regist_upload_incompelete'));
511                         break;
512                 case 6:
513                         error(_T('regist_upload_direrror'));
514                         break;
515                 case 4: // 無上傳
516                         if(NO_TEXTONLY == 2){
517                                 if(!$resto) error(_T('regist_upload_noimg'));
518                         }elseif(NO_TEXTONLY == 1){
519                                 if(!$resto && !isset($_POST['noimg'])) error(_T('regist_upload_noimg'));
520                         }
521                         break;
522                 case 0: // 上傳正常
523                 default:
524         }
525
526         // 如果有上傳檔案則處理附加圖檔
527         if($upfile && (@is_uploaded_file($upfile) || @is_file($upfile))){
528                 // 一‧先儲存檔案
529                 $dest = $path.TEMP_DIR.$tim.'.temp';
530                 @move_uploaded_file($upfile, $dest) or @copy($upfile, $dest);
531                 @chmod($dest, 0666);
532                 if(!is_file($dest)) error(_T('regist_upload_filenotfound'), $dest);
533
534                 // 二‧判斷上傳附加圖檔途中是否有中斷
535                 $upsizeTTL = $_SERVER['CONTENT_LENGTH'];
536                 if(isset($_FILES['upfile'])){ // 有傳輸資料才需要計算,避免作白工
537                         $upsizeHDR = 0;
538                         // 檔案路徑:IE附完整路徑,故得從隱藏表單取得
539                         $tmp_upfile_path = $upfile_name;
540                         if($upfile_path) $tmp_upfile_path = get_magic_quotes_gpc() ? stripslashes($upfile_path) : $upfile_path;
541                         list(,$boundary) = explode('=', $_SERVER['CONTENT_TYPE']);
542                         foreach($_POST as $header => $value){ // 表單欄位傳送資料
543                                 $upsizeHDR += strlen('--'.$boundary."\r\n");
544                                 $upsizeHDR += strlen('Content-Disposition: form-data; name="'.$header.'"'."\r\n\r\n".(get_magic_quotes_gpc()?stripslashes($value):$value)."\r\n");
545                         }
546                         // 附加圖檔欄位傳送資料
547                         $upsizeHDR += strlen('--'.$boundary."\r\n");
548                         $upsizeHDR += strlen('Content-Disposition: form-data; name="upfile"; filename="'.$tmp_upfile_path."\"\r\n".'Content-Type: '.$_FILES['upfile']['type']."\r\n\r\n");
549                         $upsizeHDR += strlen("\r\n--".$boundary."--\r\n");
550                         $upsizeHDR += $_FILES['upfile']['size']; // 傳送附加圖檔資料量
551                         // 上傳位元組差值超過 HTTP_UPLOAD_DIFF:上傳附加圖檔不完全
552                         if(($upsizeTTL - $upsizeHDR) > HTTP_UPLOAD_DIFF){
553                                 if(KILL_INCOMPLETE_UPLOAD){
554                                         unlink($dest);
555                                         die(_T('regist_upload_killincomp')); // 給瀏覽器的提示,假如使用者還看的到的話才不會納悶
556                                 }else $up_incomplete = 1;
557                         }
558                 }
559
560                 // 三‧檢查是否為可接受的檔案
561                 $size = @getimagesize($dest);
562                 if(!is_array($size)) error(_T('regist_upload_notimage'), $dest); // $size不為陣列就不是圖檔
563                 $imgsize = @filesize($dest); // 檔案大小
564                 if(!KB) $imgsize .= ' B'; // B only
565                 else $imgsize = ($imgsize>=1024) ? (int)($imgsize/1024).' KB' : $imgsize.' B'; // KB和B的判別
566                 switch($size[2]){ // 判斷上傳附加圖檔之格式
567                         case 1 : $ext = ".gif"; break;
568                         case 2 : $ext = ".jpg"; break;
569                         case 3 : $ext = ".png"; break;
570                         case 4 : $ext = ".swf"; break;
571                         case 5 : $ext = ".psd"; break;
572                         case 6 : $ext = ".bmp"; break;
573                         case 7 : $ext = ".tiff"; break;
574                         case 8 : $ext = ".tiff"; break;
575                         case 9 : $ext = ".jpc"; break;
576                         case 10 : $ext = ".jp2"; break;
577                         case 11 : $ext = ".jpx"; break;
578                         case 12 : $ext = ".jb2"; break;
579                         case 13 : $ext = ".swf"; break;
580                         case 14 : $ext = ".aiff"; break;
581                         case 15 : $ext = ".wbmp"; break;
582                         case 16 : $ext = ".xbm"; break;
583                         default : $ext = ".xxxx"; error(_T('regist_upload_notsupport'), $dest);
584                 }
585                 $allow_exts = explode('|', strtolower(ALLOW_UPLOAD_EXT)); // 接受之附加圖檔副檔名
586                 if(array_search(substr($ext, 1), $allow_exts)===false) error(_T('regist_upload_notsupport'), $dest); // 並無在接受副檔名之列
587                 // 封鎖設定:限制上傳附加圖檔之MD5檢查碼
588                 $md5chksum = md5_file($dest); // 檔案MD5
589                 if(array_search($md5chksum, $BAD_FILEMD5)!==FALSE) error(_T('regist_upload_blocked'), $dest); // 在封鎖設定內則阻擋
590
591                 // 四‧計算附加圖檔圖檔縮圖顯示尺寸
592                 $W = $imgW = $size[0];
593                 $H = $imgH = $size[1];
594                 $MAXW = $resto ? MAX_RW : MAX_W;
595                 $MAXH = $resto ? MAX_RH : MAX_H;
596                 if($W > $MAXW || $H > $MAXH){
597                         $W2 = $MAXW / $W;
598                         $H2 = $MAXH / $H;
599                         $key = ($W2 < $H2) ? $W2 : $H2;
600                         $W = ceil($W * $key);
601                         $H = ceil($H * $key);
602                 }
603                 $mes = _T('regist_uploaded', CleanStr($upfile_name));
604         }
605
606         // 檢查表單欄位內容並修整
607         if(strlen($name) > 100) error(_T('regist_nametoolong'), $dest);
608         if(strlen($email) > 100) error(_T('regist_emailtoolong'), $dest);
609         if(strlen($sub) > 100) error(_T('regist_topictoolong'), $dest);
610         if(strlen($resto) > 10) error(_T('regist_longthreadnum'), $dest);
611
612         // E-mail / 標題修整
613         $email = str_replace("\r\n", '', $email); $sub = str_replace("\r\n", '', $sub);
614         // Tripcode area--------------------------------------------------------------------------------
615         if($name){
616                 // 名稱修整
617                 $name = str_replace(TRIP_KEY, TRIP_KEY_FAKE, $name); // 防止トリップ偽造
618                 $name = str_replace(CAP_SUFFIX, CAP_SUFFIX_FAKE, $name); // 防止管理員キャップ偽造
619                 $name = str_replace("\r\n", '', $name);
620                 $nameOri = $name; // 名稱
621                 // トリップ
622                 //----if(preg_match('/(.*?)[##](.*)/u', $name, $regs)){ // トリップ(Trip)機能
623                         //----$name = $nameOri = $regs[1]; $cap = strtr($regs[2], array('&amp;'=>'&'));
624                         //----$salt = preg_replace('/[^\.-z]/', '.', substr($cap.'H.', 1, 2));
625                         //----$salt = strtr($salt, ':;<=>?@[\\]^_`', 'ABCDEFGabcdef');
626                         //----$name = $name.TRIP_KEY.substr(crypt($cap, $salt), -10);
627                 if(preg_match('/(.*?)[##](.*)/u', $name, $regs)){ // トリップ(Trip)機能
628                         $name = str_replace("&#", "&%%%%%%", $name); # otherwise HTML numeric entities screw up explode()!
629                         list($name, $trip, $sectrip) = str_replace("&&", "&%%%%%%", explode("#", $name));
630
631                         if($trip != ''){
632                                 if(function_exists("iconv")) $trip = iconv("UTF-8", "SHIFT_JIS//TRANSLIT", $trip); // convert to Windows Japanese #&#65355;&#65345;&#65357;&#65353;
633                                 $salt = strtr(preg_replace('/[^\.-z]/', '.', substr($trip.'H.', 1, 2)), ':;<=>?@[\\]^_`', 'ABCDEFGabcdef');
634                                 $metrip = TRIP_KEY.substr(crypt($trip, $salt), -10);
635                         }else $metrip = '';
636                         if($sectrip != ''){
637                                 if(function_exists("iconv")) $sectrip = iconv("UTF-8", "SHIFT_JIS//TRANSLIT", $sectrip); // convert to Windows Japanese #&#65355;&#65345;&#65357;&#65353;
638                                 $salt = "LOLLOLOLOLOLOLOLOLOLOLOLOLOLOLOLMEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"; # this is ONLY used if the host doesn't have openssl # I don't know a better way to get random data
639                                 if(file_exists(SALTFILE)){ # already generated a key
640                                         $salt = file_get_contents(SALTFILE);
641                                 }else{
642                                         system("openssl rand 448 > '".SALTFILE, $err);
643                                         if($err === 0){
644                                                 if(chmod(SALTFILE,0400)){
645                                                         $salt = file_get_contents(SALTFILE);
646                                                 }else{
647                                                         $donk = IDSEED;
648                                                         $fp = fopen(SALTFILE, "w");
649                                                         fputs($fp, $donk);
650                                                         fclose($fp);
651                                                 }
652                                         }
653                                 }
654                                 $sha = base64_encode(pack("H*", sha1($sectrip.$salt)));
655                                 $sha = substr($sha, 0, 16);
656                                 $metrip .= TRIP_KEY.TRIP_KEY.$sha;
657                         }
658                         // Tripcode filter
659                         //++++if(file_exists(FILTER_DIR)){
660                                 //++++include(FILTER_DIR.'trip.php');
661                         //++++}
662                         //----"</b></font><font class=\"postertrip\">".
663                         $name .= $metrip;
664                 }
665                 if(CAP_ENABLE && preg_match('/(.*?)[##](.*)/u', $email, $aregs)){ // 管理員キャップ(Cap)機能
666                         $acap_name = $nameOri; $acap_pwd = strtr($aregs[2], array('&amp;'=>'&'));
667                         if($acap_name==CAP_NAME && $acap_pwd==CAP_PASS){
668                                 $name = '<span class="admin_cap">'.$name.CAP_SUFFIX.'</span>';
669                                 $is_admin = true;
670                                 $email = $aregs[1]; // 去除 #xx 密碼
671                         }
672                 }
673                 if(!$is_admin){ // 非管理員
674                         $name = str_replace(_T('admin'), '"'._T('admin').'"', $name);
675                         $name = str_replace(_T('deletor'), '"'._T('deletor').'"', $name);
676                 }
677                 $name = str_replace('&'.TRIP_KEY, '&amp;'.TRIP_KEY, $name); // 避免 &#xxxx; 後面被視為 Trip 留下 & 造成解析錯誤
678         }
679         // End of Tripcode area--------------------------------------------------------------------------
680         // 內文修整
681         if((strlen($com) > COMM_MAX) && !$is_admin) error(_T('regist_commenttoolong'), $dest);
682         $com = CleanStr($com, $is_admin); // 引入$is_admin參數是因為當管理員キャップ啟動時,允許管理員依config設定是否使用HTML
683         if(!$com && $upfile_status==4) error(_T('regist_withoutcomment'));
684         $com = str_replace(array("\r\n", "\r"), "\n", $com); $com = ereg_replace("\n(( | )*\n){4,}", "\n", $com);
685         if(!BR_CHECK || substr_count($com,"\n") < BR_CHECK) $com = nl2br($com); // 換行字元用<br />代替
686         $com = str_replace("\n", '', $com); // 若還有\n換行字元則取消換行
687         // 預設的內容
688         if(!$name || ereg("^[ | |]*$", $name)){
689                 if(ALLOW_NONAME) $name = DEFAULT_NONAME;
690                 else error(_T('regist_withoutname'), $dest);
691         }
692         if(!$sub || ereg("^[ | |]*$", $sub)){
693                 if(ALLOW_NOSUB) $sub = DEFAULT_NOTITLE;
694                 else error(_T('regist_withoutsubject'), $dest);
695         }
696         if(!$com || ereg("^[ | |\t]*$", $com)){
697                 if(ALLOW_NOSUB) $com = DEFAULT_NOCOMMENT;
698                 else error(_T('regist_withoutcomment'), $dest);
699         }
700         // 修整標籤樣式
701         if($category && USE_CATEGORY){
702                 $category = explode(',', $category); // 把標籤拆成陣列
703                 $category = ','.implode(',', array_map('trim', $category)).','; // 去空白再合併為單一字串 (左右含,便可以直接以,XX,形式搜尋)
704         }else{ $category = ''; }
705         if($up_incomplete) $com .= '<br /><br /><span class="warn_txt">'._T('notice_incompletefile').'</span>'; // 上傳附加圖檔不完全的提示
706
707         // 密碼和時間的樣式 
708         if($pwd=='') if(ALLOW_NOPASS) error(_T('regist_withoutpassword'), $dest); else $pwd = ($pwdc=='') ? substr(rand(),0,8) : $pwdc;
709         $pass = $pwd ? substr(md5($pwd), 2, 8) : '*'; // 生成真正儲存判斷用的密碼
710         $youbi = array(_T('sun'),_T('mon'),_T('tue'),_T('wed'),_T('thu'),_T('fri'),_T('sat'));
711 //----  $yd = $youbi[gmdate('w', $time+TIME_ZONE*60*60)];
712         $yd = $youbi[date('w', $tome)];
713 //----  $now = gmdate('y/m/d', $time+TIME_ZONE*60*60).'('.(string)$yd.')'.gmdate('H:i', $time+TIME_ZONE*60*60);
714         if(!EN_SEC)
715                 $now = date(DATE_FORMAT, $tome).'('.(string)$yd.')'.date('H:i', $tome);
716                 else $now = date(DATE_FORMAT, $tome).'('.(string)$yd.')'.date('H:i:s', $tome);
717
718 //----  if(DISP_ID){ // 顯示ID
719 //----          if($email && DISP_ID==1) $now .= ' ID:????';
720 //----          else $now .= ' ID:'.substr(crypt(md5(getREMOTE_ADDR().IDSEED.gmdate('Ymd', $time+TIME_ZONE*60*60)),'id'), -8);
721 //----  }
722         if(DISP_ID){ // 顯示ID
723                 if($email&&DISP_ID==1) $now .= " ID:????";
724                 else $now .= " ID:".substr(crypt(md5(getREMOTE_ADDR().IDSEED.date(DATE_FORMAT, $tome)),'id'), -8);
725         }
726
727         // 連續投稿 / 相同附加圖檔檢查
728         $checkcount = 50; // 預設檢查50筆資料
729         $pwdc = substr(md5($pwdc), 2, 8); // Cookies密碼
730         if($PIO->isSuccessivePost($checkcount, $com, $time, $pass, $pwdc, $host, $upfile_name)) error(_T('regist_successivepost'), $dest); // 連續投稿檢查
731         if($dest){ if($PIO->isDuplicateAttachment($checkcount, $md5chksum)) error(_T('regist_duplicatefile'), $dest); } // 相同附加圖檔檢查
732         if($resto) $ThreadExistsBefore = $PIO->isThread($resto);
733
734         // 舊文章刪除處理
735         if(PIOSensor::check('delete', $LIMIT_SENSOR)){
736                 $delarr = PIOSensor::listee('delete', $LIMIT_SENSOR);
737                 if(count($delarr)){
738                         deleteCache($delarr);
739                         $PMS->useModuleMethods('PostOnDeletion', array($delarr, 'recycle')); // "PostOnDeletion" Hook Point
740                         $files = $PIO->removePosts($delarr);
741                         if(count($files)) $FileIO->deleteImage($files);
742                 }
743         }
744
745         // 附加圖檔容量限制功能啟動:刪除過大檔
746         if(STORAGE_LIMIT && STORAGE_MAX > 0){
747                 $tmp_total_size = total_size(); // 取得目前附加圖檔使用量
748                 if($tmp_total_size > STORAGE_MAX){
749                         $files = $PIO->delOldAttachments($tmp_total_size, STORAGE_MAX, false);
750                         $FileIO->deleteImage($files);
751                 }
752         }
753
754         // 判斷欲回應的文章是不是剛剛被刪掉了
755         if($resto){
756                 if($ThreadExistsBefore){ // 欲回應的討論串是否存在
757                         if(!$PIO->isThread($resto)){ // 被回應的討論串存在但已被刪
758                                 // 提前更新資料來源,此筆新增亦不紀錄
759                                 $PIO->dbCommit();
760                                 updatelog();
761                                 error(_T('regist_threaddeleted'), $dest);
762                         }else{ // 檢查是否討論串被設為禁止回應 (順便取出原討論串的貼文時間)
763                                 $post = $PIO->fetchPosts($resto); // [特殊] 取單篇文章內容,但是回傳的$post同樣靠[$i]切換文章!
764                                 list($chkstatus, $chktime) = array($post[0]['status'], $post[0]['tim']);
765                                 $chktime = substr($chktime, 0, -3); // 拿掉微秒 (後面三個字元)
766                                 $flgh = $PIO->getPostStatus($chkstatus);
767                                 if($flgh->exists('TS')) error(_T('regist_threadlocked'), $dest);
768                         }
769                 }else error(_T('thread_not_found'), $dest); // 不存在
770         }
771
772         // 計算某些欄位值
773         $no = $PIO->getLastPostNo('beforeCommit') + 1;
774         isset($ext) ? 0 : $ext = '';
775         isset($imgW) ? 0 : $imgW = 0;
776         isset($imgH) ? 0 : $imgH = 0;
777         isset($imgsize) ? 0 : $imgsize = '';
778         isset($W) ? 0 : $W = 0;
779         isset($H) ? 0 : $H = 0;
780         isset($md5chksum) ? 0 : $md5chksum = '';
781         $age = false;
782         $status = '';
783         if(USE_UPSERIES && stristr($email, 'noko')){
784                 $email = false;
785                 $noko = true;
786         }else $noko = false;
787         if($resto){
788                 if(!stristr($email, 'sage') && ($PIO->postCount($resto) <= MAX_RES || MAX_RES==0)){
789                         if(!MAX_AGE_TIME || (($time - $chktime) < (MAX_AGE_TIME * 60 * 60))) $age = true; // 討論串並無過期,推文
790                 }
791         }
792         $PMS->useModuleMethods('RegistBeforeCommit', array(&$name, &$email, &$sub, &$com, &$category, &$age, $dest, $resto, array($W, $H, $imgW, $imgH), &$status)); // "RegistBeforeCommit" Hook Point
793
794         // 正式寫入儲存
795         $PIO->addPost($no,$resto,$md5chksum,$category,$tim,$ext,$imgW,$imgH,$imgsize,$filename,$W,$H,$pass,$now,$name,$email,$sub,$com,$host,$age,$status);
796         //----$PIO->addPost($no,$now,$name,$email,$sub,$com,$age,$status,$host,$pwd,$ext,$W,$H,$tim,$md5chksum,$imgsize,$filename,$imgW,$imgH,$category,$resto);
797         $PIO->dbCommit();
798         $lastno = $PIO->getLastPostNo('afterCommit'); // 取得此新文章編號
799         $PMS->useModuleMethods('RegistAfterCommit', array($lastno, $resto, $name, $email, $sub, $com)); // "RegistAfterCommit" Hook Point
800
801         // noko in cookie
802         if($noko) $email = 'noko';
803
804         // Cookies儲存:密碼與E-mail部分,期限是一週
805         setcookie('pwdc', $pwd, time()+7*24*3600, '/');
806         setcookie('emailc', $email, time()+7*24*3600, '/');
807         total_size(true); // 刪除舊容量快取
808         if($dest && is_file($dest)){
809                 $destFile = $path.IMG_DIR.$tim.$ext; // 圖檔儲存位置
810                 $thumbFile = $path.THUMB_DIR.$tim.'s.jpg'; // 預覽圖儲存位置
811                 rename($dest, $destFile);
812                 if(USE_THUMB !== 0){ // 生成預覽圖
813                         $thumbType = USE_THUMB; if(USE_THUMB==1){ $thumbType = 'gd'; } // 與舊設定相容
814                         require(PHP_DIRECTORY.'lib/thumb/thumb.'.$thumbType.'.php');
815                         $thObj = new ThumbWrapper($destFile, $imgW, $imgH);
816                         $thObj->setThumbnailConfig($W, $H, THUMB_Q);
817                         $thObj->makeThumbnailtoFile($thumbFile);
818                         @chmod($thumbFile, 0666);
819                         unset($thObj);
820                 }
821                 if($FileIO->uploadImage()){ // 支援上傳圖片至其他伺服器
822                         if(file_exists($destFile)) $FileIO->uploadImage($tim.$ext, $destFile, filesize($destFile));
823                         if(file_exists($thumbFile)) $FileIO->uploadImage($tim.'s.jpg', $thumbFile, filesize($thumbFile));
824                 }
825         }
826         updatelog();
827
828         // 引導使用者至新頁面
829         $RedirURL = PHP_SELF2.'?'.$tim; // 定義儲存資料後轉址目標
830         if(isset($_POST['up_series']) || $noko){ // 勾選連貼機能
831                 if($resto) $RedirURL = PHP_SELF.'?res='.$resto.'&amp;upseries=1'; // 回應後繼續轉回此主題下
832                 else{
833                         $RedirURL = PHP_SELF.'?res='.$lastno.'&amp;upseries=1'; // 新增主題後繼續轉到此主題下
834                 }
835         }
836         $RedirforJS = strtr($RedirURL, array("&amp;"=>"&")); // JavaScript用轉址目標
837
838         echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
839         echo <<< _REDIR_
840 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
841 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="'.PIXMICAT_LANGUAGE.'">
842 <head>
843 <title></title>
844 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
845 <meta http-equiv="Refresh" content="1;URL=$RedirURL" />
846 <script type="text/javascript">
847 // Redirection (use JS)
848 // <![CDATA[
849 function redir(){
850         location.href = "$RedirforJS";
851 }
852 setTimeout("redir()", 1000);
853 // ]]>
854 </script>
855 </head>
856 <body>
857 <div>
858 _REDIR_;
859 echo _T('regist_redirect',$mes,$RedirURL).'</div>
860 </body>
861 </html>';
862 }
863
864 /* 使用者刪除 */
865 /* ユーザー削除 */
866 function usrdel(){
867         global $PIO, $FileIO, $PMS, $language;
868         // $pwd: 使用者輸入值, $pwdc: Cookie記錄密碼
869         $pwd = isset($_POST['pwd']) ? $_POST['pwd'] : '';
870         $pwdc = isset($_COOKIE['pwdc']) ? $_COOKIE['pwdc'] : '';
871         $onlyimgdel = isset($_POST['onlyimgdel']) ? $_POST['onlyimgdel'] : '';
872         $delno = array();
873         reset($_POST);
874         while($item = each($_POST)){ if($item[1]=='delete' && $item[0] != 'func') array_push($delno, $item[0]); }
875         $haveperm = ($pwd==ADMIN_PASS) || adminAuthenticate('check');
876         if($haveperm && isset($_POST['func'])){ // 前端管理功能
877                 $message = '';
878                 $PMS->useModuleMethods('AdminFunction', array('run', $delno, $_POST['func'], &$message)); // "AdminFunction" Hook Point
879                 if($_POST['func'] != 'delete'){
880                         if(isset($_SERVER['HTTP_REFERER'])){
881                                 header('HTTP/1.1 302 Moved Temporarily');
882                                 header('Location: '.$_SERVER['HTTP_REFERER']);
883                         }
884                         exit(); // 僅執行AdminFunction,終止刪除動作
885                 }
886         }
887         $PMS->useModuleMethods('Authenticate', array($pwd,'userdel',&$haveperm));
888
889         if($pwd=='' && $pwdc!='') $pwd = $pwdc;
890         $pwd_md5 = substr(md5($pwd),2,8);
891         $host = gethostbyaddr(getREMOTE_ADDR());
892         $search_flag = $delflag = false;
893
894         if(!count($delno)) error(_T('del_notchecked'));
895
896         $delposts = array(); // 真正符合刪除條件文章
897         $posts = $PIO->fetchPosts($delno);
898         foreach($posts as $post){
899                 if($pwd_md5==$post['pwd'] || $host==$post['host'] || $haveperm){
900                         $search_flag = true; // 有搜尋到
901                         array_push($delposts, $post['no']);
902                 }
903         }
904         if($search_flag){
905                 if(!$onlyimgdel) $PMS->useModuleMethods('PostOnDeletion', array($delposts, 'frontend')); // "PostOnDeletion" Hook Point
906                 $files = $onlyimgdel ? $PIO->removeAttachments($delposts) : $PIO->removePosts($delposts);
907                 $FileIO->deleteImage($files);
908                 deleteCache($delposts);
909                 total_size(true); // 刪除容量快取
910                 $PIO->dbCommit();
911         }else error(_T('del_wrongpwornotfound'));
912         if(isset($_POST['func']) && $_POST['func'] == 'delete'){ // 前端管理刪除文章返回管理頁面
913                 if(isset($_SERVER['HTTP_REFERER'])){
914                         header('HTTP/1.1 302 Moved Temporarily');
915                         header('Location: '.$_SERVER['HTTP_REFERER']);
916                 }
917                 exit();
918         }
919 }
920
921 /* 管理員密碼認證 */
922 /* パス認証 */
923 function valid(){
924         global $PMS, $language;
925         $pass = isset($_POST['pass']) ? $_POST['pass'] : ''; // 管理者密碼
926         $haveperm = false;
927         $isCheck = adminAuthenticate('check'); // 登入是否正確
928         if(!$isCheck && $pass){
929                 $haveperm = ($pass == ADMIN_PASS);
930                 $PMS->useModuleMethods('Authenticate', array($pass,'admin',&$haveperm));
931                 if($haveperm){ adminAuthenticate('login'); $isCheck = true; }
932                 else error(_T('admin_wrongpassword'));
933         }
934         $dat = '';
935         head($dat);
936         $links = '[<a href="'.PHP_SELF2.'?'.time().'">'._T('return').'</a>] [<a href="'.PHP_SELF.'?mode=remake">'._T('admin_remake').'</a>] [<a href="'.PHP_SELF.'?page_num=0">'._T('admin_frontendmanage').'</a>]';
937         $PMS->useModuleMethods('LinksAboveBar', array(&$links,'admin',$isCheck)); // LinksAboveBar hook point
938         $dat .= '<div id="bannerlink">'.$links.'</div><div id="banner"><div class="passvalid">'._T('admin_top').'</div>
939 </div>
940 <form action="'.PHP_SELF.'" method="post" id="adminform">
941 <div id="admin-check" style="text-align: center;">
942 '; //----class="bar_admin"
943         echo $dat;
944         if(!$isCheck){
945                 echo '<br />
946 <input type="radio" name="admin" value="del" checked="checked" />'._T('admin_manageposts').'
947 <input type="radio" name="admin" value="optimize" />'._T('admin_optimize').'
948 <input type="radio" name="admin" value="check" />'._T('admin_check').'
949 <input type="radio" name="admin" value="repair" />'._T('admin_repair').'
950 <input type="radio" name="admin" value="export" />'._T('admin_export').'
951 <input type="radio" name="admin" value="stylesheets" />'._T('admin_stylesheets').'<p />
952 <input type="hidden" name="mode" value="admin" />
953 <input class="inputtext" type="password" name="pass" size="8" />
954 <input type="submit" value="'._T('admin_verify_btn').'" />
955 </div>
956 </form>';
957                 die("\n</body>\n</html>");
958         }elseif(!isset($_REQUEST['admin'])){
959                 echo '<br />
960 <input type="radio" name="admin" value="del" checked="checked" />'._T('admin_manageposts').'
961 <input type="radio" name="admin" value="optimize" />'._T('admin_optimize').'
962 <input type="radio" name="admin" value="check" />'._T('admin_check').'
963 <input type="radio" name="admin" value="repair" />'._T('admin_repair').'
964 <input type="radio" name="admin" value="export" />'._T('admin_export').'
965 <input type="radio" name="admin" value="stylesheets" />'._T('admin_stylesheets').'
966 <input type="radio" name="admin" value="logout" />'._T('admin_logout').'<p />
967 <input type="hidden" name="mode" value="admin" />
968 <input type="submit" value="'._T('admin_submit_btn').'" />
969 </div>
970 </form>';
971                 die("\n</body>\n</html>");
972         }
973 }
974
975 /* 管理文章模式 */
976 /* 管理者削除 */
977 function admindel(){
978         global $PIO, $FileIO, $PMS, $language;
979
980         $pass = isset($_POST['pass']) ? $_POST['pass'] : ''; // 管理者密碼
981         $page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 0; // 切換頁數
982         $onlyimgdel = isset($_POST['onlyimgdel']) ? $_POST['onlyimgdel'] : ''; // 只刪圖
983         $modFunc = '';
984         $delno = $thsno = array();
985         $delflag = isset($_POST['func']) && ($_POST['func'] == 'delete') && isset($_POST['clist']); // 是否有「刪除」勾選
986         $thsflag = isset($_POST['stop']); // 是否有「停止」勾選
987         $is_modified = false; // 是否改寫檔案
988         $message = ''; // 操作後顯示訊息
989
990         if(isset($_POST['func']) && isset($_POST['clist']))
991                 $PMS->useModuleMethods('AdminFunction', array('run', $_POST['clist'], $_POST['func'], &$message)); // "AdminFunction" Hook Point
992
993         // 刪除文章區塊
994         if($delflag){
995                 //if(!adminAuthenticate('check')) error(_T('admin_wrongpassword'));
996
997                 $delno = array_merge($delno, $_POST['clist']);
998                 if($onlyimgdel != 'on') $PMS->useModuleMethods('PostOnDeletion', array($delno, 'backend')); // "PostOnDeletion" Hook Point
999                 $files = ($onlyimgdel != 'on') ? $PIO->removePosts($delno) : $PIO->removeAttachments($delno);
1000                 $FileIO->deleteImage($files);
1001                 deleteCache($delno);
1002                 total_size(true); // 刪除容量快取
1003                 $is_modified = true;
1004         }
1005         // 討論串停止區塊
1006         if($thsflag){
1007                 //if(!adminAuthenticate('check')) error(_T('admin_wrongpassword'));
1008
1009                 $thsno = array_merge($thsno, $_POST['stop']);
1010                 $threads = $PIO->fetchPosts($thsno); // 取得文章
1011                 foreach($threads as $th){
1012                         $flgh = $PIO->getPostStatus($th['status']);
1013                         $flgh->toggle('TS');
1014                         $PIO->setPostStatus($th['no'], $flgh->toString());
1015                 }
1016                 $is_modified = true;
1017         }
1018         if(($delflag || $thsflag) && $is_modified) $PIO->dbCommit(); // 無論如何都有檔案操作,回寫檔案
1019
1020         $line = $PIO->fetchPostList(0, $page * ADMIN_PAGE_DEF, ADMIN_PAGE_DEF); // 分頁過的文章列表
1021         $posts_count = count($line); // 迴圈次數
1022         $posts = $PIO->fetchPosts($line); // 文章內容陣列
1023
1024         echo '<input type="hidden" name="mode" value="admin" />
1025 <input type="hidden" name="admin" value="del" />
1026 <div style="text-align: left;">'._T('admin_notices').'</div>
1027 <div>'.$message.'</div>
1028 <table border="1" cellspacing="0" style="margin: 0px auto;">
1029 <tr class="managehead">'._T('admin_list_header').'</tr>
1030 ';
1031
1032         for($j = 0; $j < $posts_count; $j++){
1033                 $bg = ($j % 2) ? 'row1' : 'row2'; // 背景顏色
1034                 extract($posts[$j]);
1035
1036                 if($no == 0) break; // Do not display post 0
1037
1038                 // 修改欄位樣式
1039                 $now = preg_replace('/.{2}\/(.{5})\(.+?\)(.{5}).*/', '$1 $2', $now);
1040                 $name = htmlspecialchars(str_cut(html_entity_decode(strip_tags($name)), 8));
1041                 $sub = htmlspecialchars(str_cut(html_entity_decode($sub), 8));
1042                 if($email) $name = "<a href=\"mailto:$email\">$name</a>";
1043                 $com = str_replace('<br />',' ',$com);
1044                 $com = htmlspecialchars(str_cut(html_entity_decode($com), 20));
1045
1046                 // 討論串首篇停止勾選框 及 模組功能
1047                 $modFunc = $THstop = ' ';
1048                 $PMS->useModuleMethods('AdminList', array(&$modFunc, $posts[$j], $resto)); // "AdminList" Hook Point
1049                 if($resto==0){ // $resto = 0 (即討論串首篇)
1050                         $flgh = $PIO->getPostStatus($status);
1051                         $THstop = '<input type="checkbox" name="stop[]" value="'.$no.'" />'.($flgh->exists('TS') ? _T('admin_stop_btn') : '');
1052                 }
1053
1054                 // 從記錄抽出附加圖檔使用量並生成連結
1055                 if($ext && $FileIO->imageExists($tim.$ext)){
1056                         $clip = '<a href="'.$FileIO->getImageURL($tim.$ext).'" rel="_blank">'.$tim.$ext.'</a>';
1057                         $size = $FileIO->getImageFilesize($tim.$ext);
1058                         if($FileIO->imageExists($tim.'s.jpg')) $size += $FileIO->getImageFilesize($tim.'s.jpg');
1059                 }else{
1060                         $clip = $md5chksum = '--';
1061                         $size = 0;
1062                 }
1063
1064                 // 印出介面
1065                 echo <<< _ADMINEOF_
1066 <tr class="$bg" align="left">
1067 <th align="center">$modFunc</th><th align="center">$THstop</th><th><input type="checkbox" name="clist[]" value="$no" />$no</th><td><small>$now</small></td><td>$sub</td><td><b>$name</b></td><td><small>$com</small></td><td>$host</td><td align="center">$clip ($size)<br />$md5chksum</td>
1068 </tr>
1069
1070 _ADMINEOF_;
1071         }
1072         echo '</table>
1073 <p>
1074 <select name="func"><option value="delete">'._T('admin_delete').'</option>';
1075         $funclist = array();
1076         $PMS->useModuleMethods('AdminFunction', array('add', &$funclist, null, null)); // "AdminFunction" Hook Point
1077         foreach($funclist as $f) echo '<option value="'.$f[0].'">'.$f[1].'</option>';
1078         echo '</select>
1079 <input type="submit" value="'._T('admin_submit_btn').'" /> <input type="reset" value="'._T('admin_reset_btn').'" /> [<input type="checkbox" name="onlyimgdel" id="onlyimgdel" value="on" /><label for="onlyimgdel">'._T('del_img_only').'</label>]</p>
1080 <p>'._T('admin_totalsize',total_size()).'</p>
1081 </div>
1082 </form>
1083 <hr />
1084 ';
1085
1086         $countline = $PIO->postCount(); // 總文章數
1087         $page_max = ceil($countline / ADMIN_PAGE_DEF) - 1; // 總頁數
1088         echo '<table class="pages" border="1" style="float: left;"><tr>';
1089         if($page) echo '<td><a href="'.PHP_SELF.'?mode=admin&amp;admin=del&amp;page='.($page - 1).'">'._T('prev_page').'</a></td>';
1090         else echo '<td style="white-space: nowrap;">'._T('first_page').'</td>';
1091         echo '<td>';
1092         for($i = 0; $i <= $page_max; $i++){
1093                 if($i==$page) echo '[<b>'.$i.'</b>] ';
1094                 else echo '[<a href="'.PHP_SELF.'?mode=admin&amp;admin=del&amp;page='.$i.'">'.$i.'</a>] ';
1095         }
1096         echo '</td>';
1097         if($page < $page_max) echo '<td><a href="'.PHP_SELF.'?mode=admin&amp;admin=del&amp;page='.($page + 1).'">'._T('next_page').'</a></td>';
1098         else echo '<td style="white-space: nowrap;">'._T('last_page').'</td>';
1099         die('</tr></table><br/><br/>
1100 </body>
1101 </html>');
1102 }
1103
1104 ////////////////
1105 // manage_css //
1106 ////////////////
1107 function manage_css(){
1108         global $PMS, $language;
1109         $order = array(); $line = '';
1110
1111         // Handle submission
1112         if(isset($_POST['order']) || isset($_POST['new'])){
1113                 $default = $_POST['default'];
1114
1115                 if(isset($_POST['order'])){
1116                         $dupid = false;
1117                         $order = $_POST['order'];
1118                         $ids = array();
1119                         $id = 0;
1120                         $name = '';
1121                         if(count($order) > 1){
1122                                 foreach($order as $name => $id) $ids[$id]++;
1123                                 foreach($ids as $idu => $count){
1124                                         if($idu < 1 || $count == 1) continue;
1125                                         foreach($order as $name => $id) if($id == $idu) $dupid = true;
1126                                 }
1127                                 if($dupid){
1128                                         ksort($order); // Yes, we're going to wimp out and reset it alphabetically.
1129                                         $go = 0;
1130                                         foreach($order as $name => $id) $go++;
1131                                         $order[$name] = $go;
1132                                 }
1133                         }
1134                         $order = array_flip($order);
1135                 }
1136
1137                 // Find out if a new stylesheet entry has been added
1138                 if(is_array($_POST['new'])){
1139                         $new_path = $_POST['new']['path'];
1140                         $new_name = $_POST['new']['name'];
1141                         $new_order = $_POST['new']['order'];
1142                         if($new_path != '' && $new_name != '') $order[$new_order] = $new_name;
1143                         if($default == 'new') $default = $new_name;
1144                 }
1145
1146                 ksort($order);
1147
1148                 // Get existing stylesheet entries
1149                 foreach($order as $id => $name){
1150                         if(!$id) continue;
1151                         if(!$_POST['path'][$name]) continue;
1152                         $temp['path'][$name] = $_POST['path'][$name];
1153                         $temp['names'][$name] = $name;
1154                         $temp['short'][$name] = $_POST['short'][$name];
1155                         $temp['order'][$name] = $id;
1156                 }
1157
1158                 // Get newly added stylesheet entries
1159                 if(is_array($_POST['new'])){
1160                         $temp['path'][$new_name] = $_POST['new']['path'];
1161                         $temp['names'][$new_name] = $new_name;
1162                         $temp['short'][$new_name] = $_POST['new']['short'];
1163                         $temp['order'][$new_name] = $new_order;
1164                 }
1165
1166                 // Build CSV lines
1167                 foreach($order as $id => $name){
1168                         if(!$id) continue; // Ignore Display order 0
1169                         $line   .= $name.','.$temp['short'][$name].','.$temp['path'][$name].',';
1170                         $line   .= ($name == $default) ? 'default,' : ',';
1171                         $line   .= "\n";
1172                 }
1173
1174                 $style_dat = DATA_DIR.CSV_SS;
1175
1176                 // Success messages
1177                 $action = (file_exists($style_dat)) ? _t('admin_updated') : _t('admin_created');
1178                 $delete = (@unlink(CSS_DIR.CSVSS)) ? ' - <span class="warning">'.str_replace('[file]', CSS_DIR.CSVSS, _t('admin_deleted')).'</span>' : false;
1179                 $fp = fopen($style_dat, 'w+');
1180                 set_file_buffer($fp, 0);
1181                 rewind($fp);
1182                 fputs($fp, $line);
1183                 fclose($fp);
1184                 @chmod($style_dat, 0666);
1185                 echo '<div class="bar_managecss">'.str_replace('[file]', $style_dat, _t('admin_updated')).$delete.'</div>';
1186         }
1187
1188         // Editing messages
1189         if(file_exists(DATA_DIR.CSV_SS)){
1190                 $style_data = DATA_DIR.CSV_SS;
1191                 $style_mode = _t('admin_editing');
1192         }else{
1193                 $style_data = CSS_DIR.CSVSS;
1194                 $style_mode = _t('admin_imported');
1195         }
1196         echo '<div class="banner"><table width="100%"><tr><th class="bar_managecss">
1197 '.str_replace('[file]', $style_data, $style_mode).'
1198 </th></tr></table></div>';
1199
1200         echo '<div class="postlists">
1201 <input type="hidden" name="mode" value="admin" />
1202 <input type="hidden" name="admin" value="stylesheets" />
1203 <table width="100%" border="1" cellspacing="0">';
1204
1205         // Read data from R4+(CSV)
1206         if(file_exists(DATA_DIR.CSV_SS)){
1207                 $style_data = DATA_DIR.CSV_SS;
1208                 $lines = explode("\n", file_get_contents($style_data));
1209                 $j = 0;
1210                 $lines = array_diff($lines, array(''));
1211                 if(count($lines)){
1212                         echo '<tr class="managehead"><th colspan="2">'._t('admin_is_default').'</th><th>'._t('admin_fullname').'</th><th>'._t('admin_shortname').'</th><th>'._t('admin_dispid').'</th></tr>';
1213                 }
1214                 foreach($lines as $null => $line){
1215                         if($line != ''){ // Line has data
1216                                 list($style_name, $style_short, $style_file, $style_rel) = explode(',', $line);
1217                                 $j++; // For alternating <tr> BG colour
1218
1219                                 $style_path = CSS_DIR.$style_file;
1220
1221                                 if(file_exists($style_path)){
1222                                         if($style_rel) $style_rel = ' checked="checked"';
1223                                         else $style_rel = false;
1224                                         $class = ($j % 2) ? 'row1' : 'row2'; // BG colour
1225                                         echo '<tr class="'.$class.'"><td align="left" colspan="2"><label><input name="default" type="radio"'.$style_rel.' value="'.$style_name.'" /> '.$style_path.'</label><input type="hidden" name="path['.$style_name.']" value="'.$style_file.'" /></td><td align="left">'.$style_name.'</td><td align="left"><input name="short['.$style_name.']" value="'.$style_short.'" size="5" /></td><td align="left"><label><input name="order['.$style_name.']" size="2" value="'.$j.'" /></label></td></tr>';
1226                                 }
1227                         }
1228                 }
1229         }
1230
1231         // Read data from R3 DAT
1232         else if(file_exists(CSS_DIR.CSVSS)){
1233                 $style_data = CSS_DIR.CSVSS;
1234                 $lines = explode("\n", file_get_contents($style_data));
1235                 $j = 0;
1236                 foreach($lines as $null => $line){ // Line has data, or line is not commented out
1237                         if(substr($line, 0, 2) != '//' && $line != ''){
1238                                 $bits = explode('[*]', $line);
1239                                 $j++;
1240                                 $style_name = $bits[0];
1241                                 $style_path = CSS_DIR.$bits[2];
1242                                 if(file_exists($style_path)){
1243                                         $style_short = $bits[1];
1244                                         if($bits[3]) $style_rel = ' checked="checked"';
1245                                         else $style_rel = false;
1246                                         $class = ($j % 2) ? 'row1' : 'row2'; // BG colour
1247                                         echo '<tr class="'.$class.'"><td align="left" colspan="2"><label><input name="default" type="radio"'.$style_rel.' value="'.$style_name.'" /> '.$style_path.'</label><input type="hidden" name="path['.$style_name.']" value="'.$bits[2].'" /></td><td align="left"><input name="names['.$style_name.']" value="'.$style_name.'" size="25" /></td><td align="left"><input name="short['.$style_name.']" value="'.$style_short.'" size="5" /></td><td align="left"><input name="order['.$style_name.']" size="2" value="'.$j.'" /></td></tr>';
1248                                 }
1249                         }
1250                 }
1251         }
1252
1253         $j++; $class = ($j % 2) ? 'row1' : 'row2';
1254
1255         // Insert string for when there are stylesheet entries to modify
1256         $action = ($j > 1) ? _t('admin_modstyle') : false;
1257         // Check default radio button for new row when there are NO stylesheet entries
1258         $style_rel = (!$action) ? ' checked="checked"' : false;
1259
1260         echo '<tr class="managehead"><th>'.str_replace('[or modify]', $action, _t('admin_addstyle')).'</th><th>'._t('admin_new_file').'</th><th>'._t('admin_fullname').'</th><th>'._t('admin_shortname').'</th><th>'._t('admin_new_id').'</th></tr>';
1261
1262         echo '<tr class="'.$class.'"><td align="left"><label><input name="default" type="radio"'.$style_rel.' value="new" /> '._t('admin_style_default').'</label></td><td align="left"><nobr>'.CSS_DIR.'<input name="new[path]" /></nobr></td><td align="left"><input name="new[name]" size="25" /></td><td align="left"><input name="new[short]" size="5" /></td><td align="left"><input name="new[order]" size="2" value="'.$j.'" /></td></tr></table></div>
1263 <center><p><div class="passvalid"><input type="submit" value="'._T('admin_submit_btn').'" /> <input type="reset" value="'._T('admin_reset_btn').'" /></div></p>';
1264         die('</center></form></body></html>');
1265 }
1266
1267 /* 計算目前附加圖檔使用容量 (單位:KB) */
1268 function total_size($isupdate=false){
1269         global $PIO, $FileIO;
1270
1271         $size = 0; $all = 0;
1272         $cache_file = "./".SIZE_CACHE; // 附加圖檔使用容量值快取檔案
1273
1274         if($isupdate){ // 刪除舊快取
1275                 if(is_file($cache_file)) unlink($cache_file);
1276                 return;
1277         }
1278         if(!is_file($cache_file)){ // 無快取,新增
1279                 $line = $PIO->fetchPostList(); // 取出所有文章編號
1280                 $posts = $PIO->fetchPosts($line);
1281                 $linecount = count($posts);
1282                 for($i = 0; $i < $linecount; $i++){
1283                         extract($posts[$i]);
1284                         // 從記錄檔抽出計算附加圖檔使用量
1285                         if($ext && $FileIO->imageExists($tim.$ext)) $all += $FileIO->getImageFilesize($tim.$ext); // 附加圖檔合計計算
1286                         if($FileIO->imageExists($tim.'s.jpg')) $all += $FileIO->getImageFilesize($tim.'s.jpg'); // 預覽圖合計計算
1287                 }
1288                 $sp = fopen($cache_file, 'w');
1289                 stream_set_write_buffer($sp, 0);
1290                 fwrite($sp, $all); // 寫入目前使用容量值
1291                 fclose($sp);
1292                 @chmod($cache_file, 0666);
1293         }else{ // 使用快取
1294                 $sp = file($cache_file);
1295                 $all = $sp[0];
1296                 unset($sp);
1297         }
1298         return (int)($all / 1024);
1299 }
1300
1301 /* 搜尋(全文檢索)功能 */
1302 function search(){
1303         global $PTE, $PIO, $FileIO, $PMS, $language;
1304
1305         if(!USE_SEARCH) error(_T('search_disabled'));
1306         $searchKeyword = isset($_POST['keyword']) ? trim($_POST['keyword']) : ''; // 欲搜尋的文字
1307         $dat = '';
1308         head($dat);
1309         $links = '[<a href="'.PHP_SELF2.'?'.time().'">'._T('return').'</a>]';
1310         $PMS->useModuleMethods('LinksAboveBar', array(&$links,'search'));
1311         $dat .= '<div id="bannerlink">'.$links.'</div><div id="banner"><div class="bar_search">'._T('search_top').'</div>
1312 </div>
1313 ';
1314         echo $dat;
1315         if($searchKeyword==''){
1316                 echo '<form action="'.PHP_SELF.'" method="post">
1317 <div id="search">
1318 <input type="hidden" name="mode" value="search" />
1319 ';
1320                 echo '<ul>'._T('search_notice').'<input class="inputtext" type="text" name="keyword" size="30" />
1321 '._T('search_target').'<select name="field"><option value="com" selected="selected">'._T('search_target_comment').'</option><option value="name">'._T('search_target_name').'</option><option value="sub">'._T('search_target_topic').'</option><option value="no">'._T('search_target_number').'</option></select>
1322 '._T('search_method').'<select name="method"><option value="AND" selected="selected">'._T('search_method_and').'</option><option value="OR">'._T('search_method_or').'</option></select>
1323 <input type="submit" value="'._T('search_submit_btn').'" />
1324 </li>
1325 </ul>
1326 </div>
1327 </form>';
1328         }else{
1329                 $searchField = $_POST['field']; // 搜尋目標 (no:編號, name:名稱, sub:標題, com:內文)
1330                 $searchMethod = $_POST['method']; // 搜尋方法
1331                 $searchKeyword = preg_split('/( | )+/', trim($searchKeyword)); // 搜尋文字用空格切割
1332                 $hitPosts = $PIO->searchPost($searchKeyword, $searchField, $searchMethod); // 直接傳回符合的文章內容陣列
1333
1334                 echo '<div id="search_result">
1335 ';
1336                 $resultlist = '';
1337                 foreach($hitPosts as $post){
1338                         extract($post);
1339                         if(USE_CATEGORY){
1340                                 $ary_category = explode(',', str_replace('&#44;', ',', $category)); $ary_category = array_map('trim', $ary_category);
1341                                 $ary_category_count = count($ary_category);
1342                                 $ary_category2 = array();
1343                                 for($p = 0; $p < $ary_category_count; $p++){
1344                                         if($c = $ary_category[$p]) $ary_category2[] = '<a href="'.PHP_SELF.'?mode=category&amp;c='.urlencode($c).'">'.$c.'</a>';
1345                                 }
1346                                 $category = implode(', ', $ary_category2);
1347                         }else $category = '';
1348                         $arrLabels = array('{$NO}'=>'<a href="'.PHP_SELF.'?res='.($resto?$resto.'#r'.$no:$no).'">'.$no.'</a>', '{$SUB}'=>$sub, '{$NAME}'=>$name, '{$NOW}'=>$now, '{$COM}'=>$com, '{$CATEGORY}'=>$category, '{$NAME_TEXT}'=>_T('post_name'), '{$CATEGORY_TEXT}'=>_T('post_category'));
1349                         $resultlist .= $PTE->ParseBlock('SEARCHRESULT',$arrLabels);
1350                 }
1351                 echo $resultlist ? $resultlist : '<div style="text-align: center">'._T('search_notfound').'<br/><a href="?mode=search">'._T('search_back').'</a></div>';
1352                 echo "</div>";
1353         }
1354         echo "</body>\n</html>";
1355 }
1356
1357 /* 利用類別標籤搜尋符合的文章 */
1358 function searchCategory(){
1359         global $PTE, $PIO, $PMS, $FileIO, $language;
1360         $category = isset($_GET['c']) ? strtolower(strip_tags(trim($_GET['c']))) : ''; // 搜尋之類別標籤
1361         if(!$category) error(_T('category_nokeyword'));
1362         $category_enc = urlencode($category); $category_md5 = md5($category);
1363         $page = isset($_GET['p']) ? @intval($_GET['p']) : 1; if($page < 1) $page = 1; // 目前瀏覽頁數
1364         $isrecache = isset($_GET['recache']); // 是否強制重新生成快取
1365
1366         // 利用Session快取類別標籤出現篇別以減少負擔
1367         session_start(); // 啟動Session
1368         if(!isset($_SESSION['loglist_'.$category_md5]) || $isrecache){
1369                 $loglist = $PIO->searchCategory($category);
1370                 $_SESSION['loglist_'.$category_md5] = serialize($loglist);
1371         }else $loglist = unserialize($_SESSION['loglist_'.$category_md5]);
1372
1373         $loglist_count = count($loglist);
1374         if(!$loglist_count) error(_T('category_notfound'));
1375         $page_max = ceil($loglist_count / PAGE_DEF); if($page > $page_max) $page = $page_max; // 總頁數
1376
1377         // 分割陣列取出適當範圍作分頁之用
1378         $loglist_cut = array_slice($loglist, PAGE_DEF * ($page - 1), PAGE_DEF); // 取出特定範圍文章
1379         $loglist_cut_count = count($loglist_cut);
1380
1381         $dat = '';
1382         head($dat);
1383         $links = '[<a href="'.PHP_SELF2.'?'.time().'">'._T('return').'</a>][<a href="'.PHP_SELF.'?mode=category&amp;c='.$category_enc.'&amp;recache=1">'._T('category_recache').'</a>]';
1384         $PMS->useModuleMethods('LinksAboveBar', array(&$links,'category'));
1385         $dat .= "<div>$links</div>\n";
1386         for($i = 0; $i < $loglist_cut_count; $i++){
1387                 $posts = $PIO->fetchPosts($loglist_cut[$i]); // 取得文章內容
1388                 $dat .= arrangeThread($PTE, ($posts[0]['resto'] ? $posts[0]['resto'] : $posts[0]['no']), null, $posts, 0, $loglist_cut[$i], array(), array(), false, false, false); // 逐個輸出 (引用連結不顯示)
1389         }
1390
1391         $dat .= '<table border="1"><tr>';
1392         if($page > 1) $dat .= '<td><form action="'.PHP_SELF.'?mode=category&amp;c='.$category_enc.'&amp;p='.($page - 1).'" method="post"><div><input type="submit" value="'._T('prev_page').'" /></div></form></td>';
1393         else $dat .= '<td style="white-space: nowrap;">'._T('first_page').'</td>';
1394         $dat .= '<td>';
1395         for($i = 1; $i <= $page_max ; $i++){
1396                 if($i==$page) $dat .= "[<b>".$i."</b>] ";
1397                 else $dat .= '[<a href="'.PHP_SELF.'?mode=category&amp;c='.$category_enc.'&amp;p='.$i.'">'.$i.'</a>] ';
1398         }
1399         $dat .= '</td>';
1400         if($page < $page_max) $dat .= '<td><form action="'.PHP_SELF.'?mode=category&amp;c='.$category_enc.'&amp;p='.($page + 1).'" method="post"><div><input type="submit" value="'._T('next_page').'" /></div></form></td>';
1401         else $dat .= '<td style="white-space: nowrap;">'._T('last_page').'</td>';
1402         $dat .= '</tr></table>'."\n";
1403
1404         foot($dat);
1405         echo $dat;
1406 }
1407
1408 /* 顯示已載入模組資訊 */
1409 function listModules(){
1410         global $PMS, $language;
1411         $dat = '';
1412         head($dat);
1413         $links = '[<a href="'.PHP_SELF2.'?'.time().'">'._T('return').'</a>]';
1414         $PMS->useModuleMethods('LinksAboveBar', array(&$links,'modules'));
1415         $dat .= '<div id="bannerlink">'.$links.'</div><div id="banner"><div class="bar_info_mod">'._T('module_info_top').'</div>
1416 </div>
1417
1418 <div id="modules">
1419 ';
1420         /* Module Loaded */
1421         $dat .= _T('module_loaded').'<ul>'."\n";
1422         foreach($PMS->getLoadedModules() as $m) $dat .= '<li>'.$m."</li>\n";
1423         $dat .= "</ul><hr />\n";
1424
1425         /* Module Infomation */
1426         $dat .= _T('module_info').'<ul>'."\n";
1427         foreach($PMS->moduleInstance as $m) $dat .= '<li>'.$m->getModuleName().'<div style="padding-left:2em;">'.$m->getModuleVersionInfo()."</div></li>\n";
1428         $dat .= '</ul><hr />
1429 </div>
1430
1431 ';
1432         foot($dat);
1433         echo $dat;
1434 }
1435
1436 /* 刪除舊頁面快取檔 */
1437 function deleteCache($no){
1438         foreach($no as $n){
1439                 if($oldCaches = glob('./cache/'.$n.'-*')){
1440                         foreach($oldCaches as $o) @unlink($o);
1441                 }
1442         }
1443 }
1444
1445 /* 顯示系統各項資訊 */
1446 function showstatus(){
1447         global $PTE, $PIO, $FileIO, $PMS, $language, $LIMIT_SENSOR;
1448         $countline = $PIO->postCount(); // 計算投稿文字記錄檔目前資料筆數
1449         $counttree = $PIO->threadCount(); // 計算樹狀結構記錄檔目前資料筆數
1450         $tmp_total_size = total_size(); // 附加圖檔使用量總大小
1451         $tmp_ts_ratio = STORAGE_MAX > 0 ? $tmp_total_size / STORAGE_MAX : 0; // 附加圖檔使用量
1452
1453         // 決定「附加圖檔使用量」提示文字顏色
1454         if($tmp_ts_ratio < 0.3 ) $clrflag_sl = '235CFF';
1455         elseif($tmp_ts_ratio < 0.5 ) $clrflag_sl = '0CCE0C';
1456         elseif($tmp_ts_ratio < 0.7 ) $clrflag_sl = 'F28612';
1457         elseif($tmp_ts_ratio < 0.9 ) $clrflag_sl = 'F200D3';
1458         else $clrflag_sl = 'F2004A';
1459
1460         // 生成預覽圖物件資訊及功能是否正常
1461         $func_thumbWork = '<span style="color: red;">'._T('info_nonfunctional').'</span>';
1462         $func_thumbInfo = '(No thumbnail)';
1463         if(USE_THUMB !== 0){
1464                 $thumbType = USE_THUMB; if(USE_THUMB==1){ $thumbType = 'gd'; }
1465                 require(PHP_DIRECTORY.'lib/thumb/thumb.'.$thumbType.'.php');
1466                 $thObj = new ThumbWrapper();
1467                 if($thObj->isWorking()) $func_thumbWork = '<span style="color: blue;">'._T('info_functional').'</span>';
1468                 $func_thumbInfo = $thObj->getClass();
1469                 unset($thObj);
1470         }
1471
1472         // PIOSensor
1473         if(count($LIMIT_SENSOR))
1474                 $piosensorInfo=nl2br(PIOSensor::info($LIMIT_SENSOR));
1475
1476         $dat = '';
1477         head($dat);
1478         $links = '[<a href="'.PHP_SELF2.'?'.time().'">'._T('return').'</a>] [<a href="'.PHP_SELF.'?mode=moduleloaded">'._T('module_info_top').'</a>]';
1479         $PMS->useModuleMethods('LinksAboveBar', array(&$links,'status'));
1480         $dat .= '<div id="bannerlink">'.$links.'</div><div id="banner"><div class="bar_info">'._T('info_top').'</div>
1481 </div>
1482 ';
1483
1484         $dat .= '
1485 <div id="status-table" style="text-align: center;">
1486 <table border="1" style="margin: 0px auto; text-align: left;">
1487 <tr><td align="center" colspan="4">'._T('info_basic').'</td></tr>
1488 <tr><td style="width: 240px;">'._T('info_basic_ver').'</td><td colspan="3"> '.PIXMICAT_VER.' </td></tr>
1489 <tr><td>'._T('info_basic_pio').'</td><td colspan="3"> '.PIXMICAT_BACKEND.' : '.$PIO->pioVersion().'</td></tr>
1490 <tr><td>'._T('info_basic_threadsperpage').'</td><td colspan="3"> '.PAGE_DEF.' '._T('info_basic_threads').'</td></tr>
1491 <tr><td>'._T('info_basic_postsperpage').'</td><td colspan="3"> '.RE_DEF.' '._T('info_basic_posts').'</td></tr>
1492 <tr><td>'._T('info_basic_postsinthread').'</td><td colspan="3"> '.RE_PAGE_DEF.' '._T('info_basic_posts').' '._T('info_basic_posts_showall').'</td></tr>
1493 <tr><td>'._T('info_basic_bumpposts').'</td><td colspan="3"> '.MAX_RES.' '._T('info_basic_posts').' '._T('info_basic_0disable').'</td></tr>
1494 <tr><td>'._T('info_basic_bumphours').'</td><td colspan="3"> '.MAX_AGE_TIME.' '._T('info_basic_hours').' '._T('info_basic_0disable').'</td></tr>
1495 <tr><td>'._T('info_basic_urllinking').'</td><td colspan="3"> '.AUTO_LINK.' '._T('info_0no1yes').'</td></tr>
1496 <tr><td>'._T('info_basic_com_limit').'</td><td colspan="3"> '.COMM_MAX._T('info_basic_com_after').'</td></tr>
1497 <tr><td>'._T('info_basic_anonpost').'</td><td colspan="3"> '.ALLOW_NONAME.' '._T('info_basic_anonpost_opt').'</td></tr>
1498 <tr><td>'._T('info_basic_del_incomplete').'</td><td colspan="3"> '.KILL_INCOMPLETE_UPLOAD.' '._T('info_0no1yes').'</td></tr>
1499 <tr><td>'._T('info_basic_use_sample',THUMB_Q).'</td><td colspan="3"> '.USE_THUMB.' '._T('info_0notuse1use').'</td></tr>
1500 <tr><td>'._T('info_basic_useblock').'</td><td colspan="3"> '.BAN_CHECK.' '._T('info_0disable1enable').'</td></tr>
1501 <tr><td>'._T('info_basic_showid').'</td><td colspan="3"> '.DISP_ID.' '._T('info_basic_showid_after').'</td></tr>
1502 <tr><td>'._T('info_basic_cr_limit').'</td><td colspan="3"> '.BR_CHECK._T('info_basic_cr_after').'</td></tr>
1503 <!--<tr><td>'._T('info_basic_timezone').'</td><td colspan="3"> GMT </td></tr>-->
1504 <tr><td>'._T('info_basic_max_lines_limit').'</td><td colspan="3"> '.MAX_LINES._T('info_basic_max_lines_after').'</td></tr>
1505 <tr><td>'._T('info_basic_theme').'</td><td colspan="3"> '.$PTE->BlockValue('THEMENAME').' '.$PTE->BlockValue('THEMEVER').'<br/>by '.$PTE->BlockValue('THEMEAUTHOR').'</td></tr>
1506 <tr><td align="center" colspan="4">'._T('info_dsusage_top').'</td></tr>
1507 <tr align="center"><td>'._T('info_basic_threadcount').'</td><td colspan="'.(isset($piosensorInfo)?'2':'3').'"> '.$counttree.' '._T('info_basic_threads').'</td>'.(isset($piosensorInfo)?'<td rowspan="2">'.$piosensorInfo.'</td>':'').'</tr>
1508 <tr align="center"><td>'._T('info_dsusage_count').'</td><td colspan="'.(isset($piosensorInfo)?'2':'3').'">'.$countline.'</td></tr>
1509 <tr><td align="center" colspan="4">'._T('info_fileusage_top').STORAGE_LIMIT.' '._T('info_0disable1enable').'</td></tr>';
1510
1511         if(STORAGE_LIMIT){
1512                 $dat .= '
1513 <tr align="center"><td>'._T('info_fileusage_limit').'</td><td colspan="2">'.STORAGE_MAX.' KB</td><td rowspan="2">'._T('info_dsusage_usage').'<br /><span style="color: #'.$clrflag_sl.'">'.substr(($tmp_ts_ratio * 100), 0, 6).'</span> %</td></tr>
1514 <tr align="center"><td>'._T('info_fileusage_count').'</td><td colspan="2"><span style="color: #'.$clrflag_sl.'">'.$tmp_total_size.' KB</span></td></tr>';
1515         }else{
1516                 $dat .= '
1517 <tr align="center"><td>'._T('info_fileusage_count').'</td><td>'.$tmp_total_size.' KB</td><td colspan="2">'._T('info_dsusage_usage').'<br /><span style="color: green;">'._T('info_fileusage_unlimited').'</span></td></tr>';
1518         }
1519
1520         $dat .= '
1521 <tr><td align="center" colspan="4">'._T('info_server_top').'</td></tr>
1522 <tr align="center"><td colspan="3">PHP version</td><td>'.phpversion().'</td></tr>
1523 <tr align="center"><td colspan="3">'.$func_thumbInfo.'</td><td>'.$func_thumbWork.'</td></tr>
1524 </table>
1525 <hr />
1526 </div>'."\n";
1527
1528         foot($dat);
1529         echo $dat;
1530 }
1531
1532 /* 程式首次執行之初始化 */
1533 /* 初期設定 */
1534 function init(){
1535         global $PIO, $FileIO, $language;
1536         if(!is_writable(realpath('./'))) error(_T('init_permerror'));
1537
1538         $chkfolder = array(IMG_DIR, THUMB_DIR, 'cache/');
1539         // 逐一自動建置資料夾
1540         foreach($chkfolder as $value) if(!is_dir($value)){ mkdir($value); @chmod($value, 0777); }  // 沒有就建立
1541
1542         $PIO->dbInit(); // PIO Init
1543         $FileIO->init(); // FileIO Init
1544
1545         error(_T('init_inited'));
1546 }
1547
1548 /*-----------程式各項功能主要判斷-------------*/
1549 /*-----------Main-------------*/
1550 if(GZIP_COMPRESS_LEVEL && ($Encoding = CheckSupportGZip())){ ob_start(); ob_implicit_flush(0); } // 支援且開啟Gzip壓縮就設緩衝區
1551 $mode = isset($_GET['mode']) ? $_GET['mode'] : (isset($_POST['mode']) ? $_POST['mode'] : ''); // 目前執行模式 (GET, POST)
1552
1553 //init(); // ←■■!程式環境初始化,跑過一次後請刪除此行!■■
1554 switch($mode){
1555         case 'regist':
1556                 regist();
1557                 break;
1558         case 'admin':
1559                 $admin = isset($_REQUEST['admin']) ? $_REQUEST['admin'] : ''; // 管理者執行模式
1560                 valid();
1561                 switch($admin){
1562                         case 'del': admindel(); break;
1563                         case 'logout':
1564                                 adminAuthenticate('logout');
1565                                 header('HTTP/1.1 302 Moved Temporarily');
1566                                 header('Location: '.fullURL().PHP_SELF2.'?'.time());
1567                                 break;
1568                         case 'optimize':
1569                         case 'check':
1570                         case 'repair':
1571                         case 'export':
1572                                 if(!$PIO->dbMaintanence($admin)) echo _T('action_main_notsupport');
1573                                 else echo _T('action_main_'.$admin).(($mret = $PIO->dbMaintanence($admin,true))?_T('action_main_success'):_T('action_main_failed')).(is_bool($mret)?'':'<br/>'.$mret);
1574                                 die("</div></form></body>\n</html>");
1575                                 break;
1576                         case 'stylesheets': manage_css(); break;
1577                         default:
1578                 }
1579                 break;
1580         case 'search':
1581                 search();
1582                 break;
1583         case 'status':
1584                 showstatus();
1585                 break;
1586         case 'category':
1587                 searchCategory();
1588                 break;
1589         case 'module':
1590                 $loadModule = isset($_GET['load']) ? $_GET['load'] : '';
1591                 if($PMS->onlyLoad($loadModule)) $PMS->moduleInstance[$loadModule]->ModulePage();
1592                 else echo '404 Not Found';
1593                 break;
1594         case 'moduleloaded':
1595                 listModules();
1596                 break;
1597         case 'init':
1598                 init(); // ←■■!程式環境初始化,跑過一次後請刪除此行!■■
1599                 break;
1600         case 'usrdel':
1601                 usrdel();
1602         case 'remake':
1603                 updatelog();
1604                 header('HTTP/1.1 302 Moved Temporarily');
1605                 header('Location: '.fullURL().PHP_SELF2.'?'.time());
1606                 break;
1607         default:
1608                 // 如果瀏覽器支援XHTML標準MIME就輸出
1609                 header('Content-Type: '.((USE_XHTML && strpos($_SERVER['HTTP_ACCEPT'],'application/xhtml+xml')!==FALSE) ? 'application/xhtml+xml' : 'text/html').'; charset=utf-8');
1610                 $res = isset($_GET['res']) ? $_GET['res'] : 0; // 欲回應編號
1611                 if($res){ // 回應模式輸出
1612                         $page = isset($_GET['page_num']) ? $_GET['page_num'] : 'RE_PAGE_MAX';
1613                         if(!($page=='all' || $page=='RE_PAGE_MAX')) $page = intval($_GET['page_num']);
1614                         updatelog($res, $page); // 實行分頁
1615                 }elseif(isset($_GET['page_num']) && intval($_GET['page_num']) > -1){ // PHP動態輸出一頁
1616                         updatelog(0, intval($_GET['page_num']));
1617                 }else{ // 導至靜態庫存頁
1618                         if(!is_file(PHP_SELF2)) updatelog();
1619                         header('HTTP/1.1 302 Moved Temporarily');
1620                         header('Location: '.fullURL().PHP_SELF2.'?'.time());
1621                 }
1622 }
1623 if(GZIP_COMPRESS_LEVEL && $Encoding){ // 有啟動Gzip
1624         if(!ob_get_length()) exit; // 沒內容不必壓縮
1625         header('Content-Encoding: '.$Encoding);
1626         header('X-Content-Encoding-Level: '.GZIP_COMPRESS_LEVEL);
1627         header('Vary: Accept-Encoding');
1628         print gzencode(ob_get_clean(), GZIP_COMPRESS_LEVEL); // 壓縮內容
1629 }
1630 ?>