3 * Pixmicat! Common Library
8 * @version $Id: lib_common.php 690 2009-04-06 01:30:13Z scribe $
9 * @date $Date: 2009-04-06 09:30:13 +0800 (星期一, 06 四月 2009) $
13 * 更改 PHP 捕捉錯誤功能並顯示自訂錯誤
15 function PMCCore_errorHandler($errno, $errstr, $errfile, $errline){
16 //---- header('Content-type: text/plain;charset=utf-8');
20 print_r('Error: '.$errstr.'<br />');
23 print_r('Warning: '.$errstr.' '.$errfile.' #'.$errline.'<br />');
28 include_once(PHP_DIRECTORY.'lib/lib_css.php'); // load CSS data
32 function head(&$dat,$resno=0){
33 global $PTE, $PMS, $language, $style_load, $style_bar, $jsdonk;
36 // Title code from old yotsubanome //++++---- suigintou v.3.0+ code
37 if(SHOWTITLEIMG == 1){
38 $title = '<img src="'.TITLEIMG.'" alt="'.TITLE.'" />';
39 if(SHOWTITLETXT) $title .= '<br />';
40 }elseif(SHOWTITLEIMG == 2){
41 $title = '<img src="'.TITLEIMG.'" onclick="this.src=this.src;" alt="'.TITLE.'" />';
42 if(SHOWTITLETXT) $title .= '<br />';
44 if(SHOWTITLETXT) $title .= TITLE;
46 $pte_vals = array('{$TITLE}'=>TITLE,'{$TITLEHEAD}'=>$title,'{$TITLECOM}'=>strip_tags(TITLECOM),'{$RESTO}'=>$resno?$resno:'','{$STYLE_LOAD}'=>$style_load,'{$STYLE_BAR}'=>$style_bar,'{$JS_DIR}'=>JS_DIR,'{$CSS_DIR}'=>CSS_DIR,'{$JSDONK}'=>$jsdonk,'{$FAV_ICON}'=>FAV_ICON,'{$LANGUAGE}'=>PIXMICAT_LANGUAGE);
47 $dat .= $PTE->ParseBlock('HEADER',$pte_vals);
48 $PMS->useModuleMethods('Head', array(&$dat,$resno)); // "Head" Hook Point
49 $pte_vals+=array('{$ALLOW_UPLOAD_EXT}' => ALLOW_UPLOAD_EXT,
50 '{$JS_REGIST_WITHOUTCOMMENT}' => str_replace('\'', '\\\'', _T('regist_withoutcomment')),
51 '{$JS_REGIST_UPLOAD_NOTSUPPORT}' => str_replace('\'', '\\\'', _T('regist_upload_notsupport')),
52 '{$JS_CONVERT_SAKURA}' => str_replace('\'', '\\\'', _T('js_convert_sakura')));
53 $dat .= $PTE->ParseBlock('JSHEADER',$pte_vals);
55 $pte_vals += array('{$TOP_LINKS}' => TOP_LINKS,
56 '{$HOME}' => '[<a href="'.HOME.'" rel="_top">'._T('head_home').'</a>]',
57 '{$STATUS}' => '[<a href="'.PHP_SELF.'?mode=status">'._T('head_info').'</a>]',
58 '{$ADMIN}' => '[<a href="'.PHP_SELF.'?mode=admin">'._T('head_admin').'</a>]',
59 '{$REFRESH}' => '[<a href="'.PHP_SELF2.'?">'._T('head_refresh').'</a>]',
60 '{$SEARCH}' => (USE_SEARCH) ? '[<a href="'.PHP_SELF.'?mode=search">'._T('head_search').'</a>]' : '');
61 if(STYLEBAR) $pte_vals += array('{$HOOKLINKS}' => '<small>'.$style_bar.'</small>');
62 else $pte_vals += array('{$HOOKLINKS}' => '');
63 $PMS->useModuleMethods('Toplink', array(&$pte_vals['{$HOOKLINKS}'],$resno)); // "Toplink" Hook Point
64 $dat .= $PTE->ParseBlock('BODYHEAD',$pte_vals);
69 function form(&$dat, $resno, $iscollapse=true, $retURL=PHP_SELF, $name='', $mail='', $sub='', $com='', $cat='', $mode='regist'){
70 global $PTE, $PMS, $ADDITION_INFO, $language;
71 $pte_vals = array('{$SELF}'=>$retURL, '{$FORMTOP}'=>'', '{$MODE}'=>$mode);
72 $isedit = ($mode == 'edit'); // 是否為編輯模式
73 if($resno && !$isedit){
74 $links = '[<a href="'.PHP_SELF2.'?'.time().'">'._T('return').'</a>]';
75 $PMS->useModuleMethods('LinksAboveBar', array(&$links,'reply',$resno)); // "LinksAboveBar" Hook Point
76 $pte_vals['{$FORMTOP}'] = '<div id="bannerlink">'.$links.'</div><div id="banner"><div class="theader">'._T('form_top').'</div></div>';
77 }//----class="bar_reply"
78 if(!$resno) $ntno = _T('form_newt');
79 else $ntno = _T('reply_btn').':'.$resno; // new thread & reply:$resno (A KusabaX function that was reverse Engineered by sparky4 (I never looked at the code for that function w))
80 if(USE_FLOATFORM && !$resno && $iscollapse) $pte_vals['{$FORMTOP}'] .= "\n".'[<span id="show" class="hide" onmouseover="showform();" onclick="showform();">'._T('form_showpostform').'</span><span id="hide" class="show" onmouseover="hideform();" onclick="hideform();">'._T('form_hidepostform').'</span>]';
81 $pte_vals += array('{$MAX_FILE_SIZE}' => MAX_KB * 1024,
82 '{$RESTO}' => $resno ? '<input type="hidden" name="resto" value="'.$resno.'" />' : '',
83 '{$FORM_NAME_TEXT}' => _T('form_name'),
84 '{$FORM_NAME_FIELD}' => '<input class="hide" type="text" name="name" value="spammer" /><input class="inputtext" type="text" name="'.FT_NAME.'" id="fname" size="28" value="'.$name.'" />',
85 '{$FORM_EMAIL_TEXT}' => _T('form_email'),
86 '{$FORM_EMAIL_FIELD}' => '<input class="inputtext" type="text" name="'.FT_EMAIL.'" id="femail" size="28" value="'.$mail.'" /><input type="text" class="hide" name="email" value="foo@foo.bar" />',
87 '{$FORM_TOPIC_TEXT}' => _T('form_topic'),
88 '{$FORM_TOPIC_FIELD}' => '<input class="hide" value="DO NOT FIX THIS" type="text" name="sub" /><input class="inputtext" type="text" name="'.FT_SUBJECT.'" id="fsub" size="35" value="'.$sub.'" />',
89 '{$FORM_SUBMIT}' => ' <input type="submit" name="sendbtn" value="'._T('form_submit_btn').'" /><small>「'.$ntno.'」</small>',
90 '{$FORM_COMMENT_TEXT}' => _T('form_comment'),
91 '{$FORM_COMMENT_FIELD}' => '<textarea class="inputtext" name="'.FT_COMMENT.'" id="fcom" cols="48" rows="4">'.$com.'</textarea><textarea name="com" class="hide" cols="48" rows="4">EID OG SMAPS</textarea>',
92 '{$FORM_DELETE_PASSWORD_FIELD}' => '<input class="inputtext" type="password" name="pwd" size="8" maxlength="8" value="" />',
93 '{$FORM_DELETE_PASSWORD_TEXT}' => _T('form_delete_password'),
94 '{$FORM_DELETE_PASSWORD_NOTICE}' => _T('form_delete_password_notice'),
95 '{$FORM_EXTRA_COLUMN}' => '',
96 '{$FORM_NOTICE}' => _T('form_notice',str_replace('|',', ',ALLOW_UPLOAD_EXT),MAX_KB,($resno ? MAX_RW : MAX_W),($resno ? MAX_RH : MAX_H)),
97 '{$HOOKPOSTINFO}' => '',
98 '{$ADDITION_INFO}' => $ADDITION_INFO,
99 '{$FORM_NOTICE_NOSCRIPT}' => _T('form_notice_noscript'));
100 $PMS->useModuleMethods('PostForm', array(&$pte_vals['{$FORM_EXTRA_COLUMN}'])); // "PostForm" Hook Point
101 if(!$isedit && (RESIMG || !$resno)){
102 $pte_vals += array('{$FORM_ATTECHMENT_TEXT}' => _T('form_attechment'),
103 '{$FORM_ATTECHMENT_FIELD}' => '<input class="inputtext" type="file" name="upfile" id="fupfile" size="35" /><input class="hide" type="checkbox" name="reply" value="yes" />');
104 if(!NO_TEXTONLY || NO_TEXTONLY == 1){
105 $pte_vals += array('{$FORM_NOATTECHMENT_TEXT}' => _T('form_noattechment'),
106 '{$FORM_NOATTECHMENT_FIELD}' => '<input type="checkbox" name="noimg" id="noimg" value="on" />');
109 if(OPTION){ //++++ more options will be added on later
110 $pte_vals['{$FORM_OPTION1_TEXT}'] = _T('form_option1');
111 if(USE_UPSERIES){ // 啟動連貼機能
112 $pte_vals['{$FORM_CONTPOST_FIELD}'] = '<input type="checkbox" name="up_series" id="up_series" value="on"'.((isset($_GET["upseries"]) && $resno)?' checked="checked"':'').' />';
113 $pte_vals['{$FORM_CONTPOST_TEXT}'] = _T('form_contpost');
116 $pte_vals['{$FORM_OPTION_HOOK}'] = '';
119 $pte_vals += array('{$FORM_CATEGORY_FIELD}' => '<input class="inputtext" type="text" name="category" size="28" value="'.$cat.'" />',
120 '{$FORM_CATEGORY_TEXT}' => _T('form_category'),
121 '{$FORM_CATEGORY_NOTICE}' => _T('form_category_notice'));
123 if(STORAGE_LIMIT) $pte_vals['{$FORM_NOTICE_STORAGE_LIMIT}'] = _T('form_notice_storage_limit',total_size(),STORAGE_MAX);
124 $PMS->useModuleMethods('PostInfo', array(&$pte_vals['{$HOOKPOSTINFO}'])); // "PostInfo" Hook Point
126 if(USE_FLOATFORM && !$resno && $iscollapse) $pte_vals['{$FORMBOTTOM}'] = '<script type="text/javascript">hideform();</script>';
127 $dat .= $PTE->ParseBlock('POSTFORM',$pte_vals);
132 function foot(&$dat){
133 global $PTE, $PMS, $language;
134 $pte_vals = array('{$FOOTER}'=>'<!-- GazouBBS v3.0 --><!-- ふたば改0.8 --><!-- Pixmicat! --><!-- 四葉の芽改0.8 -->'."\n");
135 $PMS->useModuleMethods('Foot', array(&$pte_vals['{$FOOTER}'])); // "Foot" Hook Point
136 $pte_vals['{$FOOTER}'] .= '<small>- <a href="http://php.s3.to" rel="_top">GazouBBS</a> + <a href="http://www.2chan.net/" rel="_top">futaba</a> + <a href="http://pixmicat.openfoundry.org/" rel="_blank">Pixmicat!</a> + <a href="http://4ch.irc.su/" rel="_blank">yotsubanome</a> -</small>';
137 $pte_vals['{$FOOTER}'] .= '<p>
138 <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml11" alt="Valid XHTML 1.1" height="31" width="88" /></a>
140 $dat .= $PTE->ParseBlock('FOOTER',$pte_vals);
145 function auto_link_callback($matches){
146 return (strtolower($matches[3]) == "</a>") ? $matches[0] : preg_replace('/(https?|ftp|news|irc|gopher)(:\/\/[\w\+\$\;\?\.\{\}%,!#~*\/:@&=_-]+)/u', '<a href="$1$2" rel="_blank">$1$2</a>', $matches[0]);
148 function auto_link($proto){
149 $proto = preg_replace('|<br\s*/?>|',"\n",$proto);
150 $proto = preg_replace_callback('/(>|^)([^<]+?)(<.*?>|$)/m','auto_link_callback',$proto);
151 return str_replace("\n",'<br />',$proto);
155 function quoteLight($comment){
156 return preg_replace('/(^|<br \/>)((?:>|>).*?)(?=<br \/>|$)/u', '$1<span class="unkfunc">$2</span>', $comment);
159 function quoteLight2($comment){
160 return preg_replace('/(^|<br \/>)((?:#|#).*?)(?=<br \/>|$)/u', '$1<span class="unkfunc2">$2</span>', $comment);
165 return 'http://'.$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], PHP_SELF));
169 function anti_sakura($str){
170 return preg_match('/[\x{E000}-\x{F848}]/u', $str);
175 function error($mes, $dest=''){
177 if(is_file($dest)) unlink($dest);
178 $pte_vals = array('{$SELF2}'=>PHP_SELF2.'?'.time(), '{$MESG}'=>$mes, '{$RETURN_TEXT}'=>_T('return'), '{$BACK_TEXT}'=>_T('error_back'));
181 $dat .= $PTE->ParseBlock('ERROR',$pte_vals);
188 function CleanStr($str, $IsAdmin=false){
190 $str = trim($str); // 去除前後多餘空白
191 if(get_magic_quotes_gpc()) $str = stripslashes($str); // "\"斜線符號去除
192 // XML 1.1 Second Edition: 部分避免用字 (http://www.w3.org/TR/2006/REC-xml11-20060816/#charsets)
193 $str = preg_replace('/([\x1-\x8\xB-\xC\xE-\x1F\x7F-\x84\x86-\x9F\x{FDD0}-\x{FDDF}])/u', '', htmlspecialchars($str));
195 if($IsAdmin && $config['CAP.ISHTML']){ // 管理員開啟HTML
196 $str = preg_replace('/<(.*?)>/', '<$1>', $str); // 如果有<...>則轉回<...>成為正常標籤
201 /* 適用UTF-8環境的擬substr,取出特定數目字元
202 原出處:Sea Otter @ 2005.05.10
203 http://www.meyu.net/star/viewthread.php?tid=267&fpage=10 */
204 function str_cut($str, $maxlen=20){
205 $i = $l = 0; $len = strlen($str); $f = true; $return_str = $str;
207 $chars = ord($str{$i});
208 if($chars < 0x80){ $l++; $i++; }
209 elseif($chars < 0xe0){ $l++; $i += 2; }
210 elseif($chars < 0xf0){ $l += 2; $i += 3; }
211 elseif($chars < 0xf8){ $l++; $i += 4; }
212 elseif($chars < 0xfc){ $l++; $i += 5; }
213 elseif($chars < 0xfe){ $l++; $i += 6; }
214 if(($l >= $maxlen) && $f){
215 $return_str = substr($str, 0, $i);
218 if(($l > $maxlen) && ($i <= $len)){
219 $return_str = $return_str.'…';
226 /* 檢查瀏覽器和伺服器是否支援gzip壓縮方式 */
227 function CheckSupportGZip(){
228 $HTTP_ACCEPT_ENCODING = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '';
229 if(headers_sent() || connection_aborted()) return 0; // 已送出資料,取消
230 if(!(function_exists('gzencode') && function_exists('ob_start') && function_exists('ob_get_clean'))) return 0; // 伺服器相關的套件或函式無法使用,取消
231 if(strpos($HTTP_ACCEPT_ENCODING, 'gzip')!==false) return 'gzip';
235 /* 封鎖 IP / Hostname / DNSBL 綜合性檢查 */
236 function BanIPHostDNSBLCheck($IP, $HOST, &$baninfo){
237 if(!BAN_CHECK) return false; // Disabled
238 global $BANPATTERN, $DNSBLservers, $DNSBLWHlist;
241 $HOST = strtolower($HOST);
242 $checkTwice = ($IP != $HOST); // 是否需檢查第二次
244 foreach($BANPATTERN as $pattern){
245 $slash = substr_count($pattern, '/');
246 if($slash==2){ // RegExp
248 }elseif($slash==1){ // CIDR Notation
249 if(matchCIDR($IP, $pattern)){ $IsBanned = true; break; }
251 }elseif(strpos($pattern, '*')!==false || strpos($pattern, '?')!==false){ // Wildcard
252 $pattern = '/^'.str_replace(array('.', '*', '?'), array('\.', '.*', '.?'), $pattern).'$/i';
254 if($IP==$pattern || ($checkTwice && $HOST==strtolower($pattern))){ $IsBanned = true; break; }
257 if(preg_match($pattern, $HOST) || ($checkTwice && preg_match($pattern, $IP))){ $IsBanned = true; break; }
259 if($IsBanned){ $baninfo = _T('ip_banned'); return true; }
261 // DNS-based Blackhole List(DNSBL) 黑名單
262 if(!$DNSBLservers[0]) return false; // Skip check
263 if(array_search($IP, $DNSBLWHlist)!==false) return false; // IP位置在白名單內
264 $rev = implode('.', array_reverse(explode('.', $IP)));
265 $lastPoint = count($DNSBLservers) - 1; if($DNSBLservers[0] < $lastPoint) $lastPoint = $DNSBLservers[0];
267 for($i = 1; $i <= $lastPoint; $i++){
268 $query = $rev.'.'.$DNSBLservers[$i].'.'; // FQDN
269 $result = gethostbyname($query);
270 if($result && ($result != $query)){ $isListed = $DNSBLservers[$i]; break; }
272 if($isListed){ $baninfo = _T('ip_dnsbl_banned',$isListed); return true; }
275 function matchCIDR($addr, $cidr) {
276 list($ip, $mask) = explode('/', $cidr);
277 return (ip2long($addr) >> (32 - $mask) == ip2long($ip.str_repeat('.0', 3 - substr_count($ip, '.'))) >> (32 - $mask));
281 function adminAuthenticate($mode){
283 $loginkey = md5($_SERVER['HTTP_USER_AGENT'].ADMIN_PASS.$_SERVER['REMOTE_ADDR']);
286 if(isset($_SESSION['pmcLogin'])) unset($_SESSION['pmcLogin']);
289 $_SESSION['pmcLogin'] = $loginkey;
292 if(isset($_SESSION['pmcLogin']) && $_SESSION['pmcLogin']==$loginkey){
293 session_regenerate_id(true); // 更換 Session id key 避免 Hijacking
301 /* 取得 (Transparent) Proxy 提供之 IP 參數 */
302 function getREMOTE_ADDR(){
303 // 同時有 VIA 和 FORWARDED_FOR 較可能為 Proxy
304 if(isset($_SERVER['HTTP_VIA']) && isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
305 $tmp = preg_split('/[ ,]+/', $_SERVER['HTTP_X_FORWARDED_FOR']);
306 // 防止 Squid "unknown" 問題,此種情況直接使用 REMOTE_ADDR
307 return ($tmp[0] != 'unknown' ? $tmp[0] : $_SERVER['REMOTE_ADDR']);
309 return $_SERVER['REMOTE_ADDR'];
312 /* css style sheet */
313 function format_js_var($var_name){
314 return("'".$var_name."'");
318 # Written by Coda, functionified by Foone/Popcorn Mariachi#!9i78bPeIxI
319 # This code is in the public domain
320 # identify_apng returns:
321 # true if the file is an APNG
322 # false if it is any other sort of file (it is not checked for PNG validity)
323 # takes on argument, a filename.
325 function identify_apng($filename){
327 $img_bytes = file_get_contents($filename);
329 if(strpos(substr($img_bytes, 0, strpos($img_bytes, 'IDAT')), 'acTL') !== false){
330 return $apng = TRUE; // APNG
333 return $apng = FALSE; // not APNG
336 /* total amount of ommited posts/images */ // suigintou v.3.0+ code
337 function _res($posts, $images = 0){
338 $omitp = ($posts) ? sp(_T('notice_omitted_posts'), $posts) : false;
339 $omiti = ($images) ? sp(_T('notice_omitted_images'), $images) : false;
340 return($omitp.$omiti);
342 /* plural strings for ommited post messages */
343 function sp($string, $value, $shownull = false){
344 // Determine whether to show string for zero values
345 if(!$value && $shownull || $value) $show = true;
346 elseif(!$value && !$shownull) $show = false;
347 else $show = $shownull;
349 if($show) $string = str_replace('[#]', number_format($value), $string);
352 // Separate words from plural forms
353 ereg('(.*)(\[)(.*)(\])(.*)', $string, $regs);
354 $plu_word_s = $regs[1];
355 $plu_bits = $regs[3];
356 $plu_word_e = $regs[5];
358 if(strstr($plu_bits, '|')){
359 // To the left of the | is the single form; to the right, the plural form
360 ereg('(.*)(\|)(.*)', $plu_bits, $regs);
364 // [|s] will work for words that should end in "s", but this bit handles [s]
369 // Spit it out, Smith
370 $plu_bit_d = ($value == -1 || $value == 1)?$single:$plural;
371 $plu_word = $plu_word_s.$plu_bit_d.$plu_word_e;
373 if($plu_word) return($plu_word); else return($string);
378 /* comment too long function */
379 // truncate $str to $config['LINE_NUMBER'] lines and return $str and $abbr
380 // where $abbr = whether or not $str was actually truncated
381 function abbreviate($str, $max_lines){
382 $lines = explode("<br />", $str);
383 if(count($lines) > $max_lines){
385 $lines = array_slice($lines, 0, $max_lines);
386 $str = implode("<br />", $lines);
388 // close spans after abbreviating
389 // XXX will not work with more html - use abbreviate_html from shiichan
390 $str .= str_repeat("</span>", substr_count($str, "<span") - substr_count($str, "</span"));
391 return array($str, $abbr);