global.func.php 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864
  1. <?php
  2. /**
  3. * global.func.php 公共函数库
  4. *
  5. * @copyright (C) 2005-2010 PHPCMS
  6. * @license http://www.phpcms.cn/license/
  7. * @lastmodify 2010-6-1
  8. */
  9. /**
  10. * 返回经addslashes处理过的字符串或数组
  11. * @param $string 需要处理的字符串或数组
  12. * @return mixed
  13. */
  14. function new_addslashes($string){
  15. if(!is_array($string)) return addslashes($string);
  16. foreach($string as $key => $val) $string[$key] = new_addslashes($val);
  17. return $string;
  18. }
  19. /**
  20. * 返回经stripslashes处理过的字符串或数组
  21. * @param $string 需要处理的字符串或数组
  22. * @return mixed
  23. */
  24. function new_stripslashes($string) {
  25. if(!is_array($string)) return stripslashes($string);
  26. foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
  27. return $string;
  28. }
  29. /**
  30. * 返回经htmlspecialchars处理过的字符串或数组
  31. * @param $obj 需要处理的字符串或数组
  32. * @return mixed
  33. */
  34. function new_html_special_chars($string) {
  35. $encoding = 'utf-8';
  36. if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
  37. if(!is_array($string)) return htmlspecialchars($string,ENT_QUOTES,$encoding);
  38. foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
  39. return $string;
  40. }
  41. function new_html_entity_decode($string) {
  42. $encoding = 'utf-8';
  43. if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
  44. return html_entity_decode($string,ENT_QUOTES,$encoding);
  45. }
  46. function new_htmlentities($string) {
  47. $encoding = 'utf-8';
  48. if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
  49. return htmlentities($string,ENT_QUOTES,$encoding);
  50. }
  51. /**
  52. * 安全过滤函数
  53. *
  54. * @param $string
  55. * @return string
  56. */
  57. function safe_replace($string) {
  58. $string = str_replace('%20','',$string);
  59. $string = str_replace('%27','',$string);
  60. $string = str_replace('%2527','',$string);
  61. $string = str_replace('*','',$string);
  62. $string = str_replace('"','&quot;',$string);
  63. $string = str_replace("'",'',$string);
  64. $string = str_replace('"','',$string);
  65. $string = str_replace(';','',$string);
  66. $string = str_replace('<','&lt;',$string);
  67. $string = str_replace('>','&gt;',$string);
  68. $string = str_replace("{",'',$string);
  69. $string = str_replace('}','',$string);
  70. $string = str_replace('\\','',$string);
  71. return $string;
  72. }
  73. /**
  74. * xss过滤函数
  75. *
  76. * @param $string
  77. * @return string
  78. */
  79. function remove_xss($string) {
  80. $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);
  81. $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  82. $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
  83. $parm = array_merge($parm1, $parm2);
  84. for ($i = 0; $i < sizeof($parm); $i++) {
  85. $pattern = '/';
  86. for ($j = 0; $j < strlen($parm[$i]); $j++) {
  87. if ($j > 0) {
  88. $pattern .= '(';
  89. $pattern .= '(&#[x|X]0([9][a][b]);?)?';
  90. $pattern .= '|(&#0([9][10][13]);?)?';
  91. $pattern .= ')?';
  92. }
  93. $pattern .= $parm[$i][$j];
  94. }
  95. $pattern .= '/i';
  96. $string = preg_replace($pattern, ' ', $string);
  97. }
  98. return $string;
  99. }
  100. /**
  101. * 过滤ASCII码从0-28的控制字符
  102. * @return String
  103. */
  104. function trim_unsafe_control_chars($str) {
  105. $rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
  106. return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
  107. }
  108. /**
  109. * 格式化文本域内容
  110. *
  111. * @param $string 文本域内容
  112. * @return string
  113. */
  114. function trim_textarea($string) {
  115. $string = nl2br ( str_replace ( ' ', '&nbsp;', $string ) );
  116. return $string;
  117. }
  118. /**
  119. * 将文本格式成适合js输出的字符串
  120. * @param string $string 需要处理的字符串
  121. * @param intval $isjs 是否执行字符串格式化,默认为执行
  122. * @return string 处理后的字符串
  123. */
  124. function format_js($string, $isjs = 1) {
  125. $string = addslashes(str_replace(array("\r", "\n", "\t"), array('', '', ''), $string));
  126. return $isjs ? 'document.write("'.$string.'");' : $string;
  127. }
  128. /**
  129. * 转义 javascript 代码标记
  130. *
  131. * @param $str
  132. * @return mixed
  133. */
  134. function trim_script($str) {
  135. if(is_array($str)){
  136. foreach ($str as $key => $val){
  137. $str[$key] = trim_script($val);
  138. }
  139. }else{
  140. $str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str );
  141. $str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str );
  142. $str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str );
  143. $str = str_replace ( 'javascript:', 'javascript:', $str );
  144. }
  145. return $str;
  146. }
  147. /**
  148. * 获取当前页面完整URL地址
  149. */
  150. function get_url() {
  151. $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
  152. $php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
  153. $path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
  154. $relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
  155. return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
  156. }
  157. /**
  158. * 字符截取 支持UTF8/GBK
  159. * @param $string
  160. * @param $length
  161. * @param $dot
  162. */
  163. function str_cut($string, $length, $dot = '...') {
  164. $strlen = strlen($string);
  165. if($strlen <= $length) return $string;
  166. $string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
  167. $strcut = '';
  168. if(strtolower(CHARSET) == 'utf-8') {
  169. $length = intval($length-strlen($dot)-$length/3);
  170. $n = $tn = $noc = 0;
  171. while($n < strlen($string)) {
  172. $t = ord($string[$n]);
  173. if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  174. $tn = 1; $n++; $noc++;
  175. } elseif(194 <= $t && $t <= 223) {
  176. $tn = 2; $n += 2; $noc += 2;
  177. } elseif(224 <= $t && $t <= 239) {
  178. $tn = 3; $n += 3; $noc += 2;
  179. } elseif(240 <= $t && $t <= 247) {
  180. $tn = 4; $n += 4; $noc += 2;
  181. } elseif(248 <= $t && $t <= 251) {
  182. $tn = 5; $n += 5; $noc += 2;
  183. } elseif($t == 252 || $t == 253) {
  184. $tn = 6; $n += 6; $noc += 2;
  185. } else {
  186. $n++;
  187. }
  188. if($noc >= $length) {
  189. break;
  190. }
  191. }
  192. if($noc > $length) {
  193. $n -= $tn;
  194. }
  195. $strcut = substr($string, 0, $n);
  196. $strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
  197. } else {
  198. $dotlen = strlen($dot);
  199. $maxi = $length - $dotlen - 1;
  200. $current_str = '';
  201. $search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
  202. $replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
  203. $search_flip = array_flip($search_arr);
  204. for ($i = 0; $i < $maxi; $i++) {
  205. $current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
  206. if (in_array($current_str, $search_arr)) {
  207. $key = $search_flip[$current_str];
  208. $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
  209. }
  210. $strcut .= $current_str;
  211. }
  212. }
  213. return $strcut.$dot;
  214. }
  215. /**
  216. * 获取请求ip
  217. *
  218. * @return ip地址
  219. */
  220. function ip() {
  221. if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
  222. $ip = getenv('HTTP_CLIENT_IP');
  223. } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
  224. $ip = getenv('HTTP_X_FORWARDED_FOR');
  225. } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
  226. $ip = getenv('REMOTE_ADDR');
  227. } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
  228. $ip = $_SERVER['REMOTE_ADDR'];
  229. }
  230. return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
  231. }
  232. function get_cost_time() {
  233. $microtime = microtime ( TRUE );
  234. return $microtime - SYS_START_TIME;
  235. }
  236. /**
  237. * 程序执行时间
  238. *
  239. * @return int 单位ms
  240. */
  241. function execute_time() {
  242. $stime = explode ( ' ', SYS_START_TIME );
  243. $etime = explode ( ' ', microtime () );
  244. return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 );
  245. }
  246. /**
  247. * 产生随机字符串
  248. *
  249. * @param int $length 输出长度
  250. * @param string $chars 可选的 ,默认为 0123456789
  251. * @return string 字符串
  252. */
  253. function random($length, $chars = '0123456789') {
  254. $hash = '';
  255. $max = strlen($chars) - 1;
  256. for($i = 0; $i < $length; $i++) {
  257. $hash .= $chars[mt_rand(0, $max)];
  258. }
  259. return $hash;
  260. }
  261. /**
  262. * 将字符串转换为数组
  263. *
  264. * @param string $data 字符串
  265. * @return array 返回数组格式,如果,data为空,则返回空数组
  266. */
  267. function string2array($data) {
  268. $data = trim($data);
  269. if($data == '') return array();
  270. if(strpos($data, 'array')===0){
  271. @eval("\$array = $data;");
  272. }else{
  273. if(strpos($data, '{\\')===0) $data = stripslashes($data);
  274. $array=json_decode($data,true);
  275. if(strtolower(CHARSET)=='gbk'){
  276. $array = mult_iconv("UTF-8", "GBK//IGNORE", $array);
  277. }
  278. }
  279. return $array;
  280. }
  281. /**
  282. * 将数组转换为字符串
  283. *
  284. * @param array $data 数组
  285. * @param bool $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
  286. * @return string 返回字符串,如果,data为空,则返回空
  287. */
  288. function array2string($data, $isformdata = 1) {
  289. if($data == '' || empty($data)) return '';
  290. if($isformdata) $data = new_stripslashes($data);
  291. if(strtolower(CHARSET)=='gbk'){
  292. $data = mult_iconv("GBK", "UTF-8", $data);
  293. }
  294. if (version_compare(PHP_VERSION,'5.3.0','<')){
  295. return addslashes(json_encode($data));
  296. }else{
  297. return addslashes(json_encode($data,JSON_FORCE_OBJECT));
  298. }
  299. }
  300. /**
  301. * 数组转码
  302. *
  303. */
  304. function mult_iconv($in_charset,$out_charset,$data){
  305. if(substr($out_charset,-8)=='//IGNORE'){
  306. $out_charset=substr($out_charset,0,-8);
  307. }
  308. if(is_array($data)){
  309. foreach($data as $key => $value){
  310. if(is_array($value)){
  311. $key=iconv($in_charset,$out_charset.'//IGNORE',$key);
  312. $rtn[$key]=mult_iconv($in_charset,$out_charset,$value);
  313. }elseif(is_string($key) || is_string($value)){
  314. if(is_string($key)){
  315. $key=iconv($in_charset,$out_charset.'//IGNORE',$key);
  316. }
  317. if(is_string($value)){
  318. $value=iconv($in_charset,$out_charset.'//IGNORE',$value);
  319. }
  320. $rtn[$key]=$value;
  321. }else{
  322. $rtn[$key]=$value;
  323. }
  324. }
  325. }elseif(is_string($data)){
  326. $rtn=iconv($in_charset,$out_charset.'//IGNORE',$data);
  327. }else{
  328. $rtn=$data;
  329. }
  330. return $rtn;
  331. }
  332. /**
  333. * 转换字节数为其他单位
  334. *
  335. *
  336. * @param string $filesize 字节大小
  337. * @return string 返回大小
  338. */
  339. function sizecount($filesize) {
  340. if ($filesize >= 1073741824) {
  341. $filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
  342. } elseif ($filesize >= 1048576) {
  343. $filesize = round($filesize / 1048576 * 100) / 100 .' MB';
  344. } elseif($filesize >= 1024) {
  345. $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
  346. } else {
  347. $filesize = $filesize.' Bytes';
  348. }
  349. return $filesize;
  350. }
  351. /**
  352. * 字符串加密、解密函数
  353. *
  354. *
  355. * @param string $txt 字符串
  356. * @param string $operation ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE,
  357. * @param string $key 密钥:数字、字母、下划线
  358. * @param string $expiry 过期时间
  359. * @return string
  360. */
  361. function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
  362. $ckey_length = 4;
  363. $key = md5($key != '' ? $key : pc_base::load_config('system', 'auth_key'));
  364. $keya = md5(substr($key, 0, 16));
  365. $keyb = md5(substr($key, 16, 16));
  366. $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
  367. $cryptkey = $keya.md5($keya.$keyc);
  368. $key_length = strlen($cryptkey);
  369. $string = $operation == 'DECODE' ? base64_decode(strtr(substr($string, $ckey_length), '-_', '+/')) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
  370. $string_length = strlen($string);
  371. $result = '';
  372. $box = range(0, 255);
  373. $rndkey = array();
  374. for($i = 0; $i <= 255; $i++) {
  375. $rndkey[$i] = ord($cryptkey[$i % $key_length]);
  376. }
  377. for($j = $i = 0; $i < 256; $i++) {
  378. $j = ($j + $box[$i] + $rndkey[$i]) % 256;
  379. $tmp = $box[$i];
  380. $box[$i] = $box[$j];
  381. $box[$j] = $tmp;
  382. }
  383. for($a = $j = $i = 0; $i < $string_length; $i++) {
  384. $a = ($a + 1) % 256;
  385. $j = ($j + $box[$a]) % 256;
  386. $tmp = $box[$a];
  387. $box[$a] = $box[$j];
  388. $box[$j] = $tmp;
  389. $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
  390. }
  391. if($operation == 'DECODE') {
  392. if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
  393. return substr($result, 26);
  394. } else {
  395. return '';
  396. }
  397. } else {
  398. return $keyc.rtrim(strtr(base64_encode($result), '+/', '-_'), '=');
  399. }
  400. }
  401. /**
  402. * 语言文件处理
  403. *
  404. * @param string $language 标示符
  405. * @param array $pars 转义的数组,二维数组 ,'key1'=>'value1','key2'=>'value2',
  406. * @param string $modules 多个模块之间用半角逗号隔开,如:member,guestbook
  407. * @return string 语言字符
  408. */
  409. function L($language = 'no_language',$pars = array(), $modules = '') {
  410. static $LANG = array();
  411. static $LANG_MODULES = array();
  412. static $lang = '';
  413. if(defined('IN_ADMIN')) {
  414. $lang = SYS_STYLE ? SYS_STYLE : 'zh-cn';
  415. } else {
  416. $lang = pc_base::load_config('system','lang');
  417. }
  418. if(!$LANG) {
  419. require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system.lang.php';
  420. if(defined('IN_ADMIN')) require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system_menu.lang.php';
  421. if(file_exists(PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php')) require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php';
  422. }
  423. if(!empty($modules)) {
  424. $modules = explode(',',$modules);
  425. foreach($modules AS $m) {
  426. if(!isset($LANG_MODULES[$m])) require_once PC_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.$m.'.lang.php';
  427. }
  428. }
  429. if(!array_key_exists($language,$LANG)) {
  430. return $language;
  431. } else {
  432. $language = $LANG[$language];
  433. if($pars) {
  434. foreach($pars AS $_k=>$_v) {
  435. $language = str_replace('{'.$_k.'}',$_v,$language);
  436. }
  437. }
  438. return $language;
  439. }
  440. }
  441. /**
  442. * 模板调用
  443. *
  444. * @param $module
  445. * @param $template
  446. * @param $istag
  447. * @return unknown_type
  448. */
  449. function template($module = 'content', $template = 'index', $style = '') {
  450. if(strpos($module, 'plugin/')!== false) {
  451. $plugin = str_replace('plugin/', '', $module);
  452. return p_template($plugin, $template,$style);
  453. }
  454. $module = str_replace('/', DIRECTORY_SEPARATOR, $module);
  455. if(!empty($style) && preg_match('/([a-z0-9\-_]+)/is',$style)) {
  456. } elseif (empty($style) && !defined('STYLE')) {
  457. if(defined('SITEID')) {
  458. $siteid = SITEID;
  459. } else {
  460. $siteid = param::get_cookie('siteid');
  461. }
  462. if (!$siteid) $siteid = 1;
  463. $sitelist = getcache('sitelist','commons');
  464. if(!empty($siteid)) {
  465. $style = $sitelist[$siteid]['default_style'];
  466. }
  467. } elseif (empty($style) && defined('STYLE')) {
  468. $style = STYLE;
  469. } else {
  470. $style = 'default';
  471. }
  472. if(!$style) $style = 'default';
  473. $template_cache = pc_base::load_sys_class('template_cache');
  474. $compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
  475. if(file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
  476. if(!file_exists($compiledtplfile) || (@filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > @filemtime($compiledtplfile))) {
  477. $template_cache->template_compile($module, $template, $style);
  478. }
  479. } else {
  480. $compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
  481. if(!file_exists($compiledtplfile) || (file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile))) {
  482. $template_cache->template_compile($module, $template, 'default');
  483. } elseif (!file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
  484. showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html');
  485. }
  486. }
  487. return $compiledtplfile;
  488. }
  489. /**
  490. * 输出自定义错误
  491. *
  492. * @param $errno 错误号
  493. * @param $errstr 错误描述
  494. * @param $errfile 报错文件地址
  495. * @param $errline 错误行号
  496. * @return string 错误提示
  497. */
  498. function my_error_handler($errno, $errstr, $errfile, $errline) {
  499. if($errno==8) return '';
  500. $errfile = str_replace(PHPCMS_PATH,'',$errfile);
  501. if(pc_base::load_config('system','errorlog')) {
  502. error_log('<?php exit;?>'.date('m-d H:i:s',SYS_TIME).' | '.$errno.' | '.str_pad($errstr,30).' | '.$errfile.' | '.$errline."\r\n", 3, CACHE_PATH.'error_log.php');
  503. } else {
  504. $str = '<div style="font-size:12px;text-align:left; border-bottom:1px solid #9cc9e0; border-right:1px solid #9cc9e0;padding:1px 4px;color:#000000;font-family:Arial, Helvetica,sans-serif;"><span>errorno:' . $errno . ',str:' . $errstr . ',file:<font color="blue">' . $errfile . '</font>,line' . $errline .'<br /><a href="http://faq.phpcms.cn/?type=file&errno='.$errno.'&errstr='.urlencode($errstr).'&errfile='.urlencode($errfile).'&errline='.$errline.'" target="_blank" style="color:red">Need Help?</a></span></div>';
  505. echo $str;
  506. }
  507. }
  508. /**
  509. * 提示信息页面跳转,跳转地址如果传入数组,页面会提示多个地址供用户选择,默认跳转地址为数组的第一个值,时间为5秒。
  510. * showmessage('登录成功', array('默认跳转地址'=>'http://www.phpcms.cn'));
  511. * @param string $msg 提示信息
  512. * @param mixed(string/array) $url_forward 跳转地址
  513. * @param int $ms 跳转等待时间
  514. */
  515. function showmessage($msg, $url_forward = 'goback', $ms = 1250, $dialog = '', $returnjs = '') {
  516. if(defined('IN_ADMIN')) {
  517. include(admin::admin_tpl('showmessage', 'admin'));
  518. } else {
  519. include(template('content', 'message'));
  520. }
  521. exit;
  522. }
  523. /**
  524. * 查询字符是否存在于某字符串
  525. *
  526. * @param $haystack 字符串
  527. * @param $needle 要查找的字符
  528. * @return bool
  529. */
  530. function str_exists($haystack, $needle)
  531. {
  532. return !(strpos($haystack, $needle) === FALSE);
  533. }
  534. /**
  535. * 取得文件扩展
  536. *
  537. * @param $filename 文件名
  538. * @return 扩展名
  539. */
  540. function fileext($filename) {
  541. return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
  542. }
  543. /**
  544. * 加载模板标签缓存
  545. * @param string $name 缓存名
  546. * @param integer $times 缓存时间
  547. */
  548. function tpl_cache($name,$times = 0) {
  549. $filepath = 'tpl_data';
  550. $info = getcacheinfo($name, $filepath);
  551. if (SYS_TIME - $info['filemtime'] >= $times) {
  552. return false;
  553. } else {
  554. return getcache($name,$filepath);
  555. }
  556. }
  557. /**
  558. * 写入缓存,默认为文件缓存,不加载缓存配置。
  559. * @param $name 缓存名称
  560. * @param $data 缓存数据
  561. * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
  562. * @param $type 缓存类型[file,memcache,apc]
  563. * @param $config 配置名称
  564. * @param $timeout 过期时间
  565. */
  566. function setcache($name, $data, $filepath='', $type='file', $config='', $timeout=0) {
  567. if(!preg_match("/^[a-zA-Z0-9_-]+$/", $name)) return false;
  568. if($filepath!="" && !preg_match("/^[a-zA-Z0-9_-]+$/", $filepath)) return false;
  569. pc_base::load_sys_class('cache_factory','',0);
  570. if($config) {
  571. $cacheconfig = pc_base::load_config('cache');
  572. $cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
  573. } else {
  574. $cache = cache_factory::get_instance()->get_cache($type);
  575. }
  576. return $cache->set($name, $data, $timeout, '', $filepath);
  577. }
  578. /**
  579. * 读取缓存,默认为文件缓存,不加载缓存配置。
  580. * @param string $name 缓存名称
  581. * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
  582. * @param string $config 配置名称
  583. */
  584. function getcache($name, $filepath='', $type='file', $config='') {
  585. if(!preg_match("/^[a-zA-Z0-9_-]+$/", $name)) return false;
  586. if($filepath!="" && !preg_match("/^[a-zA-Z0-9_-]+$/", $filepath)) return false;
  587. pc_base::load_sys_class('cache_factory','',0);
  588. if($config) {
  589. $cacheconfig = pc_base::load_config('cache');
  590. $cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
  591. } else {
  592. $cache = cache_factory::get_instance()->get_cache($type);
  593. }
  594. return $cache->get($name, '', '', $filepath);
  595. }
  596. /**
  597. * 删除缓存,默认为文件缓存,不加载缓存配置。
  598. * @param $name 缓存名称
  599. * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
  600. * @param $type 缓存类型[file,memcache,apc]
  601. * @param $config 配置名称
  602. */
  603. function delcache($name, $filepath='', $type='file', $config='') {
  604. if(!preg_match("/^[a-zA-Z0-9_-]+$/", $name)) return false;
  605. if($filepath!="" && !preg_match("/^[a-zA-Z0-9_-]+$/", $filepath)) return false;
  606. pc_base::load_sys_class('cache_factory','',0);
  607. if($config) {
  608. $cacheconfig = pc_base::load_config('cache');
  609. $cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
  610. } else {
  611. $cache = cache_factory::get_instance()->get_cache($type);
  612. }
  613. return $cache->delete($name, '', '', $filepath);
  614. }
  615. /**
  616. * 读取缓存,默认为文件缓存,不加载缓存配置。
  617. * @param string $name 缓存名称
  618. * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
  619. * @param string $config 配置名称
  620. */
  621. function getcacheinfo($name, $filepath='', $type='file', $config='') {
  622. if(!preg_match("/^[a-zA-Z0-9_-]+$/", $name)) return false;
  623. if($filepath!="" && !preg_match("/^[a-zA-Z0-9_-]+$/", $filepath)) return false;
  624. pc_base::load_sys_class('cache_factory');
  625. if($config) {
  626. $cacheconfig = pc_base::load_config('cache');
  627. $cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
  628. } else {
  629. $cache = cache_factory::get_instance()->get_cache($type);
  630. }
  631. return $cache->cacheinfo($name, '', '', $filepath);
  632. }
  633. /**
  634. * 生成sql语句,如果传入$in_cloumn 生成格式为 IN('a', 'b', 'c')
  635. * @param $data 条件数组或者字符串
  636. * @param $front 连接符
  637. * @param $in_column 字段名称
  638. * @return string
  639. */
  640. function to_sqls($data, $front = ' AND ', $in_column = false) {
  641. if($in_column && is_array($data)) {
  642. $ids = '\''.implode('\',\'', $data).'\'';
  643. $sql = "$in_column IN ($ids)";
  644. return $sql;
  645. } else {
  646. if ($front == '') {
  647. $front = ' AND ';
  648. }
  649. if(is_array($data) && count($data) > 0) {
  650. $sql = '';
  651. foreach ($data as $key => $val) {
  652. $sql .= $sql ? " $front `$key` = '$val' " : " `$key` = '$val' ";
  653. }
  654. return $sql;
  655. } else {
  656. return $data;
  657. }
  658. }
  659. }
  660. /**
  661. * 分页函数
  662. *
  663. * @param $num 信息总数
  664. * @param $curr_page 当前分页
  665. * @param $perpage 每页显示数
  666. * @param $urlrule URL规则
  667. * @param $array 需要传递的数组,用于增加额外的方法
  668. * @return 分页
  669. */
  670. function pages($num, $curr_page, $perpage = 20, $urlrule = '', $array = array(),$setpages = 10) {
  671. if(defined('URLRULE') && $urlrule == '') {
  672. $urlrule = URLRULE;
  673. $array = $GLOBALS['URL_ARRAY'];
  674. } elseif($urlrule == '') {
  675. $urlrule = url_par('page={$page}');
  676. }
  677. $multipage = '';
  678. if($num > $perpage) {
  679. $page = $setpages+1;
  680. $offset = ceil($setpages/2-1);
  681. $pages = ceil($num / $perpage);
  682. if (defined('IN_ADMIN') && !defined('PAGES')) define('PAGES', $pages);
  683. $from = $curr_page - $offset;
  684. $to = $curr_page + $offset;
  685. $more = 0;
  686. if($page >= $pages) {
  687. $from = 2;
  688. $to = $pages-1;
  689. } else {
  690. if($from <= 1) {
  691. $to = $page-1;
  692. $from = 2;
  693. } elseif($to >= $pages) {
  694. $from = $pages-($page-2);
  695. $to = $pages-1;
  696. }
  697. $more = 1;
  698. }
  699. $multipage .= '<a class="a1">'.$num.L('page_item').'</a>';
  700. if($curr_page>0) {
  701. $multipage .= ' <a href="'.pageurl($urlrule, $curr_page-1, $array).'" class="a1">'.L('previous').'</a>';
  702. if($curr_page==1) {
  703. $multipage .= ' <span>1</span>';
  704. } elseif($curr_page>6 && $more) {
  705. $multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>..';
  706. } else {
  707. $multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>';
  708. }
  709. }
  710. for($i = $from; $i <= $to; $i++) {
  711. if($i != $curr_page) {
  712. $multipage .= ' <a href="'.pageurl($urlrule, $i, $array).'">'.$i.'</a>';
  713. } else {
  714. $multipage .= ' <span>'.$i.'</span>';
  715. }
  716. }
  717. if($curr_page<$pages) {
  718. if($curr_page<$pages-5 && $more) {
  719. $multipage .= ' ..<a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
  720. } else {
  721. $multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
  722. }
  723. } elseif($curr_page==$pages) {
  724. $multipage .= ' <span>'.$pages.'</span> <a href="'.pageurl($urlrule, $curr_page, $array).'" class="a1">'.L('next').'</a>';
  725. } else {
  726. $multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
  727. }
  728. }
  729. return $multipage;
  730. }
  731. /**
  732. * 分页函数
  733. *
  734. * @param $num 信息总数
  735. * @param $curr_page 当前分页
  736. * @param $perpage 每页显示数
  737. * @param $urlrule URL规则
  738. * @param $array 需要传递的数组,用于增加额外的方法
  739. * @return 分页
  740. */
  741. function pc_pages($num, $curr_page, $perpage = 20, $urlrule = '', $array = array(),$setpages = 10) {
  742. if(defined('URLRULE') && $urlrule == '') {
  743. $urlrule = URLRULE;
  744. $array = $GLOBALS['URL_ARRAY'];
  745. } elseif($urlrule == '') {
  746. $urlrule = url_par('page={$page}');
  747. }
  748. $multipage = '';
  749. if($num > $perpage) {
  750. $page = $setpages+1;
  751. $offset = ceil($setpages/2-1);
  752. $pages = ceil($num / $perpage);
  753. if (defined('IN_ADMIN') && !defined('PAGES')) define('PAGES', $pages);
  754. $from = $curr_page - $offset;
  755. $to = $curr_page + $offset;
  756. $more = 0;
  757. if($page >= $pages) {
  758. $from = 2;
  759. $to = $pages-1;
  760. } else {
  761. if($from <= 1) {
  762. $to = $page-1;
  763. $from = 2;
  764. } elseif($to >= $pages) {
  765. $from = $pages-($page-2);
  766. $to = $pages-1;
  767. }
  768. $more = 1;
  769. }
  770. // $multipage .= '<a class="a1">'.$num.L('page_item').'</a>';
  771. if($curr_page>0) {
  772. $multipage .= ' <a href="'.pageurl($urlrule, $curr_page-1, $array).'" class="a1">'.'&lt;'.'</a>';
  773. if($curr_page==1) {
  774. $multipage .= ' <a class="a1">1</a>';
  775. } elseif($curr_page>6 && $more) {
  776. $multipage .= ' <a class="a1" href="'.pageurl($urlrule, 1, $array).'">1</a>..';
  777. } else {
  778. $multipage .= ' <a class="a1" href="'.pageurl($urlrule, 1, $array).'">1</a>';
  779. }
  780. }
  781. for($i = $from; $i <= $to; $i++) {
  782. if($i != $curr_page) {
  783. $multipage .= ' <a class="a1" href="'.pageurl($urlrule, $i, $array).'">'.$i.'</a>';
  784. } else {
  785. $multipage .= ' <a class="a1 activegg1">'.$i.'</a>';
  786. }
  787. }
  788. if($curr_page<$pages) {
  789. if($curr_page<$pages-5 && $more) {
  790. $multipage .= ' ..<a class="a1" href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.'&gt;'.'</a>';
  791. } else {
  792. $multipage .= ' <a class="a1" href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.'&gt;'.'</a>';
  793. }
  794. } elseif($curr_page==$pages) {
  795. $multipage .= ' <a class="a1">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page, $array).'" class="a1">'.'&gt;'.'</a>';
  796. } else {
  797. $multipage .= ' <a class="a1" href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.'&gt;'.'</a>';
  798. }
  799. }
  800. return $multipage;
  801. }
  802. /**
  803. * 返回分页路径
  804. *
  805. * @param $urlrule 分页规则
  806. * @param $page 当前页
  807. * @param $array 需要传递的数组,用于增加额外的方法
  808. * @return 完整的URL路径
  809. */
  810. function pageurl($urlrule, $page, $array = array()) {
  811. if(strpos($urlrule, '~')) {
  812. $urlrules = explode('~', $urlrule);
  813. $urlrule = $page < 2 ? $urlrules[0] : $urlrules[1];
  814. }
  815. $findme = array('{$page}');
  816. $replaceme = array($page);
  817. if (is_array($array)) foreach ($array as $k=>$v) {
  818. $findme[] = '{$'.$k.'}';
  819. $replaceme[] = $v;
  820. }
  821. $url = str_replace($findme, $replaceme, $urlrule);
  822. $url = str_replace(array('http://','//','~'), array('~','/','http://'), $url);
  823. return $url;
  824. }
  825. /**
  826. * URL路径解析,pages 函数的辅助函数
  827. *
  828. * @param $par 传入需要解析的变量 默认为,page={$page}
  829. * @param $url URL地址
  830. * @return URL
  831. */
  832. function url_par($par, $url = '') {
  833. if($url == '') $url = get_url();
  834. $pos = strpos($url, '?');
  835. if($pos === false) {
  836. $url .= '?'.$par;
  837. } else {
  838. $querystring = substr(strstr($url, '?'), 1);
  839. parse_str($querystring, $pars);
  840. $query_array = array();
  841. foreach($pars as $k=>$v) {
  842. if($k != 'page') $query_array[$k] = $v;
  843. }
  844. $querystring = http_build_query($query_array).'&'.$par;
  845. $url = substr($url, 0, $pos).'?'.$querystring;
  846. }
  847. return $url;
  848. }
  849. /**
  850. * 判断email格式是否正确
  851. * @param $email
  852. */
  853. function is_email($email) {
  854. return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
  855. }
  856. /**
  857. * iconv 编辑转换
  858. */
  859. if (!function_exists('iconv')) {
  860. function iconv($in_charset, $out_charset, $str) {
  861. $in_charset = strtoupper($in_charset);
  862. $out_charset = strtoupper($out_charset);
  863. if (function_exists('mb_convert_encoding')) {
  864. return mb_convert_encoding($str, $out_charset, $in_charset);
  865. } else {
  866. pc_base::load_sys_func('iconv');
  867. $in_charset = strtoupper($in_charset);
  868. $out_charset = strtoupper($out_charset);
  869. if ($in_charset == 'UTF-8' && ($out_charset == 'GBK' || $out_charset == 'GB2312')) {
  870. return utf8_to_gbk($str);
  871. }
  872. if (($in_charset == 'GBK' || $in_charset == 'GB2312') && $out_charset == 'UTF-8') {
  873. return gbk_to_utf8($str);
  874. }
  875. return $str;
  876. }
  877. }
  878. }
  879. /**
  880. * 代码广告展示函数
  881. * @param intval $siteid 所属站点
  882. * @param intval $id 广告ID
  883. * @return 返回广告代码
  884. */
  885. function show_ad($siteid, $id) {
  886. $siteid = intval($siteid);
  887. $id = intval($id);
  888. if(!$id || !$siteid) return false;
  889. $p = pc_base::load_model('poster_model');
  890. $r = $p->get_one(array('spaceid'=>$id, 'siteid'=>$siteid), 'disabled, setting', '`id` ASC');
  891. if ($r['disabled']) return '';
  892. if ($r['setting']) {
  893. $c = string2array($r['setting']);
  894. } else {
  895. $r['code'] = '';
  896. }
  897. return $c['code'];
  898. }
  899. /**
  900. * 获取当前的站点ID
  901. */
  902. function get_siteid() {
  903. static $siteid;
  904. if (!empty($siteid)) return $siteid;
  905. if (defined('IN_ADMIN')) {
  906. if ($d = param::get_cookie('siteid')) {
  907. $siteid = $d;
  908. } else {
  909. return '';
  910. }
  911. } else {
  912. $data = getcache('sitelist', 'commons');
  913. if(!is_array($data)) return '1';
  914. $site_url = SITE_PROTOCOL.SITE_URL;
  915. foreach ($data as $v) {
  916. if ($v['url'] == $site_url.'/') $siteid = $v['siteid'];
  917. }
  918. }
  919. if (empty($siteid)) $siteid = 1;
  920. return $siteid;
  921. }
  922. /**
  923. * 获取用户昵称
  924. * 不传入userid取当前用户nickname,如果nickname为空取username
  925. * 传入field,取用户$field字段信息
  926. */
  927. function get_nickname($userid='', $field='') {
  928. $return = '';
  929. if(is_numeric($userid)) {
  930. $member_db = pc_base::load_model('member_model');
  931. $memberinfo = $member_db->get_one(array('userid'=>$userid));
  932. if(!empty($field) && $field != 'nickname' && isset($memberinfo[$field]) &&!empty($memberinfo[$field])) {
  933. $return = $memberinfo[$field];
  934. } else {
  935. $return = isset($memberinfo['nickname']) && !empty($memberinfo['nickname']) ? $memberinfo['nickname'].'('.$memberinfo['username'].')' : $memberinfo['username'];
  936. }
  937. } else {
  938. if (param::get_cookie('_nickname')) {
  939. $return .= '('.param::get_cookie('_nickname').')';
  940. } else {
  941. $return .= '('.param::get_cookie('_username').')';
  942. }
  943. }
  944. return $return;
  945. }
  946. /**
  947. * 获取用户信息
  948. * 不传入$field返回用户所有信息,
  949. * 传入field,取用户$field字段信息
  950. */
  951. function get_memberinfo($userid, $field='') {
  952. if(!is_numeric($userid)) {
  953. return false;
  954. } else {
  955. static $memberinfo;
  956. if (!isset($memberinfo[$userid])) {
  957. $member_db = pc_base::load_model('member_model');
  958. $memberinfo[$userid] = $member_db->get_one(array('userid'=>$userid));
  959. }
  960. if(!empty($field) && !empty($memberinfo[$userid][$field])) {
  961. return $memberinfo[$userid][$field];
  962. } else {
  963. return $memberinfo[$userid];
  964. }
  965. }
  966. }
  967. /**
  968. * 通过 username 值,获取用户所有信息
  969. * 获取用户信息
  970. * 不传入$field返回用户所有信息,
  971. * 传入field,取用户$field字段信息
  972. */
  973. function get_memberinfo_buyusername($username, $field='') {
  974. if(empty($username)){return false;}
  975. static $memberinfo;
  976. if (!isset($memberinfo[$username])) {
  977. $member_db = pc_base::load_model('member_model');
  978. $memberinfo[$username] = $member_db->get_one(array('username'=>$username));
  979. }
  980. if(!empty($field) && !empty($memberinfo[$username][$field])) {
  981. return $memberinfo[$username][$field];
  982. } else {
  983. return $memberinfo[$username];
  984. }
  985. }
  986. /**
  987. * 获取用户头像,建议传入phpssouid
  988. * @param $uid 默认为phpssouid
  989. * @param $is_userid $uid是否为v9 userid,如果为真,执行sql查询此用户的phpssouid
  990. * @param $size 头像大小 有四种[30x30 45x45 90x90 180x180] 默认30
  991. */
  992. function get_memberavatar($uid, $is_userid='', $size='30') {
  993. if($is_userid) {
  994. $db = pc_base::load_model('member_model');
  995. $memberinfo = $db->get_one(array('userid'=>$uid));
  996. if(isset($memberinfo['phpssouid'])) {
  997. $uid = $memberinfo['phpssouid'];
  998. } else {
  999. return false;
  1000. }
  1001. }
  1002. pc_base::load_app_class('client', 'member', 0);
  1003. define('APPID', pc_base::load_config('system', 'phpsso_appid'));
  1004. $phpsso_api_url = pc_base::load_config('system', 'phpsso_api_url');
  1005. $phpsso_auth_key = pc_base::load_config('system', 'phpsso_auth_key');
  1006. $client = new client($phpsso_api_url, $phpsso_auth_key);
  1007. $avatar = $client->ps_getavatar($uid);
  1008. if(isset($avatar[$size])) {
  1009. return $avatar[$size];
  1010. } else {
  1011. return false;
  1012. }
  1013. }
  1014. /**
  1015. * 调用关联菜单
  1016. * @param $linkageid 联动菜单id
  1017. * @param $id 生成联动菜单的样式id
  1018. * @param $defaultvalue 默认值
  1019. */
  1020. function menu_linkage($linkageid = 0, $id = 'linkid', $defaultvalue = 0) {
  1021. $linkageid = intval($linkageid);
  1022. $datas = array();
  1023. $datas = getcache($linkageid,'linkage');
  1024. $infos = $datas['data'];
  1025. if($datas['style']=='1') {
  1026. $title = $datas['title'];
  1027. $container = 'content'.random(3).date('is');
  1028. if(!defined('DIALOG_INIT_1')) {
  1029. define('DIALOG_INIT_1', 1);
  1030. $string .= '<script type="text/javascript" src="'.JS_PATH.'dialog.js"></script>';
  1031. //TODO $string .= '<link href="'.CSS_PATH.'dialog.css" rel="stylesheet" type="text/css">';
  1032. }
  1033. if(!defined('LINKAGE_INIT_1')) {
  1034. define('LINKAGE_INIT_1', 1);
  1035. $string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/pop.js"></script>';
  1036. }
  1037. $var_div = $defaultvalue && (ROUTE_A=='edit' || ROUTE_A=='account_manage_info' || ROUTE_A=='info_publish' || ROUTE_A=='orderinfo') ? menu_linkage_level($defaultvalue,$linkageid,$infos) : $datas['title'];
  1038. $var_input = $defaultvalue && (ROUTE_A=='edit' || ROUTE_A=='account_manage_info' || ROUTE_A=='info_publish') ? '<input type="hidden" name="info['.$id.']" value="'.$defaultvalue.'">' : '<input type="hidden" name="info['.$id.']" value="">';
  1039. $string .= '<div name="'.$id.'" value="" id="'.$id.'" class="ib">'.$var_div.'</div>'.$var_input.' <input type="button" name="btn_'.$id.'" class="button" value="'.L('linkage_select').'" onclick="open_linkage(\''.$id.'\',\''.$title.'\','.$container.',\''.$linkageid.'\')">';
  1040. $string .= '<script type="text/javascript">';
  1041. $string .= 'var returnid_'.$id.'= \''.$id.'\';';
  1042. $string .= 'var returnkeyid_'.$id.' = \''.$linkageid.'\';';
  1043. $string .= 'var '.$container.' = new Array(';
  1044. foreach($infos AS $k=>$v) {
  1045. if($v['parentid'] == 0) {
  1046. $s[]='new Array(\''.$v['linkageid'].'\',\''.$v['name'].'\',\''.$v['parentid'].'\')';
  1047. } else {
  1048. continue;
  1049. }
  1050. }
  1051. $s = implode(',',$s);
  1052. $string .=$s;
  1053. $string .= ')';
  1054. $string .= '</script>';
  1055. } elseif($datas['style']=='2') {
  1056. if(!defined('LINKAGE_INIT_1')) {
  1057. define('LINKAGE_INIT_1', 1);
  1058. $string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/jquery.ld.js"></script>';
  1059. }
  1060. $default_txt = '';
  1061. if($defaultvalue) {
  1062. $default_txt = menu_linkage_level($defaultvalue,$linkageid,$infos);
  1063. $default_txt = '["'.str_replace(' > ','","',$default_txt).'"]';
  1064. }
  1065. $string .= $defaultvalue && (ROUTE_A=='edit' || ROUTE_A=='account_manage_info' || ROUTE_A=='info_publish') ? '<input type="hidden" name="info['.$id.']" id="'.$id.'" value="'.$defaultvalue.'">' : '<input type="hidden" name="info['.$id.']" id="'.$id.'" value="">';
  1066. for($i=1;$i<=$datas['setting']['level'];$i++) {
  1067. $string .='<select class="pc-select-'.$id.'" name="'.$id.'-'.$i.'" id="'.$id.'-'.$i.'" width="100"><option value="">请选择菜单</option></select> ';
  1068. }
  1069. $string .= '<script type="text/javascript">
  1070. $(function(){
  1071. var $ld5 = $(".pc-select-'.$id.'");
  1072. $ld5.ld({ajaxOptions : {"url" : "'.APP_PATH.'api.php?op=get_linkage&act=ajax_select&keyid='.$linkageid.'"},defaultParentId : 0,style : {"width" : 120}})
  1073. var ld5_api = $ld5.ld("api");
  1074. ld5_api.selected('.$default_txt.');
  1075. $ld5.bind("change",onchange);
  1076. function onchange(e){
  1077. var $target = $(e.target);
  1078. var index = $ld5.index($target);
  1079. $("#'.$id.'-'.$i.'").remove();
  1080. $("#'.$id.'").val($ld5.eq(index).show().val());
  1081. index ++;
  1082. $ld5.eq(index).show(); }
  1083. })
  1084. </script>';
  1085. } else {
  1086. $title = $defaultvalue ? $infos[$defaultvalue]['name'] : $datas['title'];
  1087. $colObj = random(3).date('is');
  1088. $string = '';
  1089. if(!defined('LINKAGE_INIT')) {
  1090. define('LINKAGE_INIT', 1);
  1091. $string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/mln.colselect.js"></script>';
  1092. if(defined('IN_ADMIN')) {
  1093. $string .= '<link href="'.JS_PATH.'linkage/style/admin.css" rel="stylesheet" type="text/css">';
  1094. } else {
  1095. $string .= '<link href="'.JS_PATH.'linkage/style/css.css" rel="stylesheet" type="text/css">';
  1096. }
  1097. }
  1098. $string .= '<input type="hidden" name="info['.$id.']" value="1"><div id="'.$id.'"></div>';
  1099. $string .= '<script type="text/javascript">';
  1100. $string .= 'var colObj'.$colObj.' = {"Items":[';
  1101. foreach($infos AS $k=>$v) {
  1102. $s .= '{"name":"'.$v['name'].'","topid":"'.$v['parentid'].'","colid":"'.$k.'","value":"'.$k.'","fun":function(){}},';
  1103. }
  1104. $string .= substr($s, 0, -1);
  1105. $string .= ']};';
  1106. $string .= '$("#'.$id.'").mlnColsel(colObj'.$colObj.',{';
  1107. $string .= 'title:"'.$title.'",';
  1108. $string .= 'value:"'.$defaultvalue.'",';
  1109. $string .= 'width:100';
  1110. $string .= '});';
  1111. $string .= '</script>';
  1112. }
  1113. return $string;
  1114. }
  1115. /**
  1116. * 联动菜单层级
  1117. */
  1118. function menu_linkage_level($linkageid,$keyid,$infos,$result=array()) {
  1119. if(array_key_exists($linkageid,$infos)) {
  1120. $result[]=$infos[$linkageid]['name'];
  1121. return menu_linkage_level($infos[$linkageid]['parentid'],$keyid,$infos,$result);
  1122. }
  1123. krsort($result);
  1124. return implode(' > ',$result);
  1125. }
  1126. /**
  1127. * 通过catid获取显示菜单完整结构
  1128. * @param $menuid 菜单ID
  1129. * @param $cache_file 菜单缓存文件名称
  1130. * @param $cache_path 缓存文件目录
  1131. * @param $key 取得缓存值的键值名称
  1132. * @param $parentkey 父级的ID
  1133. * @param $linkstring 链接字符
  1134. */
  1135. function menu_level($menuid, $cache_file, $cache_path = 'commons', $key = 'catname', $parentkey = 'parentid', $linkstring = ' > ', $result=array()) {
  1136. $menu_arr = getcache($cache_file, $cache_path);
  1137. if (array_key_exists($menuid, $menu_arr)) {
  1138. $result[] = $menu_arr[$menuid][$key];
  1139. return menu_level($menu_arr[$menuid][$parentkey], $cache_file, $cache_path, $key, $parentkey, $linkstring, $result);
  1140. }
  1141. krsort($result);
  1142. return implode($linkstring, $result);
  1143. }
  1144. /**
  1145. * 通过id获取显示联动菜单
  1146. * @param $linkageid 联动菜单ID
  1147. * @param $keyid 菜单keyid
  1148. * @param $space 菜单间隔符
  1149. * @param $tyoe 1 返回间隔符链接,完整路径名称 3 返回完整路径数组,2返回当前联动菜单名称,4 直接返回ID
  1150. * @param $result 递归使用字段1
  1151. * @param $infos 递归使用字段2
  1152. */
  1153. function get_linkage($linkageid, $keyid, $space = '>', $type = 1, $result = array(), $infos = array()) {
  1154. if($space=='' || !isset($space))$space = '>';
  1155. if(!$infos) {
  1156. $datas = getcache($keyid,'linkage');
  1157. $infos = $datas['data'];
  1158. }
  1159. if($type == 1 || $type == 3 || $type == 4) {
  1160. if(array_key_exists($linkageid,$infos)) {
  1161. $result[]= ($type == 1) ? $infos[$linkageid]['name'] : (($type == 4) ? $linkageid :$infos[$linkageid]);
  1162. return get_linkage($infos[$linkageid]['parentid'], $keyid, $space, $type, $result, $infos);
  1163. } else {
  1164. if(count($result)>0) {
  1165. krsort($result);
  1166. if($type == 1 || $type == 4) $result = implode($space,$result);
  1167. return $result;
  1168. } else {
  1169. return $result;
  1170. }
  1171. }
  1172. } else {
  1173. return $infos[$linkageid]['name'];
  1174. }
  1175. }
  1176. /**
  1177. * IE浏览器判断
  1178. */
  1179. function is_ie() {
  1180. $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
  1181. if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
  1182. if(strpos($useragent, 'msie ') !== false) return true;
  1183. return false;
  1184. }
  1185. /**
  1186. * 文件下载
  1187. * @param $filepath 文件路径
  1188. * @param $filename 文件名称
  1189. */
  1190. function file_down($filepath, $filename = '') {
  1191. if(!$filename) $filename = basename($filepath);
  1192. if(is_ie()) $filename = rawurlencode($filename);
  1193. $filetype = fileext($filename);
  1194. $filesize = sprintf("%u", filesize($filepath));
  1195. if(ob_get_length() !== false) @ob_end_clean();
  1196. header('Pragma: public');
  1197. header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
  1198. header('Cache-Control: no-store, no-cache, must-revalidate');
  1199. header('Cache-Control: pre-check=0, post-check=0, max-age=0');
  1200. header('Content-Transfer-Encoding: binary');
  1201. header('Content-Encoding: none');
  1202. header('Content-type: '.$filetype);
  1203. header('Content-Disposition: attachment; filename="'.$filename.'"');
  1204. header('Content-length: '.$filesize);
  1205. readfile($filepath);
  1206. exit;
  1207. }
  1208. /**
  1209. * 判断字符串是否为utf8编码,英文和半角字符返回ture
  1210. * @param $string
  1211. * @return bool
  1212. */
  1213. function is_utf8($string) {
  1214. return preg_match('%^(?:
  1215. [\x09\x0A\x0D\x20-\x7E] # ASCII
  1216. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  1217. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  1218. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  1219. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  1220. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  1221. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  1222. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  1223. )*$%xs', $string);
  1224. }
  1225. /**
  1226. * 组装生成ID号
  1227. * @param $modules 模块名
  1228. * @param $contentid 内容ID
  1229. * @param $siteid 站点ID
  1230. */
  1231. function id_encode($modules,$contentid, $siteid) {
  1232. return urlencode($modules.'-'.$contentid.'-'.$siteid);
  1233. }
  1234. /**
  1235. * 解析ID
  1236. * @param $id 评论ID
  1237. */
  1238. function id_decode($id) {
  1239. return explode('-', $id);
  1240. }
  1241. /**
  1242. * 对用户的密码进行加密
  1243. * @param $password
  1244. * @param $encrypt //传入加密串,在修改密码时做认证
  1245. * @return array/password
  1246. */
  1247. function password($password, $encrypt='') {
  1248. $pwd = array();
  1249. $pwd['encrypt'] = $encrypt ? $encrypt : create_randomstr();
  1250. $pwd['password'] = md5(md5(trim($password)).$pwd['encrypt']);
  1251. return $encrypt ? $pwd['password'] : $pwd;
  1252. }
  1253. /**
  1254. * 生成随机字符串
  1255. * @param string $lenth 长度
  1256. * @return string 字符串
  1257. */
  1258. function create_randomstr($lenth = 6) {
  1259. return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
  1260. }
  1261. /**
  1262. * 检查密码长度是否符合规定
  1263. *
  1264. * @param STRING $password
  1265. * @return TRUE or FALSE
  1266. */
  1267. function is_password($password) {
  1268. $strlen = strlen($password);
  1269. if($strlen >= 6 && $strlen <= 20) return true;
  1270. return false;
  1271. }
  1272. /**
  1273. * 检测输入中是否含有错误字符
  1274. *
  1275. * @param char $string 要检查的字符串名称
  1276. * @return TRUE or FALSE
  1277. */
  1278. function is_badword($string) {
  1279. $badwords = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n","#");
  1280. foreach($badwords as $value){
  1281. if(strpos($string, $value) !== FALSE) {
  1282. return TRUE;
  1283. }
  1284. }
  1285. return FALSE;
  1286. }
  1287. /**
  1288. * 检查用户名是否符合规定
  1289. *
  1290. * @param STRING $username 要检查的用户名
  1291. * @return TRUE or FALSE
  1292. */
  1293. function is_username($username) {
  1294. $strlen = strlen($username);
  1295. if(is_badword($username) || !preg_match("/^[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/", $username)){
  1296. return false;
  1297. } elseif ( 20 < $strlen || $strlen < 2 ) {
  1298. return false;
  1299. }
  1300. return true;
  1301. }
  1302. /**
  1303. * 检查id是否存在于数组中
  1304. *
  1305. * @param $id
  1306. * @param $ids
  1307. * @param $s
  1308. */
  1309. function check_in($id, $ids = '', $s = ',') {
  1310. if(!$ids) return false;
  1311. $ids = explode($s, $ids);
  1312. return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);
  1313. }
  1314. /**
  1315. * 对数据进行编码转换
  1316. * @param array/string $data 数组
  1317. * @param string $input 需要转换的编码
  1318. * @param string $output 转换后的编码
  1319. */
  1320. function array_iconv($data, $input = 'gbk', $output = 'utf-8') {
  1321. if (!is_array($data)) {
  1322. return iconv($input, $output, $data);
  1323. } else {
  1324. foreach ($data as $key=>$val) {
  1325. if(is_array($val)) {
  1326. $data[$key] = array_iconv($val, $input, $output);
  1327. } else {
  1328. $data[$key] = iconv($input, $output, $val);
  1329. }
  1330. }
  1331. return $data;
  1332. }
  1333. }
  1334. /**
  1335. * 生成缩略图函数
  1336. * @param $imgurl 图片路径
  1337. * @param $width 缩略图宽度
  1338. * @param $height 缩略图高度
  1339. * @param $autocut 是否自动裁剪 默认裁剪,当高度或宽度有一个数值为0是,自动关闭
  1340. * @param $smallpic 无图片是默认图片路径
  1341. */
  1342. function thumb($imgurl, $width = 100, $height = 100 ,$autocut = 1, $smallpic = 'nopic.gif') {
  1343. global $image;
  1344. $upload_url = pc_base::load_config('system','upload_url');
  1345. $upload_path = pc_base::load_config('system','upload_path');
  1346. if(empty($imgurl)) return IMG_PATH.$smallpic;
  1347. $imgurl_replace= str_replace($upload_url, '', $imgurl);
  1348. if(!extension_loaded('gd') || strpos($imgurl_replace, '://')) return $imgurl;
  1349. if(!file_exists($upload_path.$imgurl_replace)) return IMG_PATH.$smallpic;
  1350. list($width_t, $height_t, $type, $attr) = getimagesize($upload_path.$imgurl_replace);
  1351. if($width>=$width_t || $height>=$height_t) return $imgurl;
  1352. $newimgurl = dirname($imgurl_replace).'/thumb_'.$width.'_'.$height.'_'.basename($imgurl_replace);
  1353. if(file_exists($upload_path.$newimgurl)) return $upload_url.$newimgurl;
  1354. if(!is_object($image)) {
  1355. pc_base::load_sys_class('image','','0');
  1356. $image = new image(1,0);
  1357. }
  1358. return $image->thumb($upload_path.$imgurl_replace, $upload_path.$newimgurl, $width, $height, '', $autocut) ? $upload_url.$newimgurl : $imgurl;
  1359. }
  1360. /**
  1361. * 水印添加
  1362. * @param $source 原图片路径
  1363. * @param $target 生成水印图片途径,默认为空,覆盖原图
  1364. * @param $siteid 站点id,系统需根据站点id获取水印信息
  1365. */
  1366. function watermark($source, $target = '',$siteid) {
  1367. global $image_w;
  1368. if(empty($source)) return $source;
  1369. if(!extension_loaded('gd') || strpos($source, '://')) return $source;
  1370. if(!$target) $target = $source;
  1371. if(!is_object($image_w)){
  1372. pc_base::load_sys_class('image','','0');
  1373. $image_w = new image(0,$siteid);
  1374. }
  1375. $image_w->watermark($source, $target);
  1376. return $target;
  1377. }
  1378. /**
  1379. * 当前路径
  1380. * 返回指定栏目路径层级
  1381. * @param $catid 栏目id
  1382. * @param $symbol 栏目间隔符
  1383. */
  1384. function catpos($catid, $symbol=' > '){
  1385. $category_arr = array();
  1386. $siteids = getcache('category_content','commons');
  1387. $siteid = $siteids[$catid];
  1388. $category_arr = getcache('category_content_'.$siteid,'commons');
  1389. if(!isset($category_arr[$catid])) return '';
  1390. $pos = '';
  1391. $siteurl = siteurl($category_arr[$catid]['siteid']);
  1392. $arrparentid = array_filter(explode(',', $category_arr[$catid]['arrparentid'].','.$catid));
  1393. foreach($arrparentid as $catid) {
  1394. $url = $category_arr[$catid]['url'];
  1395. if(strpos($url, '://') === false) $url = $siteurl.$url;
  1396. $pos .= $symbol.'<a href="'.$url.'">'.$category_arr[$catid]['catname'].'</a>';
  1397. }
  1398. return $pos;
  1399. }
  1400. /**
  1401. * 根据catid获取子栏目数据的sql语句
  1402. * @param string $module 缓存文件名
  1403. * @param intval $catid 栏目ID
  1404. */
  1405. function get_sql_catid($file = 'category_content_1', $catid = 0, $module = 'commons') {
  1406. $category = getcache($file,$module);
  1407. $catid = intval($catid);
  1408. if(!isset($category[$catid])) return false;
  1409. return $category[$catid]['child'] ? " `catid` IN(".$category[$catid]['arrchildid'].") " : " `catid`=$catid ";
  1410. }
  1411. /**
  1412. * 获取子栏目
  1413. * @param $parentid 父级id
  1414. * @param $type 栏目类型
  1415. * @param $self 是否包含本身 0为不包含
  1416. * @param $siteid 站点id
  1417. */
  1418. function subcat($parentid = NULL, $type = NULL,$self = '0', $siteid = '') {
  1419. if (empty($siteid)) $siteid = get_siteid();
  1420. $category = getcache('category_content_'.$siteid,'commons');
  1421. foreach($category as $id=>$cat) {
  1422. if($cat['siteid'] == $siteid && ($parentid === NULL || $cat['parentid'] == $parentid) && ($type === NULL || $cat['type'] == $type)) $subcat[$id] = $cat;
  1423. if($self == 1 && $cat['catid'] == $parentid && !$cat['child']) $subcat[$id] = $cat;
  1424. }
  1425. return $subcat;
  1426. }
  1427. /**
  1428. * 获取内容地址
  1429. * @param $catid 栏目ID
  1430. * @param $id 文章ID
  1431. * @param $allurl 是否以绝对路径返回
  1432. */
  1433. function go($catid,$id, $allurl = 0) {
  1434. static $category;
  1435. if(empty($category)) {
  1436. $siteids = getcache('category_content','commons');
  1437. $siteid = $siteids[$catid];
  1438. $category = getcache('category_content_'.$siteid,'commons');
  1439. }
  1440. $id = intval($id);
  1441. if(!$id || !isset($category[$catid])) return '';
  1442. $modelid = $category[$catid]['modelid'];
  1443. if(!$modelid) return '';
  1444. $db = pc_base::load_model('content_model');
  1445. $db->set_model($modelid);
  1446. $r = $db->get_one(array('id'=>$id), '`url`');
  1447. if (!empty($allurl)) {
  1448. if (strpos($r['url'], '://')===false) {
  1449. $site = siteinfo($category[$catid]['siteid']);
  1450. $r['url'] = substr($site['domain'], 0, -1).$r['url'];
  1451. }
  1452. }
  1453. return $r['url'];
  1454. }
  1455. /**
  1456. * 将附件地址转换为绝对地址
  1457. * @param $path 附件地址
  1458. */
  1459. function atturl($path) {
  1460. if(strpos($path, ':/')) {
  1461. return $path;
  1462. } else {
  1463. $sitelist = getcache('sitelist','commons');
  1464. $siteid = get_siteid();
  1465. $siteurl = $sitelist[$siteid]['domain'];
  1466. $domainlen = strlen($sitelist[$siteid]['domain'])-1;
  1467. $path = $siteurl.$path;
  1468. $path = substr_replace($path, '/', strpos($path, '//',$domainlen),2);
  1469. return $path;
  1470. }
  1471. }
  1472. /**
  1473. * 判断模块是否安装
  1474. * @param $m 模块名称
  1475. */
  1476. function module_exists($m = '') {
  1477. if ($m=='admin') return true;
  1478. $modules = getcache('modules', 'commons');
  1479. $modules = array_keys($modules);
  1480. return in_array($m, $modules);
  1481. }
  1482. /**
  1483. * 生成SEO
  1484. * @param $siteid 站点ID
  1485. * @param $catid 栏目ID
  1486. * @param $title 标题
  1487. * @param $description 描述
  1488. * @param $keyword 关键词
  1489. */
  1490. function seo($siteid, $catid = '', $title = '', $description = '', $keyword = '') {
  1491. if (!empty($title))$title = strip_tags($title);
  1492. if (!empty($description)) $description = strip_tags($description);
  1493. if (!empty($keyword)) $keyword = str_replace(' ', ',', strip_tags($keyword));
  1494. $sites = getcache('sitelist', 'commons');
  1495. $site = $sites[$siteid];
  1496. $cat = array();
  1497. if (!empty($catid)) {
  1498. $siteids = getcache('category_content','commons');
  1499. $siteid = $siteids[$catid];
  1500. $categorys = getcache('category_content_'.$siteid,'commons');
  1501. $cat = $categorys[$catid];
  1502. $cat['setting'] = string2array($cat['setting']);
  1503. }
  1504. $seo['site_title'] =isset($site['site_title']) && !empty($site['site_title']) ? $site['site_title'] : $site['name'];
  1505. $seo['keyword'] = !empty($keyword) ? $keyword : $site['keywords'];
  1506. $seo['description'] = isset($description) && !empty($description) ? $description : (isset($cat['setting']['meta_description']) && !empty($cat['setting']['meta_description']) ? $cat['setting']['meta_description'] : (isset($site['description']) && !empty($site['description']) ? $site['description'] : ''));
  1507. $seo['title'] = (isset($title) && !empty($title) ? $title.' - ' : '').(isset($cat['setting']['meta_title']) && !empty($cat['setting']['meta_title']) ? $cat['setting']['meta_title'].' - ' : (isset($cat['catname']) && !empty($cat['catname']) ? $cat['catname'].' - ' : ''));
  1508. foreach ($seo as $k=>$v) {
  1509. $seo[$k] = str_replace(array("\n","\r"), '', $v);
  1510. }
  1511. return $seo;
  1512. }
  1513. /**
  1514. * 获取站点的信息
  1515. * @param $siteid 站点ID
  1516. */
  1517. function siteinfo($siteid) {
  1518. static $sitelist;
  1519. if (empty($sitelist)) $sitelist = getcache('sitelist','commons');
  1520. return isset($sitelist[$siteid]) ? $sitelist[$siteid] : '';
  1521. }
  1522. /**
  1523. * 生成CNZZ统计代码
  1524. */
  1525. function tjcode() {
  1526. if(!module_exists('cnzz')) return false;
  1527. $config = getcache('cnzz', 'commons');
  1528. if (empty($config)) {
  1529. return false;
  1530. } else {
  1531. return '<script src=\'http://pw.cnzz.com/c.php?id='.$config['siteid'].'&l=2\' language=\'JavaScript\' charset=\'gb2312\'></script>';
  1532. }
  1533. }
  1534. /**
  1535. * 生成标题样式
  1536. * @param $style 样式
  1537. * @param $html 是否显示完整的STYLE
  1538. */
  1539. function title_style($style, $html = 1) {
  1540. if(!$style) return "";
  1541. $str = '';
  1542. if ($html) $str = ' style="';
  1543. $style_arr = explode(';',$style);
  1544. if (!empty($style_arr[0])) $str .= 'color:'.$style_arr[0].';';
  1545. if (!empty($style_arr[1])) $str .= 'font-weight:'.$style_arr[1].';';
  1546. if ($html) $str .= '" ';
  1547. return $str;
  1548. }
  1549. /**
  1550. * 获取站点域名
  1551. * @param $siteid 站点id
  1552. */
  1553. function siteurl($siteid) {
  1554. static $sitelist;
  1555. if(!$siteid) return WEB_PATH;
  1556. if(empty($sitelist)) $sitelist = getcache('sitelist','commons');
  1557. return substr($sitelist[$siteid]['domain'],0,-1);
  1558. }
  1559. /**
  1560. * 生成上传附件验证
  1561. * @param $args 参数
  1562. * @param $operation 操作类型(加密解密)
  1563. */
  1564. function upload_key($args) {
  1565. $pc_auth_key = md5(pc_base::load_config('system','auth_key').$_SERVER['HTTP_USER_AGENT']);
  1566. $authkey = md5($args.$pc_auth_key);
  1567. return $authkey;
  1568. }
  1569. /**
  1570. * 生成验证key
  1571. * @param $prefix 参数
  1572. * @param $suffix 参数
  1573. */
  1574. function get_auth_key($prefix,$suffix="") {
  1575. if($prefix=='login'){
  1576. $pc_auth_key = md5(pc_base::load_config('system','auth_key').ip());
  1577. }else if($prefix=='email'){
  1578. $pc_auth_key = md5(pc_base::load_config('system','auth_key'));
  1579. }else{
  1580. $pc_auth_key = md5(pc_base::load_config('system','auth_key').$suffix);
  1581. }
  1582. $authkey = md5($prefix.$pc_auth_key);
  1583. return $authkey;
  1584. }
  1585. /**
  1586. * 文本转换为图片
  1587. * @param string $txt 图形化文本内容
  1588. * @param int $fonttype 无外部字体时生成文字大小,取值范围1-5
  1589. * @param int $fontsize 引入外部字体时,字体大小
  1590. * @param string $font 字体名称 字体请放于phpcms\libs\data\font下
  1591. * @param string $fontcolor 字体颜色 十六进制形式 如FFFFFF,FF0000
  1592. */
  1593. function string2img($txt, $fonttype = 5, $fontsize = 16, $font = '', $fontcolor = 'FF0000',$transparent = '1') {
  1594. if(empty($txt)) return false;
  1595. if(function_exists("imagepng")) {
  1596. $txt = urlencode(sys_auth($txt));
  1597. $txt = '<img src="'.APP_PATH.'api.php?op=creatimg&txt='.$txt.'&fonttype='.$fonttype.'&fontsize='.$fontsize.'&font='.$font.'&fontcolor='.$fontcolor.'&transparent='.$transparent.'" align="absmiddle">';
  1598. }
  1599. return $txt;
  1600. }
  1601. /**
  1602. * 获取phpcms版本号
  1603. */
  1604. function get_pc_version($type='') {
  1605. $version = pc_base::load_config('version');
  1606. if($type==1) {
  1607. return $version['pc_version'];
  1608. } elseif($type==2) {
  1609. return $version['pc_release'];
  1610. } else {
  1611. return $version['pc_version'].' '.$version['pc_release'];
  1612. }
  1613. }
  1614. /**
  1615. * 运行钩子(插件使用)
  1616. */
  1617. function runhook($method) {
  1618. $time_start = getmicrotime();
  1619. $data = '';
  1620. $getpclass = FALSE;
  1621. $hook_appid = getcache('hook','plugins');
  1622. if(!empty($hook_appid)) {
  1623. foreach($hook_appid as $appid => $p) {
  1624. $pluginfilepath = PC_PATH.'plugin'.DIRECTORY_SEPARATOR.$p.DIRECTORY_SEPARATOR.'hook.class.php';
  1625. $getpclass = TRUE;
  1626. include_once $pluginfilepath;
  1627. }
  1628. $hook_appid = array_flip($hook_appid);
  1629. if($getpclass) {
  1630. $pclass = new ReflectionClass('hook');
  1631. foreach($pclass->getMethods() as $r) {
  1632. $legalmethods[] = $r->getName();
  1633. }
  1634. }
  1635. if(in_array($method,$legalmethods)) {
  1636. foreach (get_declared_classes() as $class){
  1637. $refclass = new ReflectionClass($class);
  1638. if($refclass->isSubclassOf('hook')){
  1639. if ($_method = $refclass->getMethod($method)) {
  1640. $classname = $refclass->getName();
  1641. if ($_method->isPublic() && $_method->isFinal()) {
  1642. plugin_stat($hook_appid[$classname]);
  1643. $data .= $_method->invoke(null);
  1644. }
  1645. }
  1646. }
  1647. }
  1648. }
  1649. return $data;
  1650. }
  1651. }
  1652. function getmicrotime() {
  1653. list($usec, $sec) = explode(" ",microtime());
  1654. return ((float)$usec + (float)$sec);
  1655. }
  1656. /**
  1657. * 插件前台模板加载
  1658. * Enter description here ...
  1659. * @param unknown_type $module
  1660. * @param unknown_type $template
  1661. * @param unknown_type $style
  1662. */
  1663. function p_template($plugin = 'content', $template = 'index',$style='default') {
  1664. if(!$style) $style = 'default';
  1665. $template_cache = pc_base::load_sys_class('template_cache');
  1666. $compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.$template.'.php';
  1667. if(!file_exists($compiledtplfile) || (file_exists(PC_PATH.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(PC_PATH.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile))) {
  1668. $template_cache->template_compile('plugin/'.$plugin, $template, 'default');
  1669. } elseif (!file_exists(PC_PATH.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$template.'.html')) {
  1670. showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.$template.'.html');
  1671. }
  1672. return $compiledtplfile;
  1673. }
  1674. /**
  1675. * 读取缓存动态页面
  1676. */
  1677. function cache_page_start() {
  1678. $relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
  1679. define('CACHE_PAGE_ID', md5($relate_url));
  1680. $contents = getcache(CACHE_PAGE_ID, 'page_tmp/'.substr(CACHE_PAGE_ID, 0, 2));
  1681. if($contents && intval(substr($contents, 15, 10)) > SYS_TIME) {
  1682. echo substr($contents, 29);
  1683. exit;
  1684. }
  1685. if (!defined('HTML')) define('HTML',true);
  1686. return true;
  1687. }
  1688. /**
  1689. * 写入缓存动态页面
  1690. */
  1691. function cache_page($ttl = 360, $isjs = 0) {
  1692. if($ttl == 0 || !defined('CACHE_PAGE_ID')) return false;
  1693. $contents = ob_get_contents();
  1694. if($isjs) $contents = format_js($contents);
  1695. $contents = "<!--expiretime:".(SYS_TIME + $ttl)."-->\n".$contents;
  1696. setcache(CACHE_PAGE_ID, $contents, 'page_tmp/'.substr(CACHE_PAGE_ID, 0, 2));
  1697. }
  1698. /**
  1699. *
  1700. * 获取远程内容
  1701. * @param $url 接口url地址
  1702. * @param $timeout 超时时间
  1703. */
  1704. function pc_file_get_contents($url, $timeout=30) {
  1705. $stream = stream_context_create(array('http' => array('timeout' => $timeout)));
  1706. return @file_get_contents($url, 0, $stream);
  1707. }
  1708. /**
  1709. * Function get_vid
  1710. * 获取视频信息
  1711. * @param int $contentid 内容ID 必须
  1712. * @param int $catid 栏目id 取内容里面视频信息时必须
  1713. * @param int $isspecial 是否取专题的视频信息
  1714. */
  1715. function get_vid($contentid = 0, $catid = 0, $isspecial = 0) {
  1716. static $categorys;
  1717. if (!$contentid) return false;
  1718. if (!$isspecial) {
  1719. if (!$catid) return false;
  1720. $contentid = intval($contentid);
  1721. $catid = intval($catid);
  1722. $siteid = get_siteid();
  1723. if (!$categorys) {
  1724. $categorys = getcache('category_content_'.$siteid, 'commons');
  1725. }
  1726. $modelid = $categorys[$catid]['modelid'];
  1727. $video_content = pc_base::load_model('video_content_model');
  1728. $r = $video_content->get_one(array('contentid'=>$contentid, 'modelid'=>$modelid), 'videoid', '`listorder` ASC');
  1729. $video_store =pc_base::load_model('video_store_model');
  1730. return $video_store->get_one(array('videoid'=>$r['videoid']));
  1731. } else {
  1732. $special_content = pc_base::load_model('special_content_model');
  1733. $contentid = intval($contentid);
  1734. $video_store =pc_base::load_model('video_store_model');
  1735. $r = $special_content->get_one(array('id'=>$contentid), 'videoid');
  1736. return $video_store->get_one(array('videoid'=>$r['videoid']));
  1737. }
  1738. }
  1739. /**
  1740. * Function dataformat
  1741. * 时间转换
  1742. * @param $n INT时间
  1743. */
  1744. function dataformat($n) {
  1745. $hours = floor($n/3600);
  1746. $minite = floor($n%3600/60);
  1747. $secend = floor($n%3600%60);
  1748. $minite = $minite < 10 ? "0".$minite : $minite;
  1749. $secend = $secend < 10 ? "0".$secend : $secend;
  1750. if($n >= 3600){
  1751. return $hours.":".$minite.":".$secend;
  1752. }else{
  1753. return $minite.":".$secend;
  1754. }
  1755. }
  1756. ?>