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

/common/functions.php

http://lazycms.googlecode.com/
PHP | 1966 lines | 1360 code | 60 blank | 546 comment | 300 complexity | d53e2fca89e0b490f23f8096b908086c MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * +---------------------------------------------------------------------------+
  4. * | LL LLLL LL L LLLL LLLL |
  5. * | LL LL L LLL LL LL L LL LL |
  6. * | LL LLLL LLLLL LL LL LL LLLL LLL LL LL LL LL |
  7. * | LL LL LL LL LL LL L LLL LL LLLLL LL LL LL |
  8. * | LL LLLLL LL LLLL LL L L LL LLLLL LL LL LL |
  9. * | LL LL LL LL LLLL LL L LL LL LLLL LL |
  10. * | LL LL LL LL LL LL L L LL L LL LLLL LL |
  11. * | LLLLLL LLLLL LLLLL LL LLLL L LL LLLL LL LLLLLL |
  12. * | LL |
  13. * | LL |
  14. * +---------------------------------------------------------------------------+
  15. * | Copyright (C) 2007-2010 LazyCMS.com All rights reserved. |
  16. * +---------------------------------------------------------------------------+
  17. * | LazyCMS is free software. See LICENSE for copyright notices and details. |
  18. * +---------------------------------------------------------------------------+
  19. */
  20. defined('COM_PATH') or die('Restricted access!');
  21. /**
  22. * LazyCMS ?????
  23. *
  24. * @author Lukin <my@lukin.cn>
  25. * @version $Id: functions.php 763 2011-05-06 14:19:16Z mylukin $
  26. */
  27. /**
  28. * ?? PHP info
  29. *
  30. * @return array
  31. */
  32. function parse_phpinfo() {
  33. ob_start(); phpinfo(INFO_MODULES); $s = ob_get_contents(); ob_end_clean();
  34. $s = strip_tags($s, '<h2><th><td>');
  35. $s = preg_replace('/<th[^>]*>([^<]+)<\/th>/', '<info>\1</info>', $s);
  36. $s = preg_replace('/<td[^>]*>([^<]+)<\/td>/', '<info>\1</info>', $s);
  37. $t = preg_split('/(<h2[^>]*>[^<]+<\/h2>)/', $s, -1, PREG_SPLIT_DELIM_CAPTURE);
  38. $r = array(); $count = count($t);
  39. $p1 = '<info>([^<]+)<\/info>';
  40. $p2 = '/'.$p1.'\s*'.$p1.'\s*'.$p1.'/';
  41. $p3 = '/'.$p1.'\s*'.$p1.'/';
  42. for ($i = 1; $i < $count; $i++) {
  43. if (preg_match('/<h2[^>]*>([^<]+)<\/h2>/', $t[$i], $matchs)) {
  44. $name = trim($matchs[1]);
  45. $vals = explode("\n", $t[$i + 1]);
  46. foreach ($vals AS $val) {
  47. if (preg_match($p2, $val, $matchs)) { // 3cols
  48. $r[$name][trim($matchs[1])] = array(trim($matchs[2]), trim($matchs[3]));
  49. } elseif (preg_match($p3, $val, $matchs)) { // 2cols
  50. $r[$name][trim($matchs[1])] = trim($matchs[2]);
  51. }
  52. }
  53. }
  54. }
  55. return $r;
  56. }
  57. /**
  58. * ???? /tags/CMS
  59. *
  60. * @param string $path
  61. * @return array
  62. */
  63. function parse_path($path) {
  64. $paths = explode('/', $path);
  65. $length = count($paths);
  66. for($i=0; $i<$length; $i++){
  67. if (isset($paths[$i+1])) {
  68. $_GET[$paths[$i]] = strval($paths[++$i]);
  69. }
  70. }
  71. $_REQUEST = array_merge($_POST,$_GET);
  72. return $paths;
  73. }
  74. /**
  75. * ?????
  76. *
  77. * @param string $path %ID,%PY,%MD5 ? strftime() ?????
  78. * @param array $data
  79. * array(
  80. * 'ID' => 1,
  81. * 'PY' => '??',
  82. * 'MD5' => '??ID??????????',
  83. * )
  84. * @return string
  85. */
  86. function path_format($path,$data=null) {
  87. if (is_array($data)) {
  88. $py = $id = $md5 = null;
  89. foreach ($data as $k=>$v) {
  90. if (empty($v)) continue;
  91. if ($k=='PY') {
  92. $py = preg_replace('/[^\w\-\.\!\(\)~,#@$%^]/', '-', trim(clear_space(pinyin($v))));
  93. } elseif ($k=='ID') {
  94. $id = $v;
  95. } elseif ($k=='MD5') {
  96. $md5 = md5($path.$v);
  97. }
  98. }
  99. if ($py) $path = str_replace(array('%PY','%py'), $py, $path);
  100. if ($id) $path = str_replace(array('%ID','%id'), $id, $path);
  101. if ($md5) $path = str_replace(array('%MD5','%md5'), $md5, $path);
  102. }
  103. return strftime($path);
  104. }
  105. /**
  106. * W3c Datetime
  107. *
  108. * @param int $timestamp
  109. * @return string
  110. */
  111. function W3cDate($timestamp=0) {
  112. if (!$timestamp) $timestamp = time();
  113. if (version_compare(PHP_VERSION,'5.1.0','>='))
  114. return date('c', $timestamp);
  115. $date = date('Y-m-d\TH:i:s', $timestamp);
  116. $matches = array();
  117. if (preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $timestamp), $matches)) {
  118. $date .= $matches[1] . $matches[2] . ':' . $matches[3];
  119. } else {
  120. $date .= 'Z';
  121. }
  122. return $date;
  123. }
  124. /**
  125. * ?????
  126. *
  127. * @param $format
  128. * @param $time
  129. * @return mixed
  130. */
  131. function time_format($format,$time) {
  132. $days = $time>86400 ? floor($time/86400) : 0;
  133. $time = $time - 86400 * $days;
  134. $hour = $time>=3600 && $time<86400 ? floor($time/3600) : 0;
  135. $time = $time - 86400 * $days - 3600 * $hour;
  136. $minute = $time>=60 && $time<3600 ? floor($time/60) : 0;
  137. $time = $time - 86400 * $days - 3600 * $hour - 60 * $minute;
  138. $second = $time>0 && $time<60 ? $time : 0;
  139. $time = floor(($time - intval($second)) * 100);
  140. $micro = $time>0 ? $time : 0;
  141. $format = str_replace(array('%%ms','%%m','%%H','%%i','%%s'), array('$ms','$m','$H','$i','$s'),$format);
  142. $result = str_replace(array('%ms','%m','%H','%i','%s'), array(
  143. sprintf('%02d',$micro),
  144. sprintf('%02d',$days),
  145. sprintf('%02d',$hour),
  146. sprintf('%02d',$minute),
  147. sprintf('%02d',$second),
  148. ),$format);
  149. return str_replace(array('$ms','$m','$H','$i','$s'),array('%ms','%m','%H','%i','%s'),$result);
  150. }
  151. /**
  152. * ?????????
  153. */
  154. function &get_conn(){
  155. global $db;
  156. if (is_null($db) || get_class($db)=='DBQuery_NOOP') {
  157. if (!class_exists('DBQuery'))
  158. include COM_PATH.'/system/dbquery.php';
  159. if (defined('DB_DSN') && defined('DB_USER') && defined('DB_PWD')) {
  160. $db = DBQuery::factory(DB_DSN, DB_USER, DB_PWD);
  161. } else {
  162. $db = new DBQuery_NOOP();
  163. }
  164. }
  165. return $db;
  166. }
  167. /**
  168. * ?????
  169. *
  170. * @param $id
  171. * @param $content
  172. * @param $options see http://xheditor.com/manual/2#chapter2
  173. * @return string
  174. */
  175. function editor($id,$content,$options=null) {
  176. $defaults = array(
  177. 'width' => '680',
  178. 'height' => '280',
  179. 'toobar' => 'full',
  180. 'emotPath' => ROOT.'common/images/emots/',
  181. 'editorRoot' => ROOT.'common/editor/',
  182. 'loadCSS' => ROOT.'common/css/xheditor.plugins.css',
  183. );
  184. $options = $options ? array_merge($defaults, $options) : $defaults;
  185. if (isset($options['tools'])) unset($options['toobar']);
  186. if (isset($options['toobar'])) {
  187. switch ($options['toobar']) {
  188. case 'full':
  189. $options['tools'] = 'Source,Preview,Pastetext,|,Blocktag,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,'.
  190. 'BackColor,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,Img,Flash,Flv,Emot,Table,GoogleMap,Pagebreak,Explorer,Removelink,LocalizedImages,|,'.
  191. 'Fullscreen';
  192. break;
  193. case 'simple':
  194. $options['tools'] = 'simple';
  195. break;
  196. case 'mini':
  197. $options['tools'] = 'mini';
  198. break;
  199. }
  200. unset($options['toobar']);
  201. }
  202. $botbar = array();
  203. if (instr('Pagebreak', $options['tools'])) {
  204. $botbar[] = '<button type="button" onclick="xhe_'.$id.'.exec(\'Pagebreak\');">'.__('Insert Pagebreak').'</button>';
  205. }
  206. if (instr('Removelink', $options['tools'])) {
  207. $botbar[] = '<button type="button" onclick="xhe_'.$id.'.exec(\'Removelink\');">'.__('Remove external links').'</button>';
  208. }
  209. if (instr('Explorer', $options['tools'])) {
  210. $botbar[] = '<button type="button" onclick="xhe_'.$id.'.exec(\'Explorer\');">'.__('Explorer').'</button>';
  211. }
  212. if (instr('LocalizedImages', $options['tools'])) {
  213. $botbar[] = '<input cookie="true" type="checkbox" name="LocalizedImages['.$id.']" id="LocalizedImages_'.$id.'" value="1" /><label for="LocalizedImages_'.$id.'">'.__('Localized Images').'</label>';
  214. }
  215. $ht = '<textarea class="text" id="'.$id.'" name="'.$id.'">'.esc_html($content).'</textarea>';
  216. $ht.= '<script type="text/javascript">';
  217. $ht.= 'var xhe_'.$id.' = $(\'textarea[name='.$id.']\').xheditor(';
  218. $ht.= '$.extend('.json_encode($options).',{"onUpload":(typeof(onUpload)==\'function\' ? onUpload : null),';
  219. $ht.= '"upLinkUrl":LazyCMS.UpLinkUrl, "upLinkExt":LazyCMS.UpLinkExt, "upImgUrl":LazyCMS.UpImgUrl, "upImgExt":LazyCMS.UpImgExt, "upFlashUrl":LazyCMS.UpFlashUrl, "upVideoUrl":LazyCMS.UpVideoUrl, "upVideoExt":LazyCMS.UpVideoExt,';
  220. $ht.= '"plugins":xhePlugins, "beforeSetSource":xheFilter.SetSource, "beforeGetSource":xheFilter.GetSource';
  221. $ht.= '}));</script>';
  222. if (!empty($botbar)) $ht.= '<div class="xhe_botbar">'.implode('', $botbar).'</div>';
  223. return $ht;
  224. }
  225. if (!function_exists('error_page')) :
  226. /**
  227. * ????
  228. *
  229. * @param string $title
  230. * @param string $content
  231. * @param bool $is_full ????????
  232. * @return string
  233. */
  234. function error_page($title,$content,$is_full=false) {
  235. // CSS
  236. $css = '<style type="text/css">';
  237. $css.= '#error-page { width:600px; min-height:250px; background:#fff url('.ROOT.'common/images/warning-large.png) no-repeat 15px 10px; margin-top:15px; padding-bottom:30px; border:1px solid #B5B5B5; }';
  238. $css.= '#error-page { -moz-border-radius:6px; -webkit-border-radius:6px; -khtml-border-radius:6px; border-radius:6px; }';
  239. $css.= '#error-title { width:500px; border-bottom:solid 1px #B5B5B5; margin:0 0 15px 80px; }';
  240. $css.= '#error-title h1{ font-size: 25px; margin:10px 0 5px 0; }';
  241. $css.= '#error-content,#error-buttons { margin:10px 0 10px 80px; }';
  242. if ($is_full) {
  243. $css.= 'body { margin:10px 20px; font-family: Verdana; color: #333333; background:#FAFAFA; font-size: 12px; line-height: 1.5; }';
  244. $css.= '#error-page { width:900px; margin:15px auto; }';
  245. $css.= '#error-title { width:800px;}';
  246. }
  247. $css.= '</style>';
  248. // Page
  249. $page = '<div id="error-page">';
  250. $page.= '<div id="error-title"><h1>'.$title.'</h1></div>';
  251. $page.= '<div id="error-content">'.$content.'</div>';
  252. $page.= '<div id="error-buttons"><button type="button" onclick="window.history.back();">'.__('Back').'</button></div>';
  253. $page.= '</div>';
  254. if ($is_full) {
  255. $hl = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
  256. $hl.= '<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
  257. $hl.= '<title>'.$title.' &#8212; LazyCMS</title>';
  258. $hl.= $css.'</head><body>'.$page;
  259. $hl.= '</body></html>';
  260. } else {
  261. $hl = $css.$page;
  262. }
  263. return $hl;
  264. }
  265. endif;
  266. /**
  267. * ??????
  268. *
  269. * @param $errno
  270. * @param $errstr
  271. * @param $errfile
  272. * @param $errline
  273. * @return bool
  274. */
  275. function handler_error($errno,$errstr,$errfile,$errline) {
  276. if (E_STRICT===$errno) return true;
  277. return throw_error($errstr,$errno,$errfile,$errline);
  278. }
  279. /**
  280. * ??????
  281. *
  282. * @return array
  283. */
  284. function last_error($error=true) {
  285. global $LC_ERRNO, $LC_ERROR,$LC_ERRFILE,$LC_ERRLINE;
  286. // ????
  287. if ($error === null)
  288. $LC_ERRNO = $LC_ERROR = $LC_ERRFILE = $LC_ERRLINE = null;
  289. // ????
  290. if (!$LC_ERRNO) return null;
  291. // ???
  292. return array(
  293. 'errno' => $LC_ERRNO,
  294. 'error' => $LC_ERROR,
  295. 'file' => $LC_ERRFILE,
  296. 'line' => $LC_ERRLINE,
  297. );
  298. }
  299. /**
  300. * ??????
  301. *
  302. * @param $errstr ????
  303. * @param int $errno ????
  304. * @return bool
  305. */
  306. function throw_error($errstr,$errno=E_LAZY_NOTICE,$errfile=null,$errline=0){
  307. global $LC_ERRNO, $LC_ERROR,$LC_ERRFILE,$LC_ERRLINE;
  308. $string = $file = null;
  309. $traces = debug_backtrace();
  310. $error = $traces[0]; unset($traces[0]);
  311. $errstr = rel_root($errstr);
  312. $errfile = rel_root($errfile ? $errfile : $error['file']);
  313. $errline = rel_root($errline ? $errline : $error['line']);
  314. $LC_ERRNO = $errno; $LC_ERROR = $errstr; $LC_ERRFILE = $errfile; $LC_ERRLINE = $errline;
  315. if (error_reporting() === 0) return false;
  316. foreach($traces as $i=>$trace) {
  317. $file = isset($trace['file']) ? rel_root($trace['file']) : $file;
  318. $line = isset($trace['line']) ? $trace['line'] : null;
  319. $class = isset($trace['class']) ? $trace['class'] : null;
  320. $type = isset($trace['type']) ? $trace['type'] : null;
  321. $args = isset($trace['args']) ? $trace['args'] : null;
  322. $function = isset($trace['function']) ? $trace['function'] : null;
  323. $string .= "\t#".$i.' ['.date("y-m-d H:i:s").'] '.$file.($line?'('.$line.') ':' ');
  324. $string .= $class.$type.$function.'(';
  325. if (is_array($args)) {
  326. $arrs = array();
  327. foreach ($args as $v) {
  328. if (is_object($v)) {
  329. $arrs[] = implode(' ',get_object_vars($v));
  330. } else {
  331. $error_level = error_reporting(0);
  332. $vars = print_r($v,true);
  333. error_reporting($error_level);
  334. while (strpos($vars,chr(32).chr(32))!==false) {
  335. $vars = str_replace(chr(32).chr(32),chr(32),$vars);
  336. }
  337. $arrs[] = $vars;
  338. }
  339. }
  340. $string.= str_replace("\n",'',implode(', ',$arrs));
  341. }
  342. $string.=")\r\n";
  343. }
  344. $log = "[Message]:\r\n\t{$errstr}\r\n";
  345. $log.= "[File]:\r\n\t{$errfile} ({$errline})\r\n";
  346. $log.= $string?"[Trace]:\r\n{$string}\r\n":'';
  347. // ????
  348. error_log($log, 3, ABS_PATH.'/error.log');
  349. // ????
  350. switch ($errno) {
  351. case E_LAZY_ERROR:
  352. // ?????
  353. if (IS_CLI) $html = $log;
  354. else {
  355. // ????HTML
  356. $html = str_replace("\t",str_repeat('&nbsp; ',2),nl2br(esc_html($log)));
  357. // ??ajax???????HTML????
  358. $html = is_ajax() ? $html : error_page(__('System Error'),$html,true);
  359. }
  360. // ????????????
  361. echo $html; exit();
  362. break;
  363. case E_LAZY_WARNING: case E_LAZY_NOTICE:
  364. // ?????
  365. if (IS_CLI) $html = $log;
  366. else {
  367. // ????HTML
  368. $html = str_replace("\t",str_repeat('&nbsp; ',2),nl2br(esc_html($log)));
  369. // ??ajax???????HTML????
  370. $html = is_ajax() ? $html : error_page(__('System Error'),$html,true);
  371. }
  372. echo $html;
  373. break;
  374. default: break;
  375. }
  376. return false;
  377. }
  378. /**
  379. * jQuery
  380. *
  381. * @param string $js
  382. * @return string
  383. */
  384. function jQuery($js) {
  385. if (!headers_sent())
  386. header('Content-Type: application/javascript; charset=utf-8');
  387. return sprintf('jQuery && (function($) { %s })(jQuery);', $js);
  388. }
  389. /**
  390. * ??ajax???json???
  391. *
  392. * @param string $code
  393. * @param mixed $data
  394. * @param string $eval
  395. * @return void
  396. */
  397. function ajax_echo($code,$data,$eval=null){
  398. if ($code) header('X-LazyCMS-Code: '.$code);
  399. if ($eval) header('X-LazyCMS-Eval: '.$eval);
  400. // ??JSON??
  401. if (is_accept_json()) {
  402. header('Content-Type: application/json; charset=utf-8');
  403. echo json_encode($data);
  404. }
  405. elseif (!is_scalar($data)) {
  406. echo json_encode($data);
  407. }
  408. else {
  409. echo $data;
  410. }
  411. exit();
  412. }
  413. /**
  414. * ajax confirm
  415. *
  416. * @param string $message ????
  417. * @param string $submit ?????????
  418. * @param string $cancel ?????????
  419. * @return void
  420. */
  421. function ajax_confirm($message,$submit,$cancel=null) {
  422. if ($submit) header('X-LazyCMS-Submit: '.$submit);
  423. if ($cancel) header('X-LazyCMS-Cancel: '.$cancel);
  424. return ajax_echo('Confirm',$message);
  425. }
  426. function ajax_alert($message,$eval=null){
  427. return ajax_echo('Alert',$message,$eval);
  428. }
  429. function ajax_success($message,$eval=null){
  430. return ajax_echo('Success',$message,$eval);
  431. }
  432. function ajax_error($message,$eval=null){
  433. return ajax_echo('Error',$message,$eval);
  434. }
  435. function ajax_return($data) {
  436. return ajax_echo('Return', $data);
  437. }
  438. /**
  439. * ????
  440. *
  441. * @param bool $state
  442. * @return string
  443. */
  444. function test_result($state) {
  445. return $state ? '<strong style="color:#009900;">&radic;</strong>' : '<strong style="color:#FF0000;">&times;</strong>';
  446. }
  447. /**
  448. * ?????IP
  449. *
  450. * @return string
  451. */
  452. function get_ip() {
  453. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  454. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  455. } elseif (isset($_SERVER['HTTP_X_REAL_IP'])) {
  456. $ip = $_SERVER['HTTP_X_REAL_IP'];
  457. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  458. $ip = $_SERVER['HTTP_CLIENT_IP'];
  459. } else {
  460. $ip = $_SERVER['REMOTE_ADDR'];
  461. }
  462. return $ip;
  463. }
  464. /**
  465. * ???????
  466. */
  467. function no_cache(){
  468. header("Expires:".date("D,d M Y H:i:s",time()-60*10)." GMT");
  469. header("Last-Modified:".date("D,d M Y H:i:s")." GMT");
  470. header("Cache-Control:no-cache,must-revalidate");
  471. header("Pragma:no-cache");
  472. }
  473. /**
  474. * ????
  475. *
  476. * @param $content
  477. * @return mixed
  478. */
  479. function clear_space($content){
  480. if (strlen($content)==0) return $content; $r = $content;
  481. $r = str_replace(array(chr(9),chr(10),chr(13)),'',$r);
  482. while (strpos($r,chr(32).chr(32))!==false || strpos($r,'&nbsp;')!==false) {
  483. $r = str_replace(chr(32).chr(32),chr(32),str_replace('&nbsp;',chr(32),$r));
  484. }
  485. return $r;
  486. }
  487. /**
  488. * ??????????
  489. *
  490. * @param mixed $needle ????????
  491. * @param string|array $haystack ?????????????“??”?????
  492. * @return bool
  493. */
  494. function instr($needle,$haystack){
  495. if (empty($haystack)) { return false; }
  496. if (!is_array($haystack)) $haystack = explode(',',$haystack);
  497. return in_array($needle,$haystack);
  498. }
  499. /**
  500. * ????
  501. *
  502. * @param string $url
  503. * @param int $time
  504. * @param string $msg
  505. * @return void
  506. */
  507. function redirect($url,$time=0,$msg='') {
  508. // ??URL????
  509. $url = str_replace(array("\n", "\r"), '', $url);
  510. if (empty($msg)) $msg = sprintf(__('<a href="%1$s">%2$d seconds after goto %1$s.</a>'),$url,$time);
  511. if (!headers_sent()) header("Content-Type:text/html; charset=utf-8");
  512. if (is_ajax()) {
  513. $data = array('Location' => $url);
  514. if ($time) $data = array_merge($data,array('Time' => $time));
  515. if ($time && $msg) $data = array_merge($data,array('Message' => $msg));
  516. ajax_echo('Redirect',$data);
  517. } else {
  518. if (!headers_sent()) {
  519. if(0===intval($time)) {
  520. header("Location: {$url}");
  521. }
  522. }
  523. $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
  524. $html.= '<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
  525. $html.= '<meta http-equiv="refresh" content="'.$time.';url='.$url.'" />';
  526. $html.= '<title>'.__('Redirecting...').'</title>';
  527. $html.= '<script type="text/javascript" charset="utf-8">';
  528. $html.= 'window.setTimeout(function(){location.replace("'.esc_js($url).'");}, '.($time*1000).');';
  529. $html.= '</script>';
  530. $html.= '</head><body>';
  531. $html.= 0===$time ? null : $msg;
  532. $html.= '</body></html>';
  533. exit($html);
  534. }
  535. }
  536. /**
  537. * ??????
  538. *
  539. * @param string $default
  540. * @param bool $back_server_referer ??????
  541. * @return string
  542. */
  543. function referer($default='',$back_server_referer=true){
  544. $default = $default?$default:ROOT;
  545. $referer = isset($_REQUEST['referer'])?$_REQUEST['referer']:null;
  546. if ($back_server_referer) {
  547. if(empty($referer) && isset($_SERVER['HTTP_REFERER'])) {
  548. $referer = $_SERVER['HTTP_REFERER'];
  549. } else {
  550. $referer = esc_html($referer);
  551. }
  552. } else {
  553. if(empty($referer)) {
  554. $referer = $default;
  555. } else {
  556. $referer = esc_html($referer);
  557. }
  558. }
  559. if(strpos($referer, 'login.php')!==false) $referer = $default;
  560. return $referer;
  561. }
  562. /**
  563. * ??????????????????????????
  564. *
  565. * @param string $path
  566. * @return string ???????????????
  567. */
  568. function rel_root($path){
  569. $abs_path = str_replace(DIRECTORY_SEPARATOR,'/',ABS_PATH.DIRECTORY_SEPARATOR);
  570. $src_path = str_replace(DIRECTORY_SEPARATOR,'/',$path);
  571. return str_replace($abs_path, (IS_CLI ? '/' : ROOT), $src_path);
  572. }
  573. /**
  574. * ??sql??
  575. *
  576. * @param $str
  577. * @return string
  578. */
  579. function esc_sql($str) {
  580. return get_conn()->escape($str);
  581. }
  582. /**
  583. * ???????HTML??
  584. *
  585. * @param string $str
  586. * @return string
  587. */
  588. function esc_html($str){
  589. if(empty($str)) {
  590. return $str;
  591. } elseif (is_array($str)) {
  592. $str = array_map('esc_html', $str);
  593. } elseif (is_object($str)) {
  594. $vars = get_object_vars($str);
  595. foreach ($vars as $key=>$data) {
  596. $str->{$key} = esc_html($data);
  597. }
  598. } else {
  599. $str = htmlspecialchars($str);
  600. }
  601. return $str;
  602. }
  603. /**
  604. * Escapes strings to be included in javascript
  605. *
  606. * @param string $str
  607. * @return mixed
  608. */
  609. function esc_js($str) {
  610. return preg_replace('/([^ :!#$%@()*+,-.\x30-\x5b\x5d-\x7e])/e',
  611. "'\\x'.(ord('\\1')<16? '0': '').dechex(ord('\\1'))", $str);
  612. }
  613. /**
  614. * ?????
  615. *
  616. * @param array $input array('a'=>0.5,'b'=>0.2,'c'=>0.4)
  617. * @param int $pow ?????
  618. * @return array key
  619. */
  620. function random($input, $pow = 2) {
  621. $much = pow(10, $pow);
  622. $max = array_sum($input) * $much;
  623. $rand = mt_rand(1, $max);
  624. $base = 0;
  625. foreach ($input as $k => $v) {
  626. $min = $base * $much + 1;
  627. $max = ($base + $v) * $much;
  628. if ($min <= $rand && $rand <= $max) {
  629. return $k;
  630. } else {
  631. $base += $v;
  632. }
  633. }
  634. return false;
  635. }
  636. /**
  637. * ?????
  638. *
  639. * @param int $length
  640. * @param string $charlist
  641. * @return string
  642. */
  643. function str_rand($length=6,$charlist='0123456789abcdefghijklmnopqrstopwxyz'){
  644. $charcount = strlen($charlist); $str = null;
  645. for ($i=0;$i<$length;$i++) {
  646. $str.= $charlist[mt_rand(0,$charcount-1)];
  647. }
  648. return $str;
  649. }
  650. /**
  651. * ????XML
  652. *
  653. * @param string $content
  654. * @return mixed
  655. */
  656. function xmlencode($content){
  657. if (strlen($content) == 0) return $content;
  658. return str_replace(
  659. array('&',"'",'"','>','<'),
  660. array('&amp;','&apos;','&quot;','&gt;','&lt;'),
  661. $content
  662. );
  663. }
  664. /**
  665. * XMLdecode
  666. *
  667. * @param string $content
  668. * @return mixed
  669. */
  670. function xmldecode($content){
  671. if (strlen($content) == 0) return $content;
  672. return str_replace(
  673. array('&amp;','&apos;','&quot;','&gt;','&lt;'),
  674. array('&',"'",'"','>','<'),
  675. $content
  676. );
  677. }
  678. /**
  679. * ?????UTF-8??
  680. *
  681. * @param string
  682. * @return bool
  683. */
  684. function is_utf8($str){
  685. return preg_match('%^(?:
  686. [\x09\x0A\x0D\x20-\x7E] # ASCII
  687. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  688. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  689. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  690. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  691. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  692. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  693. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  694. )*$%xs',$str);
  695. }
  696. /**
  697. * ?????ajax??
  698. *
  699. * @return bool
  700. */
  701. function is_ajax(){
  702. return (isset($_SERVER['HTTP_X_REQUESTED_WITH'])?$_SERVER['HTTP_X_REQUESTED_WITH']:null)=='XMLHttpRequest';
  703. }
  704. /**
  705. * ??????
  706. *
  707. * @param array $array
  708. * @return bool
  709. */
  710. function is_assoc($array) {
  711. return (is_array($array) && (0 !== count(array_diff_key($array, array_keys(array_keys($array)))) || count($array)==0));
  712. }
  713. /**
  714. * ??????????
  715. *
  716. * @param mixed $data Value to check to see if was serialized.
  717. * @return bool
  718. */
  719. function is_serialized($data) {
  720. // if it isn't a string, it isn't serialized
  721. if (!is_string($data))
  722. return false;
  723. $data = trim($data);
  724. if ('N;' == $data)
  725. return true;
  726. if (!preg_match('/^([adObis]):/', $data, $badions))
  727. return false;
  728. switch ($badions[1]) {
  729. case 'a' :
  730. case 'O' :
  731. case 's' :
  732. if (preg_match("/^{$badions[1]}:[0-9]+:.*[;}]\$/s", $data))
  733. return true;
  734. break;
  735. case 'b' :
  736. case 'i' :
  737. case 'd' :
  738. if (preg_match("/^{$badions[1]}:[0-9.E-]+;\$/", $data))
  739. return true;
  740. break;
  741. }
  742. return false;
  743. }
  744. /**
  745. * ??????JSON??
  746. *
  747. * @return bool
  748. */
  749. function is_accept_json() {
  750. return strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/json')!==false;
  751. }
  752. /**
  753. * ????json
  754. *
  755. * @param string $string
  756. * @return bool
  757. */
  758. function is_json($string){
  759. return preg_match('/^("(\\.|[^"\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/',$string);
  760. }
  761. /**
  762. * stripslashes ??
  763. *
  764. * @param array $value ??????
  765. * @return mixed
  766. */
  767. function stripslashes_deep($value) {
  768. if (is_array($value)) {
  769. $value = array_map('stripslashes_deep', $value);
  770. } elseif (is_object($value)) {
  771. $vars = get_object_vars($value);
  772. foreach ($vars as $key=>$data) {
  773. $value->{$key} = stripslashes_deep($data);
  774. }
  775. } else {
  776. $value = stripslashes($value);
  777. }
  778. return $value;
  779. }
  780. /**
  781. * ????
  782. *
  783. * @param string $content ???????
  784. * @param int $level ???????3?????????
  785. * @param bool $force_gzip ????gzip???true
  786. */
  787. function ob_compress($content,$level=3,$force_gzip=false){
  788. if (strlen($content)>2048
  789. && false == headers_sent()
  790. && false == ini_get('zlib.output_compression')
  791. && 'ob_gzhandler' != ini_get('output_handler')) {
  792. header('Vary: Accept-Encoding'); // Handle proxies
  793. if ( false !== strpos( strtolower($_SERVER['HTTP_ACCEPT_ENCODING']), 'deflate')
  794. && function_exists('gzdeflate')
  795. && ! $force_gzip ) {
  796. header('Content-Encoding: deflate');
  797. $content = gzdeflate( $content, $level );
  798. } elseif ( false !== strpos( strtolower($_SERVER['HTTP_ACCEPT_ENCODING']), 'gzip')
  799. && function_exists('gzencode') ) {
  800. header('Content-Encoding: gzip');
  801. $content = gzencode( $content, $level );
  802. }
  803. header("Content-Length: ".strlen($content));
  804. }
  805. return $content;
  806. }
  807. /**
  808. * ?????????
  809. *
  810. * $start,$end,$clear ????????“/”?????????
  811. * $clear ????
  812. *
  813. * @param string $content ??
  814. * @param string $start ????
  815. * @param string $end ????
  816. * @param string|array $clear ????
  817. * @return string
  818. */
  819. function mid($content,$start,$end=null,$clear=null){
  820. if (empty($content) || empty($start)) return null;
  821. if ( strncmp($start, '/', 1) === 0) {
  822. if (preg_match($start, $content, $args)) {
  823. $start = $args[0];
  824. }
  825. }
  826. if ( $end && strncmp($end, '/', 1) === 0 ) {
  827. if (preg_match($end, $content, $args)) {
  828. $end = $args[0];
  829. }
  830. }
  831. $start_len = strlen($start); $result = null;
  832. $start_pos = stripos($content,$start); if ($start_pos === false) return null;
  833. $length = $end===null ? null : stripos(substr($content,-(strlen($content)-$start_pos-$start_len)),$end);
  834. if ($start_pos !== false) {
  835. if ($length === null) {
  836. $result = trim(substr($content, $start_pos + $start_len));
  837. } else {
  838. $result = trim(substr($content, $start_pos + $start_len, $length));
  839. }
  840. }
  841. if ($result && $clear) {
  842. if (is_array($clear)) {
  843. foreach ($clear as $v) {
  844. if ( strncmp($v, '/', 1) === 0 ) {
  845. $result = preg_replace($v, '', $result);
  846. } else {
  847. if (strpos($result, $v) !== false) {
  848. $result = str_replace($v, '', $result);
  849. }
  850. }
  851. }
  852. } else {
  853. if ( strncmp($clear, '/', 1) === 0 ) {
  854. $result = preg_replace($clear, '', $result);
  855. } else {
  856. if (strpos($result,$clear) !== false) {
  857. $result = str_replace($clear, '', $result);
  858. }
  859. }
  860. }
  861. }
  862. return $result;
  863. }
  864. /**
  865. * ???URL??
  866. *
  867. * ??url???????
  868. *
  869. * @param string $base ????
  870. * @param string $html html??
  871. * @return string
  872. */
  873. function format_url($base, $html) {
  874. if (preg_match_all('/<(img|script)[^>]+src=([^\s]+)[^>]*>|<(a|link)[^>]+href=([^\s]+)[^>]*>/iU', $html, $matchs)) {
  875. $pase_url = parse_url($base);
  876. $base_host = sprintf('%s://%s', $pase_url['scheme'], $pase_url['host']);
  877. if (($pos=strpos($pase_url['path'], '#')) !== false) {
  878. $base_path = rtrim(dirname(substr($pase_url['path'], 0, $pos)), '\\/');
  879. } else {
  880. $base_path = rtrim(dirname($pase_url['path']), '\\/');
  881. }
  882. $base_url = $base_host.$base_path;
  883. foreach($matchs[0] as $match) {
  884. if (preg_match('/^(.+(href|src)=)([^ >]+)(.+?)$/i', $match, $args)) {
  885. $url = trim(trim($args[3],'"'),"'");
  886. // http ?????
  887. if (preg_match('/^(http|https|ftp)\:\/\//i', $url)) continue;
  888. // ?????javascript
  889. if (strncasecmp($url, 'mailto:', 7)===0 || strncasecmp($url, 'javascript:', 11)===0) continue;
  890. // ????
  891. if (strncmp($url, '/', 1) === 0) {
  892. $url = $base_host.$url;
  893. }
  894. // ????
  895. elseif (strncmp($url, '../', 3) === 0) {
  896. while (strncmp($url, '../', 3) === 0) {
  897. $url = substr($url, -(strlen($url)-3));
  898. if(strlen($base_path) > 0){
  899. $base_path = dirname($base_path);
  900. }
  901. if ($url == '../') {
  902. $url = ''; break;
  903. }
  904. }
  905. $url = $base_host.$base_path.'/'.$url;
  906. }
  907. // ????
  908. elseif (strncmp($url, './', 2) === 0) {
  909. $url = $base_url.'/'.substr($url, 2);
  910. }
  911. // ??
  912. else {
  913. $url = $base_url.'/'.$url;
  914. }
  915. // ????
  916. $html = str_replace($match, sprintf('%s"%s"%s', $args[1], $url, $args[4]), $html);
  917. }
  918. }
  919. }
  920. return $html;
  921. }
  922. /**
  923. * ?????
  924. *
  925. * @param int $bytes
  926. * @return string
  927. */
  928. function format_size($bytes){
  929. if ($bytes == 0) return '-';
  930. $units = array('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB');
  931. $i = 0; while ($bytes >= 1024) { $bytes /= 1024; $i++; }
  932. $precision = $i == 0 ? 0 : 2;
  933. return number_format(round($bytes, $precision), $precision) . ' ' . $units[$i];
  934. }
  935. /**
  936. * ??????
  937. *
  938. * @param string $string
  939. * @param int $start
  940. * @param int $end
  941. * @return bool|string
  942. */
  943. function substring($string, $start, $end=null) {
  944. if ($end === null) {
  945. return substr($string, $start);
  946. } elseif($end > $start) {
  947. return substr($string, $start, $end - $start);
  948. } else {
  949. return false;
  950. }
  951. }
  952. /**
  953. * IP??????
  954. *
  955. * @param string $ip
  956. * @return string
  957. */
  958. function ip2addr($ip) {
  959. static $QQWry;
  960. if ( is_null($QQWry) ) {
  961. include_file(COM_PATH.'/system/qqwry.php');
  962. $QQWry = new QQWry(COM_PATH.'/QQWry.Dat');
  963. }
  964. return $QQWry->ip2addr($ip);
  965. }
  966. /**
  967. * ?????
  968. *
  969. * @param string $image
  970. * @param int $max_w
  971. * @param int $max_h
  972. * @param null $toname
  973. * @return bool|null
  974. */
  975. function image_thumb($image, $max_w=100, $max_h=100, $toname=null) {
  976. if (!class_exists('Image')) {
  977. include_file(COM_PATH.'/system/image.php');
  978. }
  979. return Image::thumb($image, $max_w, $max_h, $toname);
  980. }
  981. /**
  982. * jsmin
  983. *
  984. * @param string $js
  985. * @return string
  986. */
  987. function jsmin($js) {
  988. if (!class_exists('JSMin')) {
  989. include_file(COM_PATH.'/system/jsmin.php');
  990. }
  991. return JSMin::minify($js);
  992. }
  993. /**
  994. * ????
  995. *
  996. * @param string $str
  997. * @param bool $ucfirst ?????
  998. * @return string
  999. */
  1000. function pinyin($str, $ucfirst=true) {
  1001. if (!function_exists('_pinyin_get_object')) {
  1002. include_file(COM_PATH.'/system/pinyin.php');
  1003. }
  1004. $pinyin = _pinyin_get_object();
  1005. return $pinyin->encode($str, $ucfirst);
  1006. }
  1007. /**
  1008. * ????
  1009. *
  1010. * @param string $url $ ??????
  1011. * @param string $mode ??????
  1012. * @param int $page ????
  1013. * @param int $total ???
  1014. * @param int $length ??????
  1015. * @return string
  1016. */
  1017. function pages_list($url,$mode='$',$page=null,$total=null,$length=null) {
  1018. if (!function_exists('_pages_get_object')) {
  1019. include_file(COM_PATH.'/system/pages.php');
  1020. }
  1021. $pages = _pages_get_object();
  1022. if ($page !== null) $pages->page = $page;
  1023. if ($total !== null) $pages->pages = $total;
  1024. if ($length !== null) $pages->length = $length;
  1025. return $pages->page_list($url, $mode);
  1026. }
  1027. /**
  1028. * ??HTTP?????
  1029. *
  1030. * @param int $code HTTP status code.
  1031. * @return string Empty string if not found, or description if found.
  1032. */
  1033. function http_status_desc($code) {
  1034. if (!function_exists('_httplib_get_object')) {
  1035. include_file(COM_PATH.'/system/httplib.php');
  1036. }
  1037. $http = _httplib_get_object();
  1038. return $http->status_desc($code);
  1039. }
  1040. /**
  1041. * ????
  1042. *
  1043. * @param string $timezone
  1044. * @return bool
  1045. */
  1046. function time_zone_set($timezone) {
  1047. if (!function_exists('_timezone_get_object')) {
  1048. include_file(COM_PATH.'/system/timezone.php');
  1049. }
  1050. $zone = _timezone_get_object();
  1051. return $zone->set_zone($timezone);
  1052. }
  1053. /**
  1054. * ???????
  1055. *
  1056. * @return array
  1057. */
  1058. function time_zone_group() {
  1059. if (!function_exists('_timezone_get_object')) {
  1060. include_file(COM_PATH.'/system/timezone.php');
  1061. }
  1062. $zone = _timezone_get_object();
  1063. return $zone->get_group();
  1064. }
  1065. /**
  1066. * ??????
  1067. *
  1068. * @param string $func
  1069. * @param mixed $args
  1070. * @return bool
  1071. */
  1072. function func_add_callback() {
  1073. global $LC_func_callback;
  1074. if (!is_array($LC_func_callback))
  1075. $LC_func_callback = array();
  1076. $args = func_get_args();
  1077. $func = array_shift($args);
  1078. $LC_func_callback[] = array(
  1079. 'func' => $func,
  1080. 'args' => $args,
  1081. );
  1082. return true;
  1083. }
  1084. /**
  1085. * ??
  1086. *
  1087. * @param string $email
  1088. * @param int $size
  1089. * @param string $default
  1090. * @return string
  1091. */
  1092. function get_avatar($email, $size=96, $default='') {
  1093. if ( !empty($email) )
  1094. $email_hash = md5( strtolower( $email ) );
  1095. if ( !empty($email) )
  1096. $host = sprintf( "http://%d.gravatar.com", ( hexdec( $email_hash{0} ) % 2 ) );
  1097. else
  1098. $host = 'http://0.gravatar.com';
  1099. if ( 'mystery' == $default )
  1100. $default = "{$host}/avatar/ad516503a11cd5ca435acc9bb6523536.gif?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5('unknown@gravatar.com')
  1101. elseif ( 'blank' == $default )
  1102. $default = HTTP_HOST.ROOT.'common/images/blank.gif';
  1103. elseif ( empty($email) )
  1104. $default = "{$host}/avatar/00000000000000000000000000000000.gif?d={$default}&amp;s={$size}";
  1105. if ( !empty($email) ) {
  1106. $result = "{$host}/avatar/{$email_hash}.gif?s={$size}&amp;d=".urlencode( $default )."&amp;r=g";
  1107. } else {
  1108. $result = $default;
  1109. }
  1110. return $result;
  1111. }
  1112. /**
  1113. * ???
  1114. *
  1115. * @param string $name
  1116. * @param string $alt
  1117. * @return string
  1118. */
  1119. function get_icon($name,$alt='') {
  1120. switch ($name) {
  1121. case 'passed': $name = 'b8'; break;
  1122. case 'draft': $name = 'b9'; break;
  1123. case 'enabled': $name = 'c3'; break;
  1124. case 'disabled': $name = 'c4'; break;
  1125. }
  1126. return '<img src="'.ROOT.'common/images/blank.gif" class="os '.$name.'" alt="'.$alt.'" />';
  1127. }
  1128. /**
  1129. * ?????????????????
  1130. *
  1131. * @param string $path ??
  1132. * @param string $ext ????
  1133. * @return array
  1134. */
  1135. function get_dir_array($path,$ext='*'){
  1136. $path = str_replace(array('.','[',']'),array(DIRECTORY_SEPARATOR,'*','*'),$path);
  1137. if (!strncasecmp($path,'@',1)) {
  1138. $path = str_replace('@',COM_PATH,$path);
  1139. } else {
  1140. $path = ABS_PATH.DIRECTORY_SEPARATOR.$path;
  1141. }
  1142. $process_func = create_function('&$path,$ext','$path=substr($path,strrpos($path,"/")+1);');
  1143. if (!substr_compare($path,'/',strlen($path)-1,1)===false) $path .= '/';
  1144. $result = ($ext=='dir') ? glob("{$path}*",GLOB_ONLYDIR) : glob("{$path}*.{{$ext}}",GLOB_BRACE);
  1145. array_walk($result,$process_func);
  1146. return $result;
  1147. }
  1148. /**
  1149. * ??????
  1150. *
  1151. * @return bool
  1152. */
  1153. function include_modules() {
  1154. static $loaded; if ($loaded) return true;
  1155. // ???????
  1156. include_file(COM_PATH.'/system/template.php');
  1157. // ?????
  1158. include_file(COM_PATH.'/system/pages.php');
  1159. // ??????
  1160. $modules = get_dir_array('@/module','php');
  1161. foreach ($modules as $file) {
  1162. include_file(COM_PATH.'/module/'.$file);
  1163. }
  1164. // ??????
  1165. global $LC_func_callback;
  1166. if ($LC_func_callback) {
  1167. foreach ((array)$LC_func_callback as $call) {
  1168. if (function_exists($call['func'])) call_user_func_array($call['func'], $call['args']);
  1169. }
  1170. }
  1171. $loaded = true; return true;
  1172. }
  1173. /**
  1174. * ????????
  1175. *
  1176. * @param string $path ??
  1177. * @param string $ext ??
  1178. * @param string $html html??? ???????#value#,#name#,#selected#
  1179. * @param string $selected selected
  1180. */
  1181. function options($path,$ext,$html,$selected=null){
  1182. $type = $ext=='lang' ? 'mo' : $ext;
  1183. $dirs = get_dir_array($path,$type); $result = null;
  1184. if (strpos($html,'%23')!==false) { $html = str_replace('%23','#',$html); }
  1185. foreach ($dirs as $v) {
  1186. if ($ext=='lang') {
  1187. $v = basename($v,'.mo');
  1188. $val = code2lang($v);
  1189. } else{
  1190. $val = $v;
  1191. }
  1192. $opt = $html;
  1193. if (strpos($opt,'#value#')!==false) { $opt = str_replace('#value#',$v,$opt); }
  1194. if (strpos($opt,'#name#')!==false) { $opt = str_replace('#name#',$val,$opt); }
  1195. if ($selected==$v) {
  1196. $opt = str_replace('#selected#',' selected="selected"',$opt);
  1197. } else{
  1198. $opt = str_replace('#selected#','',$opt);
  1199. }
  1200. $result.= $opt;
  1201. }
  1202. return $result;
  1203. }
  1204. /**
  1205. * ??????? ??????
  1206. *
  1207. * @param string $from
  1208. * @param string $to
  1209. * @param mixed $data
  1210. * @return mixed
  1211. */
  1212. function iconvs($from,$to,$data){
  1213. $from = strtoupper($from)=='UTF8'? 'UTF-8':$from;
  1214. $to = strtoupper($to)=='UTF8'? 'UTF-8':$to;
  1215. if ( strtoupper($from) === strtoupper($to) || empty($data) || (is_scalar($data) && !is_string($data)) ){
  1216. //??????????????????
  1217. return $data;
  1218. }
  1219. if (is_string($data) ) {
  1220. if(function_exists('iconv')) {
  1221. $to = substr($to,-8)=='//IGNORE' ? $to : $to.'//IGNORE';
  1222. return iconv($from,$to,$data);
  1223. } elseif (function_exists('mb_convert_encoding')) {
  1224. return mb_convert_encoding ($data, $to, $from);
  1225. } else {
  1226. return $data;
  1227. }
  1228. }
  1229. elseif (is_array($data)){
  1230. foreach ( $data as $key => $val ) {
  1231. $_key = iconvs($from,$to,$key);
  1232. $data[$_key] = iconvs($from,$to,$val);
  1233. if ($key != $_key ) {
  1234. unset($data[$key]);
  1235. }
  1236. }
  1237. return $data;
  1238. }
  1239. else {
  1240. return $data;
  1241. }
  1242. }
  1243. /**
  1244. * ??????
  1245. *
  1246. * @param string $path ?????
  1247. * @param int $mode ??
  1248. * @return bool
  1249. */
  1250. function mkdirs($path, $mode = 0777){
  1251. if (!is_dir($path)) {
  1252. mkdirs(dirname($path), $mode);
  1253. $error_level = error_reporting(0);
  1254. $result = mkdir($path, $mode);
  1255. error_reporting($error_level);
  1256. return $result;
  1257. }
  1258. return true;
  1259. }
  1260. /**
  1261. * ?????
  1262. *
  1263. * @param string $path ?????????
  1264. * @return bool
  1265. */
  1266. function rmdirs($path){
  1267. // ????????
  1268. if ($path=='/' || realpath($path)==ABS_PATH)
  1269. return false;
  1270. $error_level = error_reporting(0);
  1271. if ($dh = opendir($path)) {
  1272. while (false !== ($file=readdir($dh))) {
  1273. if ($file != '.' && $file != '..') {
  1274. $file_path = $path.'/'.$file;
  1275. is_dir($file_path) ? rmdirs($file_path) : unlink($file_path);
  1276. }
  1277. }
  1278. closedir($dh);
  1279. }
  1280. $result = rmdir($path);
  1281. error_reporting($error_level);
  1282. return $result;
  1283. }
  1284. /**
  1285. * ?? require_once
  1286. *
  1287. * @param $path
  1288. * @return bool
  1289. */
  1290. function include_file($path){
  1291. static $paths = array();
  1292. if (is_file($path)) {
  1293. if (!isset($paths[$path])) {
  1294. include $path;
  1295. $paths[$path] = true;
  1296. return true;
  1297. }
  1298. return false;
  1299. }
  1300. return false;
  1301. }
  1302. if (!function_exists('authcode')) :
  1303. /**
  1304. * ???????CODE
  1305. *
  1306. * @param string $data
  1307. * @return string
  1308. */
  1309. function authcode($data=null){
  1310. return guid(HTTP_HOST.$data.get_ip().$_SERVER['HTTP_USER_AGENT']);
  1311. }
  1312. endif;
  1313. /**
  1314. * ??guid
  1315. *
  1316. * @param $randid ???
  1317. * @return string guid
  1318. */
  1319. function guid($mix=null){
  1320. if (is_null($mix)) {
  1321. $randid = uniqid(mt_rand(),true);
  1322. } else {
  1323. if (is_object($mix) && function_exists('spl_object_hash')) {
  1324. $randid = spl_object_hash($mix);
  1325. } elseif (is_resource($mix)) {
  1326. $randid = get_resource_type($mix).strval($mix);
  1327. } else {
  1328. $randid = serialize($mix);
  1329. }
  1330. }
  1331. $randid = strtoupper(md5($randid));
  1332. $hyphen = chr(45);
  1333. $result = array();
  1334. $result[] = substr($randid, 0, 8);
  1335. $result[] = substr($randid, 8, 4);
  1336. $result[] = substr($randid, 12, 4);
  1337. $result[] = substr($randid, 16, 4);
  1338. $result[] = substr($randid, 20, 12);
  1339. return implode($hyphen,$result);
  1340. }
  1341. /**
  1342. * ?????
  1343. *
  1344. * @param string $code ????????
  1345. * @return string
  1346. */
  1347. function code2lang($code){
  1348. $lang = array(
  1349. 'af' => __('Afrikaans'),
  1350. 'sq' => __('Albanian'),
  1351. 'ar' => __('Arabic'),
  1352. 'be' => __('Belarusian'),
  1353. 'bg' => __('Bulgarian'),
  1354. 'ca' => __('Catalan'),
  1355. 'zh-CN' => __('Chinese (Simplified)'),
  1356. 'zh-TW' => __('Chinese (Traditional)'),
  1357. 'hr' => __('Croatian'),
  1358. 'cs' => __('Czech'),
  1359. 'da' => __('Danish'),
  1360. 'nl' => __('Dutch'),
  1361. 'en' => __('English'),
  1362. 'et' => __('Estonian'),
  1363. 'tl' => __('Filipino'),
  1364. 'fi' => __('Finnish'),
  1365. 'fr' => __('French'),
  1366. 'gl' => __('Galician'),
  1367. 'de' => __('German'),
  1368. 'el' => __('Greek'),
  1369. 'iw' => __('Hebrew'),
  1370. 'hi' => __('Hindi'),
  1371. 'hu' => __('Hungarian'),
  1372. 'is' => __('Icelandic'),
  1373. 'id' => __('Indonesian'),
  1374. 'ga' => __('Irish'),
  1375. 'it' => __('Italian'),
  1376. 'ja' => __('Japanese'),
  1377. 'ko' => __('Korean'),
  1378. 'lv' => __('Latvian'),
  1379. 'lt' => __('Lithuanian'),
  1380. 'mk' => __('Macedonian'),
  1381. 'ms' => __('Malay'),
  1382. 'mt' => __('Maltese'),
  1383. 'no' => __('Norwegian'),
  1384. 'fa' => __('Persian'),
  1385. 'pl' => __('Polish'),
  1386. 'pt' => __('Portuguese'),
  1387. 'ro' => __('Romanian'),
  1388. 'ru' => __('Russian'),
  1389. 'sr' => __('Serbian'),
  1390. 'sk' => __('Slovak'),
  1391. 'sl' => __('Slovenian'),
  1392. 'es' => __('Spanish'),
  1393. 'sw' => __('Swahili'),
  1394. 'sv' => __('Swedish'),
  1395. 'th' => __('Thai'),
  1396. 'tr' => __('Turkish'),
  1397. 'uk' => __('Ukrainian'),
  1398. 'vi' => __('Vietnamese'),
  1399. 'cy' => __('Welsh'),
  1400. 'yi' => __('Yiddish'),
  1401. );
  1402. return isset($lang[$code])?$lang[$code]:$code;
  1403. }
  1404. /**
  1405. * ???????
  1406. *
  1407. * @return string
  1408. */
  1409. function language() {
  1410. $ck_lang = cookie_get('language');
  1411. $ck_lang = preg_replace( '/[^a-z0-9,_-]+/i', '', $ck_lang );
  1412. if (empty($ck_lang) && isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  1413. $ck_lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  1414. if (($pos=strpos($ck_lang,',')) !== false) {
  1415. $ck_lang = substr($ck_lang,0,$pos);
  1416. }
  1417. // ???????
  1418. if (strtolower($ck_lang) == 'zh-cn') {
  1419. $ck_lang = 'zh-CN';
  1420. } elseif (strtolower($ck_lang) == 'zh-tw') {
  1421. $ck_lang = 'zh-TW';
  1422. }
  1423. } elseif(empty($ck_lang)) {
  1424. $ck_lang = C('Language');
  1425. }
  1426. return $ck_lang;
  1427. }
  1428. /**
  1429. * ????
  1430. *
  1431. * @param string|array $key
  1432. * @param mixed $value
  1433. * @return mixed
  1434. */
  1435. function C($key,$value=null){
  1436. $ckey = 'cfg.'; $args = null;
  1437. // ????
  1438. if(is_array($key)) {
  1439. foreach ($key as $k=>$v) {
  1440. C($k,$v);
  1441. }
  1442. return true;
  1443. }
  1444. // ??key
  1445. if (strpos($key,'.')!==false) {
  1446. $args = explode('.',$key);
  1447. $module = array_shift($args);
  1448. $code = array_shift($args);
  1449. } else {
  1450. $module = 'System';
  1451. $code = $key;
  1452. }
  1453. $db = @get_conn();
  1454. $key = $module.'.'.$code;
  1455. // ??
  1456. if($key && func_num_args()==1) {
  1457. // ????????
  1458. if ($db && !$db->ready) return null;
  1459. // ???????
  1460. $value = fcache_get($ckey.$key);
  1461. if (fcache_is_null($value)) {
  1462. if ($db->is_table('#@_option')) {
  1463. $result = $db->query("SELECT `value` FROM `#@_option` WHERE `module`='%s' AND `code`='%s' LIMIT 1 OFFSET 0;",array($module,$code));
  1464. if ($data = $db->fetch($result)) {
  1465. $value = is_serialized($data['value']) ? unserialize($data['value']) : $data['value'];
  1466. // ?????
  1467. fcache_set($ckey.$key,$value);
  1468. }
  1469. }
  1470. }
  1471. // ????????
  1472. if (!empty($args) && is_array($value)) {
  1473. foreach ($args as $arg) {
  1474. $value = $value[$arg];
  1475. }
  1476. }
  1477. return $value;
  1478. }
  1479. // ????
  1480. else {
  1481. // ????
  1482. if (is_null($value)) {
  1483. fcache_delete($key);
  1484. $db->delete('#@_option',array(
  1485. 'module' => $module,
  1486. 'code' => $code,
  1487. ));
  1488. } else {
  1489. // ?????
  1490. fcache_set($ckey.$key,$value);
  1491. // ????????????
  1492. $length = (int) $db->result(vsprintf("SELECT COUNT(`id`) FROM `#@_option` WHERE `module`='%s' AND `code`='%s'",array(esc_sql($module),esc_sql($code))));
  1493. // update
  1494. if ($length > 0) {
  1495. $db->update('#@_option',array(
  1496. 'value' => $value,
  1497. ),array(
  1498. 'module' => $module,
  1499. 'code' => $code,
  1500. ));
  1501. }
  1502. // insert
  1503. else {
  1504. // ???????
  1505. $db->insert('#@_option',array(
  1506. 'module' => $module,
  1507. 'code' => $code,
  1508. 'value' => $value,
  1509. ));
  1510. }
  1511. }
  1512. return true;
  1513. }
  1514. return null;
  1515. }
  1516. if (!function_exists('json_encode')) {
  1517. function json_encode($value){
  1518. global $_json;
  1519. if (!$_json) {
  1520. include_file(COM_PATH.'/system/json.php');
  1521. $_json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
  1522. }
  1523. return $_json->encode($value);
  1524. }
  1525. }
  1526. if (!function_exists('json_decode')) {
  1527. function json_decode($json){
  1528. global $_json;
  1529. if (!$_json) {
  1530. include_file(COM_PATH.'/system/json.php');
  1531. $_json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
  1532. }
  1533. return $_json->decode($json);
  1534. }
  1535. }
  1536. if (!function_exists('mb_substr')) {
  1537. function mb_substr( $str, $start, $length=null, $encoding='UTF-8' ) {
  1538. if ( !instr( $encoding, 'utf8,utf-8,UTF8,UTF-8' ) ) {
  1539. return is_null( $length )? substr( $str, $start ) : substr( $str, $start, $length);
  1540. }
  1541. if (function_exists('iconv_substr')){
  1542. return iconv_substr($str,$start,$length,$encoding);
  1543. }
  1544. // use the regex unicode support to separate the UTF-8 characters into an array
  1545. preg_match_all( '/./us', $str, $match );
  1546. $chars = is_null( $length )? array_slice( $match[0], $start ) : array_slice( $match[0], $start, $length );
  1547. return implode( '', $chars );
  1548. }
  1549. }
  1550. if (!function_exists('mb_strlen')) {
  1551. function mb_strlen( $str, $encoding='UTF-8' ) {
  1552. if ( !instr( $encoding, 'utf8,utf-8,UTF8,UTF-8' ) ) {
  1553. return strlen($str);
  1554. }
  1555. if (function_exists('iconv_strlen')){
  1556. return iconv_strlen($str,$encoding);
  1557. }
  1558. // use the regex unicode support to separate the UTF-8 characters into an array
  1559. preg_match_all( '/./us', $str, $match );
  1560. return count($match);
  1561. }
  1562. }
  1563. if (!function_exists('hash_hmac')){
  1564. function hash_hmac($algo, $data, $key, $raw_output = false) {
  1565. $packs = array('md5' => 'H32', 'sha1' => 'H40');
  1566. if ( !isset($packs[$algo]) )
  1567. return false;
  1568. $pack = $packs[$algo];
  1569. if (strlen($key) > 64)
  1570. $key = pack($pack, $algo($key));
  1571. else if (strlen($key) < 64)
  1572. $key = str_pad($key, 64, chr(0));
  1573. $ipad = (substr($key, 0, 64) ^ str_repeat(chr(0x36), 64));
  1574. $opad = (substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64));
  1575. return $algo($opad . pack($pack, $algo($ipad . $data)));
  1576. }
  1577. }
  1578. if (!function_exists('http_build_query')) {
  1579. // from php.net (modified by Mark Jaquith to behave like the native PHP5 function)
  1580. function http_build_query($data, $prefix=null, $sep=null, $key='', $urlencode=true) {
  1581. $ret = array();
  1582. foreach ( (array) $data as $k => $v ) {
  1583. if ( $urlencode)
  1584. $k = urlencode($k);
  1585. if ( is_int($k) && $prefix != null )
  1586. $k = $prefix.$k;
  1587. if ( !empty($key) )
  1588. $k = $key . '%5B' . $k . '%5D';
  1589. if ( $v === NULL )
  1590. continue;
  1591. elseif ( $v === FALSE )
  1592. $v = '0';
  1593. if ( is_array($v) || is_object($v) )
  1594. array_push($ret, http_build_query($v, '', $sep, $k, $urlencode));
  1595. elseif ( $urlencode )
  1596. array_push($ret, $k.'='.urlencode($v));
  1597. else
  1598. array_push($ret, $k.'='.$v);
  1599. }
  1600. if ( NULL === $sep )
  1601. $sep = ini_get('arg_separator.output');
  1602. return implode($sep, $ret);
  1603. }
  1604. }
  1605. if (!function_exists('substr_compare')) {
  1606. function substr_compare($main_str, $str, $offset

Large files files are truncated, but you can click here to view the full file