PageRenderTime 62ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/system/functions.inc.php

https://github.com/sony88/answion
PHP | 1088 lines | 890 code | 131 blank | 67 comment | 101 complexity | 2c3a98df49ae496498e83320ecd32e4d MD5 | raw file
  1. <?php
  2. /*
  3. +--------------------------------------------------------------------------
  4. | Anwsion [#RELEASE_VERSION#]
  5. | ========================================
  6. | by Anwsion dev team
  7. | (c) 2011 - 2012 Anwsion Software
  8. | http://www.anwsion.com
  9. | ========================================
  10. | Support: zhengqiang@gmail.com
  11. |
  12. +---------------------------------------------------------------------------
  13. */
  14. /**
  15. * 根据特定规则对数据进行排序
  16. *
  17. * @return array
  18. */
  19. function aasort($source_array, $order_field, $sort_type)
  20. {
  21. if (! is_array($source_array) or sizeof($source_array) == 0)
  22. {
  23. return false;
  24. }
  25. foreach ($source_array as $array_key => $array_row)
  26. {
  27. $sort_array[$array_key] = $array_row[$order_field];
  28. }
  29. $sort_func = ($sort_type == 'ASC' ? 'asort' : 'arsort');
  30. $sort_func($sort_array);
  31. // 重组数组
  32. foreach ($sort_array as $key => $val)
  33. {
  34. $sorted_array[$key] = $source_array[$key];
  35. }
  36. return $sorted_array;
  37. }
  38. /**
  39. * 获取用户 IP
  40. *
  41. * @return string
  42. */
  43. function fetch_ip()
  44. {
  45. if ($_SERVER['HTTP_X_FORWARDED_FOR'] and valid_ip($_SERVER['HTTP_X_FORWARDED_FOR']))
  46. {
  47. $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
  48. }
  49. else if ($_SERVER['REMOTE_ADDR'] and $_SERVER['HTTP_CLIENT_IP'])
  50. {
  51. $ip_address = $_SERVER['HTTP_CLIENT_IP'];
  52. }
  53. else if ($_SERVER['REMOTE_ADDR'])
  54. {
  55. $ip_address = $_SERVER['REMOTE_ADDR'];
  56. }
  57. else if ($_SERVER['HTTP_CLIENT_IP'])
  58. {
  59. $ip_address = $_SERVER['HTTP_CLIENT_IP'];
  60. }
  61. if ($ip_address === FALSE)
  62. {
  63. $ip_address = '0.0.0.0';
  64. return $ip_address;
  65. }
  66. if (strstr($ip_address, ','))
  67. {
  68. $x = explode(',', $ip_address);
  69. $ip_address = end($x);
  70. }
  71. return $ip_address;
  72. }
  73. function valid_ip($ip)
  74. {
  75. $ip_segments = explode('.', $ip);
  76. // Always 4 segments needed
  77. if (count($ip_segments) != 4)
  78. {
  79. return FALSE;
  80. }
  81. // IP can not start with 0
  82. if (substr($ip_segments[0], 0, 1) == '0')
  83. {
  84. return FALSE;
  85. }
  86. // Check each segment
  87. foreach ($ip_segments as $segment)
  88. {
  89. // IP segments must be digits and can not be
  90. // longer than 3 digits or greater then 255
  91. if (preg_match("/[^0-9]/", $segment) or $segment > 255 or strlen($segment) > 3)
  92. {
  93. return FALSE;
  94. }
  95. }
  96. return TRUE;
  97. }
  98. if (! function_exists('iconv'))
  99. {
  100. function iconv($from_encoding = 'GBK', $target_encoding = 'UTF-8', $string)
  101. {
  102. return convert_encoding($string, $from_encoding, $target_encoding);
  103. }
  104. }
  105. if (! function_exists('iconv_substr'))
  106. {
  107. function iconv_substr($string, $start, $length, $charset = 'UTF-8')
  108. {
  109. return mb_substr($string, $start, $length, $charset);
  110. }
  111. }
  112. if (! function_exists('iconv_strpos'))
  113. {
  114. function iconv_strpos($haystack, $needle, $offset = 0, $charset = 'UTF-8')
  115. {
  116. return mb_strpos($haystack, $needle, $offset, $charset);
  117. }
  118. }
  119. function convert_encoding($string, $from_encoding = 'GBK', $target_encoding = 'UTF-8')
  120. {
  121. if (function_exists('mb_convert_encoding'))
  122. {
  123. return mb_convert_encoding($string, str_replace('//IGNORE', '', strtoupper($target_encoding)), $from_encoding);
  124. }
  125. else
  126. {
  127. if (strtoupper($target_encoding) == 'GB2312' or strtoupper($target_encoding) == 'GBK')
  128. {
  129. $target_encoding .= '//IGNORE';
  130. }
  131. return iconv($from_encoding, $target_encoding, $string);
  132. }
  133. }
  134. function cjk_strpos($haystack, $needle, $offset = 0, $charset = 'UTF-8')
  135. {
  136. if (function_exists('iconv_strpos'))
  137. {
  138. return iconv_strpos($haystack, $needle, $offset, $charset);
  139. }
  140. return mb_strpos($haystack, $needle, $offset, $charset);
  141. }
  142. function cjk_substr($string, $start, $length, $charset = 'UTF-8', $dot = '')
  143. {
  144. if (cjk_strlen($string, $charset) <= $length)
  145. {
  146. return $string;
  147. }
  148. if (function_exists('mb_substr'))
  149. {
  150. return mb_substr($string, $start, $length, $charset) . $dot;
  151. }
  152. else
  153. {
  154. return iconv_substr($string, $start, $length, $charset) . $dot;
  155. }
  156. }
  157. function cjk_strlen($string, $charset = 'UTF-8')
  158. {
  159. if (function_exists('mb_strlen'))
  160. {
  161. return mb_strlen($string, $charset);
  162. }
  163. else
  164. {
  165. return iconv_strlen($string, $charset);
  166. }
  167. }
  168. function make_dir($dir, $mode = 0777)
  169. {
  170. $dir = rtrim($dir, '/') . '/';
  171. if (is_dir($dir))
  172. {
  173. return TRUE;
  174. }
  175. if (! make_dir(dirname($dir), $mode))
  176. {
  177. return FALSE;
  178. }
  179. return @mkdir($dir, $mode);
  180. }
  181. /**
  182. * 获取头像目录文件地址
  183. */
  184. function get_avatar_url($uid, $size = 'min')
  185. {
  186. $uid = intval($uid);
  187. if ($uid < 1)
  188. {
  189. return G_STATIC_URL . '/common/avatar-' . $size . '-img.jpg';
  190. }
  191. foreach (AWS_APP::config()->get('image')->avatar_thumbnail as $key => $val)
  192. {
  193. $all_size[] = $key;
  194. }
  195. $size = in_array($size, $all_size) ? $size : $all_size[0];
  196. $uid = abs(intval($uid));
  197. $uid = sprintf("%09d", $uid);
  198. $dir1 = substr($uid, 0, 3);
  199. $dir2 = substr($uid, 3, 2);
  200. $dir3 = substr($uid, 5, 2);
  201. if (file_exists(get_setting('upload_dir') . '/avatar/' . $dir1 . '/' . $dir2 . '/' . $dir3 . '/' . substr($uid, - 2) . "_avatar_$size.jpg"))
  202. {
  203. return get_setting('upload_url') . '/avatar/' . $dir1 . '/' . $dir2 . '/' . $dir3 . '/' . substr($uid, - 2) . "_avatar_$size.jpg";
  204. }
  205. else
  206. {
  207. return G_STATIC_URL . '/common/avatar-' . $size . '-img.jpg';
  208. }
  209. }
  210. function jsonp_encode($json = array(), $callback = 'jsoncallback')
  211. {
  212. if ($_GET[$callback])
  213. {
  214. return $_GET[$callback] . '(' . json_encode($json) . ')';
  215. }
  216. return json_encode($json);
  217. }
  218. function download_url($file_name, $url)
  219. {
  220. $file_name = trim($file_name);
  221. $url = trim($url);
  222. if (! $file_name || ! $url)
  223. {
  224. return false;
  225. }
  226. return get_js_url('file/download/file_name-' . base64_encode($file_name) . '__url-' . base64_encode($url));
  227. }
  228. function date_friendly($timestamp, $time_limit = 604800, $out_format = 'Y-m-d H:i', $formats = null, $time_now = null)
  229. {
  230. if (get_setting('time_style') == 'N')
  231. {
  232. return date($out_format, $timestamp);
  233. }
  234. if ($formats == null)
  235. {
  236. $formats = array('YEAR' => '%s 年前', 'MONTH' => '%s 月前', 'DAY' => '%s 天前', 'HOUR' => '%s 小时前', 'MINUTE' => '%s 分钟前', 'SECOND' => '%s 秒前');
  237. }
  238. $time_now = $time_now == null ? time() : $time_now;
  239. $seconds = $time_now - $timestamp;
  240. if ($seconds == 0)
  241. {
  242. $seconds = 1;
  243. }
  244. if ($time_limit != null && $seconds > $time_limit)
  245. {
  246. return date($out_format, $timestamp);
  247. }
  248. $minutes = floor($seconds / 60);
  249. $hours = floor($minutes / 60);
  250. $days = floor($hours / 24);
  251. $months = floor($days / 30);
  252. $years = floor($months / 12);
  253. if ($years > 0)
  254. {
  255. $diffFormat = 'YEAR';
  256. }
  257. else
  258. {
  259. if ($months > 0)
  260. {
  261. $diffFormat = 'MONTH';
  262. }
  263. else
  264. {
  265. if ($days > 0)
  266. {
  267. $diffFormat = 'DAY';
  268. }
  269. else
  270. {
  271. if ($hours > 0)
  272. {
  273. $diffFormat = 'HOUR';
  274. }
  275. else
  276. {
  277. $diffFormat = ($minutes > 0) ? 'MINUTE' : 'SECOND';
  278. }
  279. }
  280. }
  281. }
  282. $dateDiff = null;
  283. switch ($diffFormat)
  284. {
  285. case 'YEAR' :
  286. $dateDiff = sprintf($formats[$diffFormat], $years);
  287. break;
  288. case 'MONTH' :
  289. $dateDiff = sprintf($formats[$diffFormat], $months);
  290. break;
  291. case 'DAY' :
  292. $dateDiff = sprintf($formats[$diffFormat], $days);
  293. break;
  294. case 'HOUR' :
  295. $dateDiff = sprintf($formats[$diffFormat], $hours);
  296. break;
  297. case 'MINUTE' :
  298. $dateDiff = sprintf($formats[$diffFormat], $minutes);
  299. break;
  300. case 'SECOND' :
  301. $dateDiff = sprintf($formats[$diffFormat], $seconds);
  302. break;
  303. }
  304. return $dateDiff;
  305. }
  306. function &load_class($class)
  307. {
  308. static $_classes = array();
  309. // Does the class exist? If so, we're done...
  310. if (isset($_classes[$class]))
  311. {
  312. return $_classes[$class];
  313. }
  314. if (class_exists($class) === FALSE)
  315. {
  316. $file = AWS_PATH . preg_replace('#_+#', '/', $class) . '.php';
  317. if (! file_exists($file))
  318. {
  319. show_error('Unable to locate the specified class: ' . $class . ' ' . preg_replace('#_+#', '/', $class) . '.php');
  320. }
  321. require_once $file;
  322. }
  323. $_classes[$class] = new $class();
  324. return $_classes[$class];
  325. }
  326. function _show_error($errorMessage = '')
  327. {
  328. $errorBlock = '';
  329. $name = strtoupper($_SERVER['HTTP_HOST']);
  330. if ($errorMessage)
  331. {
  332. $errorMessage = htmlspecialchars($errorMessage);
  333. $errorBlock = <<<EOF
  334. <div class='database-error'>
  335. <form name='mysql'>
  336. <textarea rows="15" cols="60">{$errorMessage}</textarea>
  337. </form>
  338. </div>
  339. EOF;
  340. }
  341. if (defined('IN_AJAX'))
  342. {
  343. return $errorMessage;
  344. }
  345. return <<<EOF
  346. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  347. <html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
  348. <head>
  349. <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  350. <meta http-equiv="Pragma" content="no-cache" />
  351. <meta http-equiv="Cache-Control" content="no-cache" />
  352. <meta http-equiv="Expires" content="Fri, 01 January 1999 01:00:00 GMT" />
  353. <title>{$name} System Error</title>
  354. <style type='text/css'>
  355. body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td { margin:0; padding:0; }
  356. table { border-collapse:collapse; border-spacing:0; }
  357. fieldset,img { border:0; }
  358. address,caption,cite,code,dfn,em,strong,th,var { font-style:normal; font-weight:normal; }
  359. ol,ul { list-style:none; }
  360. caption,th { text-align:left; }
  361. h1,h2,h3,h4,h5,h6 { font-size:100%; font-weight:normal; }
  362. q:before,q:after { content:''; }
  363. abbr,acronym { border:0; }
  364. hr { display: none; }
  365. address{ display: inline; }
  366. body {
  367. font-family: arial, tahoma, sans-serif;
  368. font-size: 0.8em;
  369. width: 100%;
  370. }
  371. h1 {
  372. font-family: arial, tahoma, "times new roman", serif;
  373. font-size: 1.9em;
  374. color: #fff;
  375. }
  376. h2 {
  377. font-size: 1.6em;
  378. font-weight: normal;
  379. margin: 0 0 8px 0;
  380. clear: both;
  381. }
  382. a {
  383. color: #3e70a8;
  384. }
  385. a:hover {
  386. color: #3d8ce4;
  387. }
  388. a.cancel {
  389. color: #ad2930;
  390. }
  391. #branding {
  392. background: #484848;
  393. padding: 8px;
  394. }
  395. #content {
  396. clear: both;
  397. overflow: hidden;
  398. padding: 20px 15px 0px 15px;
  399. }
  400. * #content {
  401. height: 1%;
  402. }
  403. .message {
  404. border-width: 1px;
  405. border-style: solid;
  406. border-color: #d7d7d7;
  407. background-color: #f5f5f5;
  408. padding: 7px 7px 7px 30px;
  409. margin: 0 0 10px 0;
  410. clear: both;
  411. }
  412. .message.error {
  413. background-color: #f3dddd;
  414. border-color: #deb7b7;
  415. color: #281b1b;
  416. font-size: 1.3em;
  417. font-weight: bold;
  418. }
  419. .message.unspecific {
  420. background-color: #f3f3f3;
  421. border-color: #d4d4d4;
  422. color: #515151;
  423. }
  424. .footer {
  425. text-align: center;
  426. font-size: 1.5em;
  427. }
  428. .database-error {
  429. padding: 4px 0px 10px 80px;
  430. margin: 10px 0px 10px 0px;
  431. }
  432. textarea {
  433. width: 700px;
  434. height: 250px;
  435. }
  436. </style>
  437. </head>
  438. <body id='ipboard_body'>
  439. <div id='header'>
  440. <div id='branding'>
  441. <h1>{$name} System Error</h1>
  442. </div>
  443. </div>
  444. <div id='content'>
  445. <div class='message error'>
  446. There appears to be an error:
  447. {$errorBlock}
  448. </div>
  449. <p class='message unspecific'>
  450. If you are seeing this page, it means there was a problem communicating with our database. Sometimes this error is temporary and will go away when you refresh the page. Sometimes the error will need to be fixed by an administrator before the site will become accessible again.
  451. <br /><br />
  452. You can try to refresh the page by clicking <a href="#" onclick="window.location=window.location; return false;">here</a>
  453. </p>
  454. </div>
  455. </body>
  456. </html>
  457. EOF;
  458. }
  459. function show_error($errorMessage = '')
  460. {
  461. echo _show_error($errorMessage);
  462. exit();
  463. }
  464. function get_table($name)
  465. {
  466. return AWS_APP::config()->get('database')->prefix . $name;
  467. }
  468. function get_setting($varname = null)
  469. {
  470. if (! class_exists('AWS_APP', false))
  471. {
  472. return false;
  473. }
  474. static $setting;
  475. if (! $setting)
  476. {
  477. if ($setting = AWS_APP::setting())
  478. {
  479. if ($setting['upload_enable'] == 'Y' && ! $_SESSION['permission']['upload_attach'])
  480. {
  481. $setting['upload_enable'] = 'N';
  482. }
  483. }
  484. }
  485. if ($varname)
  486. {
  487. return $setting[$varname];
  488. }
  489. else
  490. {
  491. return $setting;
  492. }
  493. }
  494. // ------------------------------------------------------------------------
  495. /**
  496. * Tests for file writability
  497. *
  498. * is_writable() returns TRUE on Windows servers when you really can't write to
  499. * the file, based on the read-only attribute. is_writable() is also unreliable
  500. * on Unix servers if safe_mode is on.
  501. *
  502. * @return void
  503. */
  504. function is_really_writable($file)
  505. {
  506. // If we're on a Unix server with safe_mode off we call is_writable
  507. if (DIRECTORY_SEPARATOR == '/' and @ini_get("safe_mode") == FALSE)
  508. {
  509. return is_writable($file);
  510. }
  511. // For windows servers and safe_mode "on" installations we'll actually
  512. // write a file then read it. Bah...
  513. if (is_dir($file))
  514. {
  515. $file = rtrim($file, '/') . '/' . md5(rand(1, 100));
  516. if (! @file_put_contents($file, 'is_really_writable() test.'))
  517. {
  518. return FALSE;
  519. }
  520. else
  521. {
  522. @unlink($file);
  523. }
  524. return TRUE;
  525. }
  526. else if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE)
  527. {
  528. return FALSE;
  529. }
  530. return TRUE;
  531. }
  532. /**
  533. * 生成密码种子的函数
  534. *
  535. * @access private
  536. * @param int length 长度
  537. * @return string
  538. */
  539. function fetch_salt($length = 4)
  540. {
  541. $salt = '';
  542. for ($i = 0; $i < $length; $i ++)
  543. {
  544. $salt .= chr(rand(97, 122));
  545. }
  546. return $salt;
  547. }
  548. /**
  549. * 编译密码
  550. *
  551. * @param $password 密码
  552. * @param $salt 混淆码
  553. * @return string 加密后的密码
  554. */
  555. function compile_password($password, $salt)
  556. {
  557. // md5 password...
  558. if (strlen($password) == 32)
  559. {
  560. return md5($password . $salt);
  561. }
  562. $password = md5(md5($password) . $salt);
  563. return $password;
  564. }
  565. function get_js_url($url)
  566. {
  567. if (substr($url, 0, 1) == '/')
  568. {
  569. $url = substr($url, 1);
  570. if ((get_setting('url_rewrite_enable') == 'Y') && $request_routes = get_request_route())
  571. {
  572. foreach ($request_routes as $key => $val)
  573. {
  574. if (preg_match('/^' . $val[0] . '$/', $url))
  575. {
  576. $url = preg_replace('/^' . $val[0] . '$/', $val[1], $url);
  577. break;
  578. }
  579. }
  580. }
  581. $url = get_setting('base_url') . '/' . (get_setting('url_rewrite_enable') != 'Y' ? G_INDEX_SCRIPT : '') . $url;
  582. }
  583. return $url;
  584. }
  585. function calc_page_limit($page, $per_page)
  586. {
  587. if (intval($per_page) == 0)
  588. {
  589. die('calc_page_limit(): Error param - $per_page');
  590. }
  591. if ($page < 1)
  592. {
  593. $page = 1;
  594. }
  595. return ((intval($page) - 1) * intval($per_page)) . ', ' . intval($per_page);
  596. }
  597. function get_login_cookie_hash($user_name, $password, $salt, $uid, $hash_password = true)
  598. {
  599. if ($hash_password)
  600. {
  601. $password = compile_password($password, $salt);
  602. }
  603. return H::encode_hash(array('user_name' => $user_name, 'password' => $password, 'uid' => $uid, 'UA' => $_SERVER['HTTP_USER_AGENT']));
  604. }
  605. function random($length, $numeric = 0)
  606. {
  607. //PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
  608. if ($numeric)
  609. {
  610. $hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
  611. }
  612. else
  613. {
  614. $hash = '';
  615. $chars = '0123456789abcdefghijklmnopqrstuvwxyz';
  616. $max = strlen($chars) - 1;
  617. for ($i = 0; $i < $length; $i ++)
  618. {
  619. $hash .= $chars[mt_rand(0, $max)];
  620. }
  621. }
  622. return $hash;
  623. }
  624. function valid_post_hash($hash)
  625. {
  626. return AWS_APP::form()->valid_post_hash($hash);
  627. }
  628. function new_post_hash()
  629. {
  630. return AWS_APP::form()->new_post_hash();
  631. }
  632. // 检测当前操作是否需要验证码
  633. function human_valid($permission_tag)
  634. {
  635. if (! is_array($_SESSION['human_valid']))
  636. {
  637. return FALSE;
  638. }
  639. if (! $_SESSION['human_valid'][$permission_tag] or ! $_SESSION['permission'][$permission_tag])
  640. {
  641. return FALSE;
  642. }
  643. foreach ($_SESSION['human_valid'][$permission_tag] as $time => $val)
  644. {
  645. if (date('H', $time) != date('H', time()))
  646. {
  647. unset($_SESSION['human_valid'][$permission_tag][$time]);
  648. }
  649. }
  650. if (sizeof($_SESSION['human_valid'][$permission_tag]) >= $_SESSION['permission'][$permission_tag])
  651. {
  652. return TRUE;
  653. }
  654. return FALSE;
  655. }
  656. function set_human_valid($permission_tag)
  657. {
  658. if (! is_array($_SESSION['human_valid']))
  659. {
  660. return FALSE;
  661. }
  662. $_SESSION['human_valid'][$permission_tag][time()] = TRUE;
  663. return count($_SESSION['human_valid'][$permission_tag]);
  664. }
  665. /**
  666. * @param int $positive true:正向 false:反向
  667. */
  668. function get_request_route($positive = true)
  669. {
  670. $route_data = (get_setting('request_route') == 99) ? get_setting('request_route_custom') : get_setting('request_route_sys_' . get_setting('request_route'));
  671. if ($request_routes = explode("\n", $route_data))
  672. {
  673. $routes = array();
  674. $replace_array = array("(:any)" => "([^\"'&#\?\/]+[&#\?\/]*[^\"'&#\?\/]*)", "(:num)" => "([0-9]+)");
  675. foreach ($request_routes as $key => $val)
  676. {
  677. $val = trim($val);
  678. if (empty($val))
  679. {
  680. continue;
  681. }
  682. if ($positive)
  683. {
  684. list($pattern, $replace) = explode('===', $val);
  685. }
  686. else
  687. {
  688. list($replace, $pattern) = explode('===', $val);
  689. }
  690. if (substr($pattern, 0, 1) == '/' and $pattern != '/')
  691. {
  692. $pattern = substr($pattern, 1);
  693. }
  694. if (substr($replace, 0, 1) == '/' and $replace != '/')
  695. {
  696. $replace = substr($replace, 1);
  697. }
  698. $pattern = addcslashes($pattern, "/\.?");
  699. $pattern = str_replace(array_keys($replace_array), array_values($replace_array), $pattern);
  700. $replace = str_replace(array_keys($replace_array), "\$1", $replace);
  701. $routes[] = array($pattern, $replace);
  702. }
  703. return $routes;
  704. }
  705. else
  706. {
  707. return false;
  708. }
  709. }
  710. function restri_url($matches)
  711. {
  712. return strip_tags($matches[0]);
  713. }
  714. function strip_ubb($str)
  715. {
  716. $str = preg_replace('/\[attach\]([0-9]+)\[\/attach]/', '[附件内容]', $str);
  717. $str = preg_replace('/\[[^\]]+\](http[s]?:\/\/[^\[]*)\[\/[^\]]+\]/', "\$1 ", $str);
  718. return preg_replace('/\[[^\]]+\]([^\[]*)\[\/[^\]]+\]/', "\$1", $str);
  719. }
  720. function normalize_whitespace($str)
  721. {
  722. $str = trim($str);
  723. $str = str_replace("\r", "\n", $str);
  724. $str = preg_replace(array('/\n+/', '/[ \t]+/'), array("\n", ' '), $str);
  725. return $str;
  726. }
  727. /**
  728. * 打印变量
  729. *
  730. * @param fixed $var
  731. */
  732. if (! function_exists("p"))
  733. {
  734. function p($var)
  735. {
  736. echo "<br><pre>";
  737. if (empty($var))
  738. {
  739. var_dump($var);
  740. }
  741. else
  742. {
  743. print_r($var);
  744. }
  745. echo "</pre><br>";
  746. }
  747. }
  748. /**
  749. * 打印变量 带 REQUEST['debugx']==1
  750. *
  751. * @param fixed $var
  752. */
  753. if (! function_exists("pd"))
  754. {
  755. function pd($var, $exit = 0)
  756. {
  757. if ($_REQUEST['debugx'] == 1)
  758. {
  759. echo "<br><pre>";
  760. if (empty($var))
  761. {
  762. var_dump($var);
  763. }
  764. else
  765. {
  766. print_r($var);
  767. }
  768. echo "</pre><br>";
  769. if ($exit == 1)
  770. exit();
  771. }
  772. }
  773. }
  774. function parse_attachs_callback($matches)
  775. {
  776. if ($attach = AWS_APP::model('publish')->get_attach_by_id($matches[1]))
  777. {
  778. TPL::assign('attach', $attach);
  779. return TPL::output('question/ajax/load_attach', false);
  780. }
  781. }
  782. function get_topic_pic_url($size = null, $pic_file = null)
  783. {
  784. $sized_file = AWS_APP::model('topic')->get_sized_file($size, $pic_file);
  785. if ($sized_file)
  786. {
  787. return get_setting('upload_url') . '/topic/' . $sized_file;
  788. }
  789. else
  790. {
  791. if (! $size)
  792. {
  793. return G_STATIC_URL . '/common/topic-max-img.jpg';
  794. }
  795. return G_STATIC_URL . '/common/topic-' . $size . '-img.jpg';
  796. }
  797. }
  798. function get_feature_pic_url($size = null, $pic_file = null)
  799. {
  800. if (! $pic_file)
  801. {
  802. return false;
  803. }
  804. else
  805. {
  806. if ($size)
  807. {
  808. $pic_file = str_replace(AWS_APP::config()->get('image')->feature_thumbnail['min']['w'] . '_' . AWS_APP::config()->get('image')->feature_thumbnail['min']['h'], AWS_APP::config()->get('image')->feature_thumbnail[$size]['w'] . '_' . AWS_APP::config()->get('image')->feature_thumbnail[$size]['h'], $pic_file);
  809. }
  810. }
  811. return get_setting('upload_url') . '/feature/' . $pic_file;
  812. }
  813. function array_random($arr)
  814. {
  815. shuffle($arr);
  816. return end($arr);
  817. }
  818. /**
  819. * 获得二维数据中第二维指定键对应的值,并组成新数组
  820. */
  821. function fetch_array_value($array, $key)
  822. {
  823. if (! is_array($array) || empty($array))
  824. {
  825. return array();
  826. }
  827. $data = array();
  828. foreach ($array as $_key => $val)
  829. {
  830. $data[] = $val[$key];
  831. }
  832. return $data;
  833. }
  834. function get_host_top_domain()
  835. {
  836. $host = strtolower($_SERVER['HTTP_HOST']);
  837. if (strpos($host, '/') !== false)
  838. {
  839. $parse = @parse_url($host);
  840. $host = $parse['host'];
  841. }
  842. $topleveldomaindb = array('com', 'edu', 'gov', 'int', 'mil', 'net', 'org', 'biz', 'info', 'pro', 'name', 'museum', 'coop', 'aero', 'xxx', 'idv', 'mobi', 'cc', 'me');
  843. $str = '';
  844. foreach ($topleveldomaindb as $v)
  845. {
  846. $str .= ($str ? '|' : '') . $v;
  847. }
  848. $matchstr = "[^\.]+\.(?:(" . $str . ")|\w{2}|((" . $str . ")\.\w{2}))$";
  849. if (preg_match("/" . $matchstr . "/ies", $host, $matchs))
  850. {
  851. $domain = $matchs['0'];
  852. }
  853. else
  854. {
  855. $domain = $host;
  856. }
  857. return $domain;
  858. }
  859. function parse_link_callback($matches)
  860. {
  861. if (preg_match('/^(?!http).*/i', $matches[1]))
  862. {
  863. $url = 'http://' . $matches[1];
  864. }
  865. else
  866. {
  867. $url = $matches[1];
  868. }
  869. if (is_inside_url($url))
  870. {
  871. return '<a href="' . $url . '" class="a">' . FORMAT::sub_url($matches[1], 50) . '</a>';
  872. }
  873. else
  874. {
  875. return '<a href="' . $url . '" class="a" rel="nofollow" target="_blank">' . FORMAT::sub_url($matches[1], 50) . '</a>';
  876. }
  877. }
  878. function is_inside_url($url)
  879. {
  880. if(!$url)
  881. {
  882. return false;
  883. }
  884. if (preg_match('/^(?!http).*/i', $url))
  885. {
  886. $url = 'http://' . $url;
  887. }
  888. $domain = get_host_top_domain();
  889. if (preg_match('/^http[s]?:\/\/([-_a-zA-Z0-9]+[\.])*?' . $domain . '(?!\.)[-a-zA-Z0-9@:;%_\+.~#?&\/\/=]*$/i', $url))
  890. {
  891. return true;
  892. }
  893. return false;
  894. }
  895. function intval_string(&$value)
  896. {
  897. if (! is_numeric($value))
  898. {
  899. $value = intval($value);
  900. }
  901. }
  902. function get_time_zone()
  903. {
  904. $time_zone = 0 + (date('O') / 100);
  905. if ($time_zone == 0)
  906. {
  907. return '';
  908. }
  909. if ($time_zone > 0)
  910. {
  911. return '+' . $time_zone;
  912. }
  913. return $time_zone;
  914. }