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) $
16 if(file_exists(DATA_DIR.CSV_SS)){ // Load FuuR4 CSS data
17 $style_data = DATA_DIR.CSV_SS;
19 $lines = explode("\n", file_get_contents($style_data));
20 foreach($lines as $null => $line){
22 list($style_name, $style_short, $style_path, $style_rel) = explode (',', $line);
23 $style_path = CSS_DIR.$style_path;
24 if(file_exists($style_path)){
25 if($style_rel) $style_rel = 'stylesheet';
26 else $style_rel = 'alternate stylesheet';
27 $style_load .= '<link rel="'.$style_rel.'" type="text/css" href="'.$style_path.'" title="'.$style_name.'" />'."\n";
28 $style_js = format_js_var($style_name);
29 $style_title = str_replace('[what]', $style_name, _T('style_tooltip'));
30 $style_bar .= ' <a href="javascript:set_stylesheet('.$style_js.')" title="'.$style_title.'">'.$style_short.'</a> |';
37 // Tidy up trailing seperators and empty brackets
38 $style_bar = str_replace('|]', ']', $style_bar);
39 $style_bar = str_replace('[] ', '', $style_bar);
40 $style_bar = str_replace('[]', '', $style_bar);
43 // Load stylesheet setting from config.php
44 // if either of the datafiles are missing or empty
45 if(str_replace('[]', '', $style_bar) == '') $style_load .= '<link rel="stylesheet" type="text/css" href="'.CSS_DIR.CSSFILE.'" />';
47 // style sheet js loader
48 $jsdonk = 'var style_cookie = "';
49 $jsdonk .= ($style_bar) ? 'yo_style' : '';
55 function head(&$dat,$resno=0){
56 global $PTE, $PMS, $language, $style_load, $style_bar, $jsdonk;
59 // Title from old yotsubanome //++++----
60 if(SHOWTITLEIMG == 1){
61 $title = '<img src="'.TITLEIMG.'" alt="'.TITLE.'" />';
62 if(SHOWTITLETXT) $title .= '<br />';
63 }elseif(SHOWTITLEIMG == 2){
64 $title = '<img src="'.TITLEIMG.'" onclick="this.src=this.src;" alt="'.TITLE.'" />';
65 if(SHOWTITLETXT) $title .= '<br />';
67 if(SHOWTITLETXT) $title .= TITLE;
69 $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);
70 $dat .= $PTE->ParseBlock('HEADER',$pte_vals);
71 $PMS->useModuleMethods('Head', array(&$dat,$resno)); // "Head" Hook Point
72 $pte_vals+=array('{$ALLOW_UPLOAD_EXT}' => ALLOW_UPLOAD_EXT,
73 '{$JS_REGIST_WITHOUTCOMMENT}' => str_replace('\'', '\\\'', _T('regist_withoutcomment')),
74 '{$JS_REGIST_UPLOAD_NOTSUPPORT}' => str_replace('\'', '\\\'', _T('regist_upload_notsupport')),
75 '{$JS_CONVERT_SAKURA}' => str_replace('\'', '\\\'', _T('js_convert_sakura')));
76 $dat .= $PTE->ParseBlock('JSHEADER',$pte_vals);
78 $pte_vals += array('{$TOP_LINKS}' => TOP_LINKS,
79 '{$HOME}' => '[<a href="'.HOME.'" rel="_top">'._T('head_home').'</a>]',
80 '{$STATUS}' => '[<a href="'.PHP_SELF.'?mode=status">'._T('head_info').'</a>]',
81 '{$ADMIN}' => '[<a href="'.PHP_SELF.'?mode=admin">'._T('head_admin').'</a>]',
82 '{$REFRESH}' => '[<a href="'.PHP_SELF2.'?">'._T('head_refresh').'</a>]',
83 '{$SEARCH}' => (USE_SEARCH) ? '[<a href="'.PHP_SELF.'?mode=search">'._T('head_search').'</a>]' : '');
84 if(STYLEBAR) $pte_vals += array('{$HOOKLINKS}' => '<small>'.$style_bar.'</small>');
85 else $pte_vals += array('{$HOOKLINKS}' => '');
86 $PMS->useModuleMethods('Toplink', array(&$pte_vals['{$HOOKLINKS}'],$resno)); // "Toplink" Hook Point
87 $dat .= $PTE->ParseBlock('BODYHEAD',$pte_vals);
92 function form(&$dat, $resno, $iscollapse=true, $retURL=PHP_SELF, $name='', $mail='', $sub='', $com='', $cat='', $mode='regist'){
93 global $PTE, $PMS, $ADDITION_INFO, $language;
94 $pte_vals = array('{$SELF}'=>$retURL, '{$FORMTOP}'=>'', '{$MODE}'=>$mode);
95 $isedit = ($mode == 'edit'); // 是否為編輯模式
96 if($resno && !$isedit){
97 $links = '[<a href="'.PHP_SELF2.'?'.time().'">'._T('return').'</a>]';
98 $PMS->useModuleMethods('LinksAboveBar', array(&$links,'reply',$resno)); // "LinksAboveBar" Hook Point
99 $pte_vals['{$FORMTOP}'] = '<div id="bannerlink">'.$links.'</div><div id="banner"><div class="theader">'._T('form_top').'</div></div>';
100 } //----class="bar_reply"
101 if(!$resno) $ntno = _T('form_newt');
102 else $ntno = _T('reply_btn').':'.$resno; // new thread & reply:$resno
103 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>]';
104 $pte_vals += array('{$MAX_FILE_SIZE}' => MAX_KB * 1024,
105 '{$RESTO}' => $resno ? '<input type="hidden" name="resto" value="'.$resno.'" />' : '',
106 '{$FORM_NAME_TEXT}' => _T('form_name'),
107 '{$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.'" />',
108 '{$FORM_EMAIL_TEXT}' => _T('form_email'),
109 '{$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" />',
110 '{$FORM_TOPIC_TEXT}' => _T('form_topic'),
111 '{$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.'" />',
112 '{$FORM_SUBMIT}' => ' <input type="submit" name="sendbtn" value="'._T('form_submit_btn').'" /><small>「'.$ntno.'」</small>',
113 '{$FORM_COMMENT_TEXT}' => _T('form_comment'),
114 '{$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>',
115 '{$FORM_DELETE_PASSWORD_FIELD}' => '<input class="inputtext" type="password" name="pwd" size="8" maxlength="8" value="" />',
116 '{$FORM_DELETE_PASSWORD_TEXT}' => _T('form_delete_password'),
117 '{$FORM_DELETE_PASSWORD_NOTICE}' => _T('form_delete_password_notice'),
118 '{$FORM_EXTRA_COLUMN}' => '',
119 '{$FORM_NOTICE}' => _T('form_notice',str_replace('|',', ',ALLOW_UPLOAD_EXT),MAX_KB,($resno ? MAX_RW : MAX_W),($resno ? MAX_RH : MAX_H)),
120 '{$HOOKPOSTINFO}' => '',
121 '{$ADDITION_INFO}' => $ADDITION_INFO,
122 '{$FORM_NOTICE_NOSCRIPT}' => _T('form_notice_noscript'));
123 $PMS->useModuleMethods('PostForm', array(&$pte_vals['{$FORM_EXTRA_COLUMN}'])); // "PostForm" Hook Point
124 if(!$isedit && (RESIMG || !$resno)){
125 $pte_vals += array('{$FORM_ATTECHMENT_TEXT}' => _T('form_attechment'),
126 '{$FORM_ATTECHMENT_FIELD}' => '<input class="inputtext" type="file" name="upfile" id="fupfile" size="35" /><input class="hide" type="checkbox" name="reply" value="yes" />');
127 if(!NO_TEXTONLY || NO_TEXTONLY == 1){
128 $pte_vals += array('{$FORM_NOATTECHMENT_TEXT}' => _T('form_noattechment'),
129 '{$FORM_NOATTECHMENT_FIELD}' => '<input type="checkbox" name="noimg" id="noimg" value="on" />');
132 if(OPTION || USE_UPSERIES){ //++++ more options will be added on later
133 $pte_vals['{$FORM_OPTION1_TEXT}'] = _T('form_option1');
135 if(USE_UPSERIES){ // 啟動連貼機能
136 $pte_vals['{$FORM_CONTPOST_FIELD}'] = '<input type="checkbox" name="up_series" id="up_series" value="on"'.((isset($_GET["upseries"]) && $resno)?' checked="checked"':'').' />';
137 $pte_vals['{$FORM_CONTPOST_TEXT}'] = _T('form_contpost');
139 if(OPTION){ //options hook
140 $pte_vals['{$FORM_OPTION_HOOK}'] = '';
143 $pte_vals += array('{$FORM_CATEGORY_FIELD}' => '<input class="inputtext" type="text" name="category" size="28" value="'.$cat.'" />',
144 '{$FORM_CATEGORY_TEXT}' => _T('form_category'),
145 '{$FORM_CATEGORY_NOTICE}' => _T('form_category_notice'));
147 if(STORAGE_LIMIT) $pte_vals['{$FORM_NOTICE_STORAGE_LIMIT}'] = _T('form_notice_storage_limit',total_size(),STORAGE_MAX);
148 $PMS->useModuleMethods('PostInfo', array(&$pte_vals['{$HOOKPOSTINFO}'])); // "PostInfo" Hook Point
150 if(USE_FLOATFORM && !$resno && $iscollapse) $pte_vals['{$FORMBOTTOM}'] = '<script type="text/javascript">hideform();</script>';
151 $dat .= $PTE->ParseBlock('POSTFORM',$pte_vals);
156 function foot(&$dat){
157 global $PTE, $PMS, $language;
158 $pte_vals = array('{$FOOTER}'=>'<!-- GazouBBS v3.0 --><!-- ふたば改0.8 --><!-- Pixmicat! --><!-- 四葉の芽改0.8 -->'."\n");
159 $PMS->useModuleMethods('Foot', array(&$pte_vals['{$FOOTER}'])); // "Foot" Hook Point
160 $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>';
161 $pte_vals['{$FOOTER}'] .= '<p>
162 <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>
164 $dat .= $PTE->ParseBlock('FOOTER',$pte_vals);
169 function auto_link_callback($matches){
170 return (strtolower($matches[3]) == "</a>") ? $matches[0] : preg_replace('/(https?|ftp|news|gopher)(:\/\/[\w\+\$\;\?\.\{\}%,!#~*\/:@&=_-]+)/u', '<a href="$1$2" rel="_blank">$1$2</a>', $matches[0]);
172 function auto_link($proto){
173 $proto = preg_replace('|<br\s*/?>|',"\n",$proto);
174 $proto = preg_replace_callback('/(>|^)([^<]+?)(<.*?>|$)/m','auto_link_callback',$proto);
175 return str_replace("\n",'<br />',$proto);
179 function quoteLight($comment){
180 return preg_replace('/(^|<br \/>)((?:>|>).*?)(?=<br \/>|$)/u', '$1<span class="unkfunc">$2</span>', $comment);
183 function quoteLight2($comment){
184 return preg_replace('/(^|<br \/>)((?:#|#).*?)(?=<br \/>|$)/u', '$1<span class="unkfunc2">$2</span>', $comment);
189 return 'http://'.$_SERVER['HTTP_HOST'].substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], PHP_SELF));
193 function anti_sakura($str){
194 return preg_match('/[\x{E000}-\x{F848}]/u', $str);
199 function error($mes, $dest=''){
201 if(is_file($dest)) unlink($dest);
202 $pte_vals = array('{$SELF2}'=>PHP_SELF2.'?'.time(), '{$MESG}'=>$mes, '{$RETURN_TEXT}'=>_T('return'), '{$BACK_TEXT}'=>_T('error_back'));
205 $dat .= $PTE->ParseBlock('ERROR',$pte_vals);
212 function CleanStr($str, $IsAdmin=false){
213 $str = trim($str); // 去除前後多餘空白
214 if(get_magic_quotes_gpc()) $str = stripslashes($str); // "\"斜線符號去除
215 // XML 1.1 Second Edition: 部分避免用字 (http://www.w3.org/TR/2006/REC-xml11-20060816/#charsets)
216 $str = preg_replace('/([\x1-\x8\xB-\xC\xE-\x1F\x7F-\x84\x86-\x9F\x{FDD0}-\x{FDDF}])/u', '', htmlspecialchars($str));
218 if($IsAdmin && CAP_ISHTML){ // 管理員開啟HTML
219 $str = preg_replace('/<(.*?)>/', '<$1>', $str); // 如果有<...>則轉回<...>成為正常標籤
224 /* 適用UTF-8環境的擬substr,取出特定數目字元
225 原出處:Sea Otter @ 2005.05.10
226 http://www.meyu.net/star/viewthread.php?tid=267&fpage=10 */
227 function str_cut($str, $maxlen=20){
228 $i = $l = 0; $len = strlen($str); $f = true; $return_str = $str;
230 $chars = ord($str{$i});
231 if($chars < 0x80){ $l++; $i++; }
232 elseif($chars < 0xe0){ $l++; $i += 2; }
233 elseif($chars < 0xf0){ $l += 2; $i += 3; }
234 elseif($chars < 0xf8){ $l++; $i += 4; }
235 elseif($chars < 0xfc){ $l++; $i += 5; }
236 elseif($chars < 0xfe){ $l++; $i += 6; }
237 if(($l >= $maxlen) && $f){
238 $return_str = substr($str, 0, $i);
241 if(($l > $maxlen) && ($i <= $len)){
242 $return_str = $return_str.'…';
249 /* 檢查瀏覽器和伺服器是否支援gzip壓縮方式 */
250 function CheckSupportGZip(){
251 $HTTP_ACCEPT_ENCODING = isset($_SERVER['HTTP_ACCEPT_ENCODING']) ? $_SERVER['HTTP_ACCEPT_ENCODING'] : '';
252 if(headers_sent() || connection_aborted()) return 0; // 已送出資料,取消
253 if(!(function_exists('gzencode') && function_exists('ob_start') && function_exists('ob_get_clean'))) return 0; // 伺服器相關的套件或函式無法使用,取消
254 if(strpos($HTTP_ACCEPT_ENCODING, 'gzip')!==false) return 'gzip';
258 /* 封鎖 IP / Hostname / DNSBL 綜合性檢查 */
259 function BanIPHostDNSBLCheck($IP, $HOST, &$baninfo){
260 if(!BAN_CHECK) return false; // Disabled
261 global $BANPATTERN, $DNSBLservers, $DNSBLWHlist;
264 $HOST = strtolower($HOST);
265 $checkTwice = ($IP != $HOST); // 是否需檢查第二次
267 foreach($BANPATTERN as $pattern){
268 $slash = substr_count($pattern, '/');
269 if($slash==2){ // RegExp
271 }elseif($slash==1){ // CIDR Notation
272 if(matchCIDR($IP, $pattern)){ $IsBanned = true; break; }
274 }elseif(strpos($pattern, '*')!==false || strpos($pattern, '?')!==false){ // Wildcard
275 $pattern = '/^'.str_replace(array('.', '*', '?'), array('\.', '.*', '.?'), $pattern).'$/i';
277 if($IP==$pattern || ($checkTwice && $HOST==strtolower($pattern))){ $IsBanned = true; break; }
280 if(preg_match($pattern, $HOST) || ($checkTwice && preg_match($pattern, $IP))){ $IsBanned = true; break; }
282 if($IsBanned){ $baninfo = _T('ip_banned'); return true; }
284 // DNS-based Blackhole List(DNSBL) 黑名單
285 if(!$DNSBLservers[0]) return false; // Skip check
286 if(array_search($IP, $DNSBLWHlist)!==false) return false; // IP位置在白名單內
287 $rev = implode('.', array_reverse(explode('.', $IP)));
288 $lastPoint = count($DNSBLservers) - 1; if($DNSBLservers[0] < $lastPoint) $lastPoint = $DNSBLservers[0];
290 for($i = 1; $i <= $lastPoint; $i++){
291 $query = $rev.'.'.$DNSBLservers[$i].'.'; // FQDN
292 $result = gethostbyname($query);
293 if($result && ($result != $query)){ $isListed = $DNSBLservers[$i]; break; }
295 if($isListed){ $baninfo = _T('ip_dnsbl_banned',$isListed); return true; }
298 function matchCIDR($addr, $cidr) {
299 list($ip, $mask) = explode('/', $cidr);
300 return (ip2long($addr) >> (32 - $mask) == ip2long($ip.str_repeat('.0', 3 - substr_count($ip, '.'))) >> (32 - $mask));
304 function adminAuthenticate($mode){
306 $loginkey = md5($_SERVER['HTTP_USER_AGENT'].ADMIN_PASS.$_SERVER['REMOTE_ADDR']);
309 if(isset($_SESSION['pmcLogin'])) unset($_SESSION['pmcLogin']);
312 $_SESSION['pmcLogin'] = $loginkey;
315 if(isset($_SESSION['pmcLogin']) && $_SESSION['pmcLogin']==$loginkey){
316 session_regenerate_id(true); // 更換 Session id key 避免 Hijacking
324 /* 取得 (Transparent) Proxy 提供之 IP 參數 */
325 function getREMOTE_ADDR(){
326 // 同時有 VIA 和 FORWARDED_FOR 較可能為 Proxy
327 if(isset($_SERVER['HTTP_VIA']) && isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
328 $tmp = preg_split('/[ ,]+/', $_SERVER['HTTP_X_FORWARDED_FOR']);
329 // 防止 Squid "unknown" 問題,此種情況直接使用 REMOTE_ADDR
330 return ($tmp[0] != 'unknown' ? $tmp[0] : $_SERVER['REMOTE_ADDR']);
332 return $_SERVER['REMOTE_ADDR'];
336 function format_js_var($var_name){
337 return("'".$var_name."'");
341 # Written by Coda, functionified by Foone/Popcorn Mariachi#!9i78bPeIxI
342 # This code is in the public domain
343 # identify_apng returns:
344 # true if the file is an APNG
345 # false if it is any other sort of file (it is not checked for PNG validity)
346 # takes on argument, a filename.
348 function identify_apng($filename){
350 $img_bytes = file_get_contents($filename);
352 if(strpos(substr($img_bytes, 0, strpos($img_bytes, 'IDAT')), 'acTL') !== false){
353 return $apng = TRUE; // APNG
356 return $apng = FALSE; // not APNG
359 /* total amount of ommited posts/images */
360 function _res($posts, $images=0){
361 $omitp = ($posts) ? sp(_T('notice_omitted_posts'), $posts) : false;
362 $omiti = ($images) ? sp(_T('notice_omitted_images'), $images) : false;
363 return($omitp.$omiti);
365 /* plural strings for ommited post messages */
366 function sp($string, $value, $shownull = false){
367 // Determine whether to show string for zero values
368 if(!$value && $shownull || $value) $show = true;
369 elseif(!$value && !$shownull) $show = false;
370 else $show = $shownull;
372 if($show) $string = str_replace('[#]', number_format($value), $string);
375 // Separate words from plural forms
376 ereg('(.*)(\[)(.*)(\])(.*)', $string, $regs);
377 $plu_word_s = $regs[1];
378 $plu_bits = $regs[3];
379 $plu_word_e = $regs[5];
381 if(strstr($plu_bits, '|')){
382 // To the left of the | is the single form; to the right, the plural form
383 ereg('(.*)(\|)(.*)', $plu_bits, $regs);
387 // [|s] will work for words that should end in "s", but this bit handles [s]
392 // Spit it out, Smith
393 $plu_bit_d = ($value == -1 || $value == 1)?$single:$plural;
394 $plu_word = $plu_word_s.$plu_bit_d.$plu_word_e;
396 if($plu_word) return($plu_word); else return($string);
399 /* comment too long function */
400 // truncate $str to $max_lines lines and return $str and $abbr
401 // where $abbr = whether or not $str was actually truncated
402 function abbreviate($str, $max_lines){
403 if(!defined('MAX_LINES')){
404 if(defined('BR_CHECK')) define('MAX_LINES', BR_CHECK);
405 else define('MAX_LINES', 24);
407 $max_lines = MAX_LINES;
409 $lines = explode("<br />", $str);
410 if(count($lines) > $max_lines){
412 $lines = array_slice($lines, 0, $max_lines);
413 $str = implode("<br />", $lines);
415 //close spans after abbreviating
416 //XXX will not work with more html - use abbreviate_html from shiichan
417 $str .= str_repeat("</span>", substr_count($str, "<span") - substr_count($str, "</span"));
418 return array($str, $abbr);