functions.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. <?php
  2. // +--------------------------------------------------------------------------
  3. // | Senthot [ DEVELOPED BY ME ]
  4. // +--------------------------------------------------------------------------
  5. // | Copyright (c) 2005-2013 http://www.senthot.com All rights reserved.
  6. // | License ( http://www.apache.org/licenses/LICENSE-2.0 )
  7. // | Author: ms134n ( [email protected] )
  8. // +--------------------------------------------------------------------------
  9. /**
  10. * Sen Standard Mode public library
  11. * @category Sen
  12. * @package Common
  13. * @author ms134n <[email protected]>
  14. */
  15. /**
  16. * Error Output
  17. * @param mixed $error Error
  18. * @return void
  19. */
  20. function halt($error) {
  21. $e = array();
  22. if (APP_DEBUG) {
  23. //The following error message is output Debug Mode
  24. if (!is_array($error)) {
  25. $trace = debug_backtrace();
  26. $e['message'] = $error;
  27. $e['file'] = $trace[0]['file'];
  28. $e['class'] = isset($trace[0]['class'])?$trace[0]['class']:'';
  29. $e['function'] = isset($trace[0]['function'])?$trace[0]['function']:'';
  30. $e['line'] = $trace[0]['line'];
  31. $traceInfo = '';
  32. $time = date('y-m-d H:i:m');
  33. foreach ($trace as $t) {
  34. $traceInfo .= '[' . $time . '] ' . $t['file'] . ' (' . $t['line'] . ') ';
  35. $traceInfo .= $t['class'] . $t['type'] . $t['function'] . '(';
  36. $traceInfo .= implode(', ', $t['args']);
  37. $traceInfo .=')<br/>';
  38. }
  39. $e['trace'] = $traceInfo;
  40. } else {
  41. $e = $error;
  42. }
  43. } else {
  44. //Otherwise directed to the error page
  45. $error_page = C('ERROR_PAGE');
  46. if (!empty($error_page)) {
  47. redirect($error_page);
  48. } else {
  49. if (C('SHOW_ERROR_MSG'))
  50. $e['message'] = is_array($error) ? $error['message'] : $error;
  51. else
  52. $e['message'] = C('ERROR_MESSAGE');
  53. }
  54. }
  55. // Contains an exception page templates
  56. include C('TMPL_EXCEPTION_FILE');
  57. exit;
  58. }
  59. /**
  60. * Custom Exception Handling
  61. * @param string $msg The exception message
  62. * @param string $type Exception Types The default is SenException
  63. * @param integer $code Exception Code The default is 0
  64. * @return void
  65. */
  66. function throw_exception($msg, $type='SenException', $code=0) {
  67. if (class_exists($type, false))
  68. throw new $type($msg, $code, true);
  69. else
  70. halt($msg); // Exception type does not exist error message is output string
  71. }
  72. /**
  73. * Browser-friendly variable output
  74. * @param mixed $var Variable
  75. * @param boolean $echo Whether to output default is True If false Output string is returned
  76. * @param string $label Tag The default is empty
  77. * @param boolean $strict Whether rigorous default is true
  78. * @return void|string
  79. */
  80. function dump($var, $echo=true, $label=null, $strict=true) {
  81. $label = ($label === null) ? '' : rtrim($label) . ' ';
  82. if (!$strict) {
  83. if (ini_get('html_errors')) {
  84. $output = print_r($var, true);
  85. $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
  86. } else {
  87. $output = $label . print_r($var, true);
  88. }
  89. } else {
  90. ob_start();
  91. var_dump($var);
  92. $output = ob_get_clean();
  93. if (!extension_loaded('xdebug')) {
  94. $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
  95. $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
  96. }
  97. }
  98. if ($echo) {
  99. echo($output);
  100. return null;
  101. }else
  102. return $output;
  103. }
  104. /**
  105. * 404 Processing
  106. * Debug Mode will throw an exception
  107. * Deployment Mode Here you can specify the url parameter passed Jump page, or send 404 message
  108. * @param string $msg Tips
  109. * @param string $url Jump URL address
  110. * @return void
  111. */
  112. function _404($msg='',$url='') {
  113. APP_DEBUG && throw_exception($msg);
  114. if($msg && C('LOG_EXCEPTION_RECORD')) Log::write($msg);
  115. if(empty($url) && C('URL_404_REDIRECT')) {
  116. $url = C('URL_404_REDIRECT');
  117. }
  118. if($url) {
  119. redirect($url);
  120. }else{
  121. send_http_status(404);
  122. exit;
  123. }
  124. }
  125. /**
  126. * Set the current layout of the page
  127. * @param string|false $layout Layout Name When the representation is false closure layout
  128. * @return void
  129. */
  130. function layout($layout) {
  131. if(false !== $layout) {
  132. // Open layout
  133. C('LAYOUT_ON',true);
  134. if(is_string($layout)) { // Set up a new layout template
  135. C('LAYOUT_NAME',$layout);
  136. }
  137. }else{// Temporary closure layout
  138. C('LAYOUT_ON',false);
  139. }
  140. }
  141. /**
  142. * URL Assembly Support different URLMode
  143. * @param string $url URL expressions, Format:'[Grouping/Module/Operating#Anchor@DomainName]?Parameter1=Value1&Parameter2=Value2...'
  144. * @param string|array $vars Incoming parameters, Support arrays and strings
  145. * @param string $suffix Pseudo-static suffix, the default configuration values for the true means to obtain
  146. * @param boolean $redirect Whether the jump, if set to true then the jump to the URL address
  147. * @param boolean $domain Whether to display the name
  148. * @return string
  149. */
  150. function U($url='',$vars='',$suffix=true,$redirect=false,$domain=false) {
  151. // Parse URL
  152. $info = parse_url($url);
  153. $url = !empty($info['path'])?$info['path']:ACTION_NAME;
  154. if(isset($info['fragment'])) { // Resolution anchor
  155. $anchor = $info['fragment'];
  156. if(false !== strpos($anchor,'?')) { // Analytical parameters
  157. list($anchor,$info['query']) = explode('?',$anchor,2);
  158. }
  159. if(false !== strpos($anchor,'@')) { // Resolve domain names
  160. list($anchor,$host) = explode('@',$anchor, 2);
  161. }
  162. }elseif(false !== strpos($url,'@')) { // Resolve domain names
  163. list($url,$host) = explode('@',$info['path'], 2);
  164. }
  165. // Analytic subdomain
  166. if(isset($host)) {
  167. $domain = $host.(strpos($host,'.')?'':strstr($_SERVER['HTTP_HOST'],'.'));
  168. }elseif($domain===true){
  169. $domain = $_SERVER['HTTP_HOST'];
  170. if(C('APP_SUB_DOMAIN_DEPLOY') ) { // On sub-domain deployment
  171. $domain = $domain=='localhost'?'localhost':'www'.strstr($_SERVER['HTTP_HOST'],'.');
  172. // 'Subdomain'=>array('Project[/Grouping]');
  173. foreach (C('APP_SUB_DOMAIN_RULES') as $key => $rule) {
  174. if(false === strpos($key,'*') && 0=== strpos($url,$rule[0])) {
  175. $domain = $key.strstr($domain,'.'); // Generate the corresponding sub-domain
  176. $url = substr_replace($url,'',0,strlen($rule[0]));
  177. break;
  178. }
  179. }
  180. }
  181. }
  182. // Analytical parameters
  183. if(is_string($vars)) { // aaa=1&bbb=2 Converted into an array
  184. parse_str($vars,$vars);
  185. }elseif(!is_array($vars)){
  186. $vars = array();
  187. }
  188. if(isset($info['query'])) { // Resolve the address inside the parameters Merged into vars
  189. parse_str($info['query'],$params);
  190. $vars = array_merge($params,$vars);
  191. }
  192. // URL Assembly
  193. $depr = C('URL_PATHINFO_DEPR');
  194. if($url) {
  195. if(0=== strpos($url,'/')) {// Defining Routing
  196. $route = true;
  197. $url = substr($url,1);
  198. if('/' != $depr) {
  199. $url = str_replace('/',$depr,$url);
  200. }
  201. }else{
  202. if('/' != $depr) { // Secure replacement
  203. $url = str_replace('/',$depr,$url);
  204. }
  205. // Packet parsing module and operating
  206. $url = trim($url,$depr);
  207. $path = explode($depr,$url);
  208. $var = array();
  209. $var[C('VAR_ACTION')] = !empty($path)?array_pop($path):ACTION_NAME;
  210. $var[C('VAR_MODULE')] = !empty($path)?array_pop($path):MODULE_NAME;
  211. if($maps = C('URL_ACTION_MAP')) {
  212. if(isset($maps[strtolower($var[C('VAR_MODULE')])])) {
  213. $maps = $maps[strtolower($var[C('VAR_MODULE')])];
  214. if($action = array_search(strtolower($var[C('VAR_ACTION')]),$maps)){
  215. $var[C('VAR_ACTION')] = $action;
  216. }
  217. }
  218. }
  219. if($maps = C('URL_MODULE_MAP')) {
  220. if($module = array_search(strtolower($var[C('VAR_MODULE')]),$maps)){
  221. $var[C('VAR_MODULE')] = $module;
  222. }
  223. }
  224. if(C('URL_CASE_INSENSITIVE')) {
  225. $var[C('VAR_MODULE')] = parse_name($var[C('VAR_MODULE')]);
  226. }
  227. if(!C('APP_SUB_DOMAIN_DEPLOY') && C('APP_GROUP_LIST')) {
  228. if(!empty($path)) {
  229. $group = array_pop($path);
  230. $var[C('VAR_GROUP')] = $group;
  231. }else{
  232. if(GROUP_NAME != C('DEFAULT_GROUP')) {
  233. $var[C('VAR_GROUP')]= GROUP_NAME;
  234. }
  235. }
  236. if(C('URL_CASE_INSENSITIVE') && isset($var[C('VAR_GROUP')])) {
  237. $var[C('VAR_GROUP')] = strtolower($var[C('VAR_GROUP')]);
  238. }
  239. }
  240. }
  241. }
  242. if(C('URL_MODEL') == 0) { // Normal modeURL conversion
  243. $url = __APP__.'?'.http_build_query(array_reverse($var));
  244. if(!empty($vars)) {
  245. $vars = urldecode(http_build_query($vars));
  246. $url .= '&'.$vars;
  247. }
  248. }else{ // PATHINFOMode or compatible URLMode
  249. if(isset($route)) {
  250. $url = __APP__.'/'.rtrim($url,$depr);
  251. }else{
  252. $url = __APP__.'/'.implode($depr,array_reverse($var));
  253. }
  254. if(!empty($vars)) { // Adding Parameters
  255. foreach ($vars as $var => $val){
  256. if('' !== trim($val)) $url .= $depr . $var . $depr . urlencode($val);
  257. }
  258. }
  259. if($suffix) {
  260. $suffix = $suffix===true?C('URL_HTML_SUFFIX'):$suffix;
  261. if($pos = strpos($suffix, '|')){
  262. $suffix = substr($suffix, 0, $pos);
  263. }
  264. if($suffix && '/' != substr($url,-1)){
  265. $url .= '.'.ltrim($suffix,'.');
  266. }
  267. }
  268. }
  269. if(isset($anchor)){
  270. $url .= '#'.$anchor;
  271. }
  272. if($domain) {
  273. $url = (is_ssl()?'https://':'http://').$domain.$url;
  274. }
  275. if($redirect) // Jump directly to URL
  276. redirect($url);
  277. else
  278. return $url;
  279. }
  280. /**
  281. * Render Output Widget
  282. * @param string $name Widget name
  283. * @param array $data Transmission parameters
  284. * @param boolean $return Returns the content
  285. * @return void
  286. */
  287. function W($name, $data=array(), $return=false) {
  288. $class = $name . 'Widget';
  289. require_cache(BASE_LIB_PATH . 'Widget/' . $class . '.class.php');
  290. if (!class_exists($class))
  291. throw_exception(L('_CLASS_NOT_EXIST_') . ':' . $class);
  292. $widget = Sen::instance($class);
  293. $content = $widget->render($data);
  294. if ($return)
  295. return $content;
  296. else
  297. echo $content;
  298. }
  299. /**
  300. * Filter method Passing a value by reference
  301. * @param string $name Filter name
  302. * @param string $content To filter the content
  303. * @return void
  304. */
  305. function filter($name, &$content) {
  306. $class = $name . 'Filter';
  307. require_cache(BASE_LIB_PATH . 'Filter/' . $class . '.class.php');
  308. $filter = new $class();
  309. $content = $filter->run($content);
  310. }
  311. /**
  312. * Determine whether the SSL protocol
  313. * @return boolean
  314. */
  315. function is_ssl() {
  316. if(isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))){
  317. return true;
  318. }elseif(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) {
  319. return true;
  320. }
  321. return false;
  322. }
  323. /**
  324. * URL Redirection
  325. * @param string $url Redirect URL address
  326. * @param integer $time Redirection waiting time ( sec )
  327. * @param string $msg Message before redirecting
  328. * @return void
  329. */
  330. function redirect($url, $time=0, $msg='') {
  331. //Support multi-line URL address
  332. $url = str_replace(array("\n", "\r"), '', $url);
  333. if (empty($msg))
  334. $msg = "System will {$time}seconds automatically jump to {$url}!";
  335. if (!headers_sent()) {
  336. // redirect
  337. if (0 === $time) {
  338. header('Location: ' . $url);
  339. } else {
  340. header("refresh:{$time};url={$url}");
  341. echo($msg);
  342. }
  343. exit();
  344. } else {
  345. $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
  346. if ($time != 0)
  347. $str .= $msg;
  348. exit($str);
  349. }
  350. }
  351. /**
  352. * Cache Management
  353. * @param mixed $name Cache name, if it is expressed as an array cache settings
  354. * @param mixed $value Cached value
  355. * @param mixed $options Cache parameters
  356. * @return mixed
  357. */
  358. function S($name,$value='',$options=null) {
  359. static $cache = '';
  360. if(is_array($options)){
  361. // Cache operation while initializing
  362. $type = isset($options['type'])?$options['type']:'';
  363. $cache = Cache::getInstance($type,$options);
  364. }elseif(is_array($name)) { // Cache initialization
  365. $type = isset($name['type'])?$name['type']:'';
  366. $cache = Cache::getInstance($type,$name);
  367. return $cache;
  368. }elseif(empty($cache)) { // Automatic initialization
  369. $cache = Cache::getInstance();
  370. }
  371. if(''=== $value){ // Get Cache
  372. return $cache->get($name);
  373. }elseif(is_null($value)) { // Deleting the cache
  374. return $cache->rm($name);
  375. }else { // Cache data
  376. $expire = is_numeric($options)?$options:NULL;
  377. return $cache->set($name, $value, $expire);
  378. }
  379. }
  380. // S method aliases has been abolished no longer recommended
  381. function cache($name,$value='',$options=null){
  382. return S($name,$value,$options);
  383. }
  384. /**
  385. * Fast read and save data files For simple data types Strings, arrays
  386. * @param string $name Cache name
  387. * @param mixed $value Cached value
  388. * @param string $path Cache path
  389. * @return mixed
  390. */
  391. function F($name, $value='', $path=DATA_PATH) {
  392. static $_cache = array();
  393. $filename = $path . $name . '.php';
  394. if ('' !== $value) {
  395. if (is_null($value)) {
  396. // Deleting the cache
  397. return false !== strpos($name,'*')?array_map("unlink", glob($filename)):unlink($filename);
  398. } else {
  399. // Cache data
  400. $dir = dirname($filename);
  401. // Directory does not exist, create
  402. if (!is_dir($dir))
  403. mkdir($dir,0755,true);
  404. $_cache[$name] = $value;
  405. return file_put_contents($filename, strip_whitespace("<?php\treturn " . var_export($value, true) . ";?>"));
  406. }
  407. }
  408. if (isset($_cache[$name]))
  409. return $_cache[$name];
  410. // Get cached data
  411. if (is_file($filename)) {
  412. $value = include $filename;
  413. $_cache[$name] = $value;
  414. } else {
  415. $value = false;
  416. }
  417. return $value;
  418. }
  419. /**
  420. * Get object instance Support call the class static method
  421. * @param string $name Class name
  422. * @param string $method Method name, if it is empty then return instantiate objects
  423. * @param array $args Call parameters
  424. * @return object
  425. */
  426. function get_instance_of($name, $method='', $args=array()) {
  427. static $_instance = array();
  428. $identify = empty($args) ? $name . $method : $name . $method . to_guid_string($args);
  429. if (!isset($_instance[$identify])) {
  430. if (class_exists($name)) {
  431. $o = new $name();
  432. if (method_exists($o, $method)) {
  433. if (!empty($args)) {
  434. $_instance[$identify] = call_user_func_array(array(&$o, $method), $args);
  435. } else {
  436. $_instance[$identify] = $o->$method();
  437. }
  438. }
  439. else
  440. $_instance[$identify] = $o;
  441. }
  442. else
  443. halt(L('_CLASS_NOT_EXIST_') . ':' . $name);
  444. }
  445. return $_instance[$identify];
  446. }
  447. /**
  448. * According to PHP variable types to generate a unique identification number
  449. * @param mixed $mix Variable
  450. * @return string
  451. */
  452. function to_guid_string($mix) {
  453. if (is_object($mix) && function_exists('spl_object_hash')) {
  454. return spl_object_hash($mix);
  455. } elseif (is_resource($mix)) {
  456. $mix = get_resource_type($mix) . strval($mix);
  457. } else {
  458. $mix = serialize($mix);
  459. }
  460. return md5($mix);
  461. }
  462. /**
  463. * XML encoding
  464. * @param mixed $data Data
  465. * @param string $encoding Data encoding
  466. * @param string $root Root name
  467. * @return string
  468. */
  469. function xml_encode($data, $encoding='utf-8', $root='sen') {
  470. $xml = '<?xml version="1.0" encoding="' . $encoding . '"?>';
  471. $xml .= '<' . $root . '>';
  472. $xml .= data_to_xml($data);
  473. $xml .= '</' . $root . '>';
  474. return $xml;
  475. }
  476. /**
  477. * XML-encoded data
  478. * @param mixed $data Data
  479. * @return string
  480. */
  481. function data_to_xml($data) {
  482. $xml = '';
  483. foreach ($data as $key => $val) {
  484. is_numeric($key) && $key = "item id=\"$key\"";
  485. $xml .= "<$key>";
  486. $xml .= ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val;
  487. list($key, ) = explode(' ', $key);
  488. $xml .= "</$key>";
  489. }
  490. return $xml;
  491. }
  492. /**
  493. * session management functions
  494. * @param string|array $name session name If an array indicates settings for session
  495. * @param mixed $value session value
  496. * @return mixed
  497. */
  498. function session($name,$value='') {
  499. $prefix = C('SESSION_PREFIX');
  500. if(is_array($name)) { // session initialization in session_start before calling
  501. if(isset($name['prefix'])) C('SESSION_PREFIX',$name['prefix']);
  502. if(C('VAR_SESSION_ID') && isset($_REQUEST[C('VAR_SESSION_ID')])){
  503. session_id($_REQUEST[C('VAR_SESSION_ID')]);
  504. }elseif(isset($name['id'])) {
  505. session_id($name['id']);
  506. }
  507. ini_set('session.auto_start', 0);
  508. if(isset($name['name'])) session_name($name['name']);
  509. if(isset($name['path'])) session_save_path($name['path']);
  510. if(isset($name['domain'])) ini_set('session.cookie_domain', $name['domain']);
  511. if(isset($name['expire'])) ini_set('session.gc_maxlifetime', $name['expire']);
  512. if(isset($name['use_trans_sid'])) ini_set('session.use_trans_sid', $name['use_trans_sid']?1:0);
  513. if(isset($name['use_cookies'])) ini_set('session.use_cookies', $name['use_cookies']?1:0);
  514. if(isset($name['cache_limiter'])) session_cache_limiter($name['cache_limiter']);
  515. if(isset($name['cache_expire'])) session_cache_expire($name['cache_expire']);
  516. if(isset($name['type'])) C('SESSION_TYPE',$name['type']);
  517. if(C('SESSION_TYPE')) { // Reading session drive
  518. $class = 'Session'. ucwords(strtolower(C('SESSION_TYPE')));
  519. // Check the driver class
  520. if(require_cache(ADDONS_PATH.'Driver/Session/'.$class.'.class.php')) {
  521. $hander = new $class();
  522. $hander->execute();
  523. }else {
  524. // Class does not define
  525. throw_exception(L('_CLASS_NOT_EXIST_').': ' . $class);
  526. }
  527. }
  528. // Start session
  529. if(C('SESSION_AUTO_START')) session_start();
  530. }elseif('' === $value){
  531. if(0===strpos($name,'[')) { // session Operating
  532. if('[pause]'==$name){ // Pause session
  533. session_write_close();
  534. }elseif('[start]'==$name){ // Start session
  535. session_start();
  536. }elseif('[destroy]'==$name){ // Destroys the session
  537. $_SESSION = array();
  538. session_unset();
  539. session_destroy();
  540. }elseif('[regenerate]'==$name){ // Rebuild id
  541. session_regenerate_id();
  542. }
  543. }elseif(0===strpos($name,'?')){ // Examination session
  544. $name = substr($name,1);
  545. if($prefix) {
  546. return isset($_SESSION[$prefix][$name]);
  547. }else{
  548. return isset($_SESSION[$name]);
  549. }
  550. }elseif(is_null($name)){ // Empty session
  551. if($prefix) {
  552. unset($_SESSION[$prefix]);
  553. }else{
  554. $_SESSION = array();
  555. }
  556. }elseif($prefix){ // Get session
  557. return isset($_SESSION[$prefix][$name])?$_SESSION[$prefix][$name]:null;
  558. }else{
  559. return isset($_SESSION[$name])?$_SESSION[$name]:null;
  560. }
  561. }elseif(is_null($value)){ // Delete session
  562. if($prefix){
  563. unset($_SESSION[$prefix][$name]);
  564. }else{
  565. unset($_SESSION[$name]);
  566. }
  567. }else{ // Set session
  568. if($prefix){
  569. if (!is_array($_SESSION[$prefix])) {
  570. $_SESSION[$prefix] = array();
  571. }
  572. $_SESSION[$prefix][$name] = $value;
  573. }else{
  574. $_SESSION[$name] = $value;
  575. }
  576. }
  577. }
  578. /**
  579. * Cookie set, get, delete
  580. * @param string $name cookie name
  581. * @param mixed $value cookie value
  582. * @param mixed $options cookie parameters
  583. * @return mixed
  584. */
  585. function cookie($name, $value='', $option=null) {
  586. // Default setting
  587. $config = array(
  588. 'prefix' => C('COOKIE_PREFIX'), // cookie Name Prefix
  589. 'expire' => C('COOKIE_EXPIRE'), // cookie Save Time
  590. 'path' => C('COOKIE_PATH'), // cookie Save path
  591. 'domain' => C('COOKIE_DOMAIN'), // cookie Valid domain name
  592. );
  593. // Parameter settings(will cover the default setting Summerside)
  594. if (!is_null($option)) {
  595. if (is_numeric($option))
  596. $option = array('expire' => $option);
  597. elseif (is_string($option))
  598. parse_str($option, $option);
  599. $config = array_merge($config, array_change_key_case($option));
  600. }
  601. // Clear all cookie specified Prefix
  602. if (is_null($name)) {
  603. if (empty($_COOKIE))
  604. return;
  605. // To delete cookiePrefix, not specified remove the config settings specified Prefix
  606. $prefix = empty($value) ? $config['prefix'] : $value;
  607. if (!empty($prefix)) {// If Prefix is an empty string will not be processed directly back
  608. foreach ($_COOKIE as $key => $val) {
  609. if (0 === stripos($key, $prefix)) {
  610. setcookie($key, '', time() - 3600, $config['path'], $config['domain']);
  611. unset($_COOKIE[$key]);
  612. }
  613. }
  614. }
  615. return;
  616. }
  617. $name = $config['prefix'] . $name;
  618. if ('' === $value) {
  619. if(isset($_COOKIE[$name])){
  620. $value = $_COOKIE[$name];
  621. if(0===strpos($value,'sen:')){
  622. $value = substr($value,6);
  623. return array_map('urldecode',json_decode(MAGIC_QUOTES_GPC?stripslashes($value):$value,true));
  624. }else{
  625. return $value;
  626. }
  627. }else{
  628. return null;
  629. }
  630. } else {
  631. if (is_null($value)) {
  632. setcookie($name, '', time() - 3600, $config['path'], $config['domain']);
  633. unset($_COOKIE[$name]); // Deletes the specified cookie
  634. } else {
  635. // Set a cookie
  636. if(is_array($value)){
  637. $value = 'sen:'.json_encode(array_map('urlencode',$value));
  638. }
  639. $expire = !empty($config['expire']) ? time() + intval($config['expire']) : 0;
  640. setcookie($name, $value, $expire, $config['path'], $config['domain']);
  641. $_COOKIE[$name] = $value;
  642. }
  643. }
  644. }
  645. /**
  646. * Loaded dynamically expanding file
  647. * @return void
  648. */
  649. function load_ext_file() {
  650. // Load custom external file
  651. if(C('LOAD_EXT_FILE')) {
  652. $files = explode(',',C('LOAD_EXT_FILE'));
  653. foreach ($files as $file){
  654. $file = COMMON_PATH.$file.'.php';
  655. if(is_file($file)) include $file;
  656. }
  657. }
  658. // Dynamic load custom configuration files
  659. if(C('LOAD_EXT_CONFIG')) {
  660. $configs = C('LOAD_EXT_CONFIG');
  661. if(is_string($configs)) $configs = explode(',',$configs);
  662. foreach ($configs as $key=>$config){
  663. $file = CONF_PATH.$config.'.php';
  664. if(is_file($file)) {
  665. is_numeric($key)?C(include $file):C($key,include $file);
  666. }
  667. }
  668. }
  669. }
  670. /**
  671. * Get client IP address
  672. * @param integer $type Return Type 0 Returns the IP address 1 Back IPV4 address numbers
  673. * @return mixed
  674. */
  675. function get_client_ip($type = 0) {
  676. $type = $type ? 1 : 0;
  677. static $ip = NULL;
  678. if ($ip !== NULL) return $ip[$type];
  679. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  680. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  681. $pos = array_search('unknown',$arr);
  682. if(false !== $pos) unset($arr[$pos]);
  683. $ip = trim($arr[0]);
  684. }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  685. $ip = $_SERVER['HTTP_CLIENT_IP'];
  686. }elseif (isset($_SERVER['REMOTE_ADDR'])) {
  687. $ip = $_SERVER['REMOTE_ADDR'];
  688. }
  689. // IP address of the legal verification
  690. $long = sprintf("%u",ip2long($ip));
  691. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  692. return $ip[$type];
  693. }
  694. /**
  695. * Send HTTP status
  696. * @param integer $code Status Codes
  697. * @return void
  698. */
  699. function send_http_status($code) {
  700. static $_status = array(
  701. // Success 2xx
  702. 200 => 'OK',
  703. // Redirection 3xx
  704. 301 => 'Moved Permanently',
  705. 302 => 'Moved Temporarily ', // 1.1
  706. // Client Error 4xx
  707. 400 => 'Bad Request',
  708. 403 => 'Forbidden',
  709. 404 => 'Not Found',
  710. // Server Error 5xx
  711. 500 => 'Internal Server Error',
  712. 503 => 'Service Unavailable',
  713. );
  714. if(isset($_status[$code])) {
  715. header('HTTP/1.1 '.$code.' '.$_status[$code]);
  716. // Ensure FastCGIMode normal
  717. header('Status:'.$code.' '.$_status[$code]);
  718. }
  719. }
  720. // Filter expression in the form
  721. function filter_exp(&$value){
  722. if (in_array(strtolower($value),array('exp','or'))){
  723. $value .= ' ';
  724. }
  725. }