国内流行的内容管理系统(CMS)多端全媒体解决方案 https://www.dedebiz.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

773 lines
31KB

  1. <?php
  2. if (!defined('DEDEINC')) exit ('dedebiz');
  3. /**
  4. * 系统核心函数存放
  5. *
  6. * @version $id:common.func.php 4 16:39 2010年7月6日 tianya $
  7. * @package DedeBIZ.Libraries
  8. * @copyright Copyright (c) 2022 DedeBIZ.COM
  9. * @license https://www.dedebiz.com/license
  10. * @link https://www.dedebiz.com
  11. */
  12. //类似Bootstrap警告框
  13. define('ALERT_PRIMARY', 1);
  14. define('ALERT_SECONDARY', 2);
  15. define('ALERT_SUCCESS', 3);
  16. define('ALERT_DANGER', 4);
  17. define('ALERT_WARNING', 5);
  18. define('ALERT_INFO', 6);
  19. define('ALERT_LIGHT', 7);
  20. define('ALERT_DARK', 8);
  21. define("ALERT_TPL", '<div style="position:relative;padding:.75rem 1.25rem;margin-bottom:1rem;width:auto;font-size:14px;color:~color~;background:~background~;border-color:~border~;border:1px solid transparent;border-radius:.5rem">~content~</div>');
  22. //$content:文档,$type:alert类型
  23. function DedeAlert($content, $type = ALERT_PRIMARY, $isHTML = false)
  24. {
  25. $colors = array(
  26. ALERT_PRIMARY => array('#cfe2ff','#b6d4fe','#084298'),
  27. ALERT_SECONDARY => array('#e2e3e5','#d3d6d8','#41464b'),
  28. ALERT_SUCCESS => array('#d1e7dd','#badbcc','#0f5132'),
  29. ALERT_DANGER => array('#f8d7da','#f5c2c7','#842029'),
  30. ALERT_WARNING => array('#fff3cd','#ffecb5','#664d03'),
  31. ALERT_INFO => array('#cff4fc','#b6effb','#055160'),
  32. ALERT_LIGHT => array('#fefefe','#fdfdfe','#636464'),
  33. ALERT_DARK => array('#d3d3d4','#bcbebf','#141619'),
  34. );
  35. $content = $isHTML? RemoveXSS($content) : htmlspecialchars($content);
  36. $colors = isset($colors[$type])? $colors[$type] : $colors[ALERT_PRIMARY];
  37. list($background, $border, $color) = $colors;
  38. return str_replace(array('~color~','~background~','~border~', '~content~'),array($color,$background,$border,$content),ALERT_TPL);
  39. }
  40. if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
  41. if (!function_exists('mysql_connect') and function_exists('mysqli_connect')) {
  42. function mysql_connect($server, $username, $password)
  43. {
  44. return mysqli_connect($server, $username, $password);
  45. }
  46. }
  47. if (!function_exists('mysql_query') and function_exists('mysqli_query')) {
  48. function mysql_query($query, $link)
  49. {
  50. return mysqli_query($link, $query);
  51. }
  52. }
  53. if (!function_exists('mysql_select_db') and function_exists('mysqli_select_db')) {
  54. function mysql_select_db($database_name, $link)
  55. {
  56. return mysqli_select_db($link, $database_name);
  57. }
  58. }
  59. if (!function_exists('mysql_fetch_array') and function_exists('mysqli_fetch_array')) {
  60. function mysql_fetch_array($result)
  61. {
  62. return mysqli_fetch_array($result);
  63. }
  64. }
  65. if (!function_exists('mysql_close') and function_exists('mysqli_close')) {
  66. function mysql_close($link)
  67. {
  68. if ($link) {
  69. return @mysqli_close($link);
  70. } else {
  71. return false;
  72. }
  73. }
  74. }
  75. if (!function_exists('mysql_error') and function_exists('mysqli_connect_error')) {
  76. function mysql_error($link='')
  77. {
  78. if (mysqli_connect_errno()) {
  79. return mysqli_connect_error();
  80. }
  81. if ($link) {
  82. return @mysqli_error($link);
  83. } else {
  84. return false;
  85. }
  86. }
  87. }
  88. if (!function_exists('mysql_free_result') and function_exists('mysqli_free_result')) {
  89. function mysql_free_result($result)
  90. {
  91. return mysqli_free_result($result);
  92. }
  93. }
  94. if (!function_exists('split')) {
  95. function split($pattern, $string)
  96. {
  97. return explode($pattern, $string);
  98. }
  99. }
  100. }
  101. //一个支持在PHP Cli Server打印的方法
  102. function var_dump_cli($val,...$values)
  103. {
  104. ob_start();
  105. var_dump($val,$values);
  106. error_log(ob_get_clean(), 4);
  107. }
  108. function get_mime_type($filename)
  109. {
  110. if (!function_exists('finfo_open')) {
  111. return 'unknow/octet-stream';
  112. }
  113. $finfo = finfo_open(FILEINFO_MIME_TYPE);
  114. $mimeType = finfo_file($finfo, $filename);
  115. finfo_close($finfo);
  116. return $mimeType;
  117. }
  118. function is_all_numeric(array $array)
  119. {
  120. foreach ($array as $item) {
  121. if (!is_numeric($item)) return false;
  122. }
  123. return true;
  124. }
  125. function make_hash()
  126. {
  127. $rand = dede_random_bytes(16);
  128. $_SESSION['token'] = ($rand === FALSE) ? md5(uniqid(mt_rand(), TRUE)) : bin2hex($rand);
  129. return $_SESSION['token'];
  130. }
  131. function dede_random_bytes($length)
  132. {
  133. if (empty($length) or !ctype_digit((string) $length)) {
  134. return FALSE;
  135. }
  136. if (function_exists('openssl_random_pseudo_bytes')) {
  137. return openssl_random_pseudo_bytes($length);
  138. }
  139. if (function_exists('random_bytes')) {
  140. try {
  141. return random_bytes((int) $length);
  142. } catch (Exception $e) {
  143. return FALSE;
  144. }
  145. }
  146. if (is_readable('/dev/urandom') && ($fp = fopen('/dev/urandom', 'rb')) !== FALSE) {
  147. version_compare(PHP_VERSION, '5.4.0', '>=') && stream_set_chunk_size($fp, $length);
  148. $output = fread($fp, $length);
  149. fclose($fp);
  150. if ($output !== FALSE) {
  151. return $output;
  152. }
  153. }
  154. return FALSE;
  155. }
  156. //SQL语句过滤程序,由80sec提供,这里作了适当的修改
  157. if (!function_exists('CheckSql')) {
  158. function CheckSql($db_string, $querytype = 'select')
  159. {
  160. global $cfg_cookie_encode;
  161. $clean = '';
  162. $error = '';
  163. $old_pos = 0;
  164. $pos = -1;
  165. $enkey = substr(md5(substr($cfg_cookie_encode.'dedebiz', 0, 5)), 0, 10);
  166. $log_file = DEDEDATA.'/checksql_'.$enkey.'_safe.txt';
  167. $userIP = GetIP();
  168. $getUrl = GetCurUrl();
  169. //如果是普通查询语句,直接过滤一些特殊语法
  170. if ($querytype == 'select') {
  171. $notallow1 = "[^0-9a-z@\._-]{1,}(union|sleep|benchmark|load_file|outfile)[^0-9a-z@\.-]{1,}";
  172. if (preg_match("/".$notallow1."/i", $db_string)) {
  173. fputs(fopen($log_file, 'a+'), "$userIP||$getUrl||$db_string||SelectBreak\r\n");
  174. exit("<span>Safe Alert: Request Error step 1 !</span>");
  175. }
  176. }
  177. //完整的SQL检查
  178. while (TRUE) {
  179. $pos = strpos($db_string, '\'', $pos + 1);
  180. if ($pos === FALSE) {
  181. break;
  182. }
  183. $clean .= substr($db_string, $old_pos, $pos - $old_pos);
  184. while (TRUE) {
  185. $pos1 = strpos($db_string, '\'', $pos + 1);
  186. $pos2 = strpos($db_string, '\\', $pos + 1);
  187. if ($pos1 === FALSE) {
  188. break;
  189. } elseif ($pos2 == FALSE || $pos2 > $pos1) {
  190. $pos = $pos1;
  191. break;
  192. }
  193. $pos = $pos2 + 1;
  194. }
  195. $clean .= '$s$';
  196. $old_pos = $pos + 1;
  197. }
  198. $clean .= substr($db_string, $old_pos);
  199. $clean = trim(strtolower(preg_replace(array('~\s+~s'), array(' '), $clean)));
  200. if (
  201. strpos($clean, '@') !== FALSE or strpos($clean, 'char(') !== FALSE or strpos($clean, '"') !== FALSE
  202. or strpos($clean, '$s$$s$') !== FALSE
  203. ) {
  204. $fail = TRUE;
  205. if (preg_match("#^create table#i", $clean)) $fail = FALSE;
  206. $error = "unusual character";
  207. }
  208. //老版本数据库不支持union,程序不使用union,但黑客使用它,所以检查它
  209. if (strpos($clean, 'union') !== FALSE && preg_match('~(^|[^a-z])union($|[^[a-z])~s', $clean) != 0) {
  210. $fail = TRUE;
  211. $error = "union detect";
  212. }
  213. //发布版本的程序比较少包括--,#这样的注释,但黑客经常使用它们
  214. elseif (strpos($clean, '/*') > 2 || strpos($clean, '--') !== FALSE || strpos($clean, '#') !== FALSE) {
  215. $fail = TRUE;
  216. $error = "comment detect";
  217. }
  218. //这些函数不会被使用,但是黑客会用它来操作文件,down掉数据库
  219. elseif (strpos($clean, 'sleep') !== FALSE && preg_match('~(^|[^a-z])sleep($|[^[a-z])~s', $clean) != 0) {
  220. $fail = TRUE;
  221. $error = "slown down detect";
  222. } elseif (strpos($clean, 'benchmark') !== FALSE && preg_match('~(^|[^a-z])benchmark($|[^[a-z])~s', $clean) != 0) {
  223. $fail = TRUE;
  224. $error = "slown down detect";
  225. } elseif (strpos($clean, 'load_file') !== FALSE && preg_match('~(^|[^a-z])load_file($|[^[a-z])~s', $clean) != 0) {
  226. $fail = TRUE;
  227. $error = "file fun detect";
  228. } elseif (strpos($clean, 'into outfile') !== FALSE && preg_match('~(^|[^a-z])into\s+outfile($|[^[a-z])~s', $clean) != 0) {
  229. $fail = TRUE;
  230. $error = "file fun detect";
  231. }
  232. //老版本数据库不支持子查询,该功能也用得少,但黑客可以使用它来查询数据库敏感信息
  233. elseif (preg_match('~\([^)]*?select~s', $clean) != 0) {
  234. $fail = TRUE;
  235. $error = "sub select detect";
  236. }
  237. if (!empty($fail)) {
  238. fputs(fopen($log_file, 'a+'), "$userIP||$getUrl||$db_string||$error\r\n");
  239. exit("<span>Safe Alert: Request Error step 2!</span>");
  240. } else {
  241. return $db_string;
  242. }
  243. }
  244. }
  245. /**
  246. * 载入助手,系统默认载入助手示例
  247. * <code>
  248. * if (!function_exists('HelloDede'))
  249. * {
  250. * function HelloDede()
  251. * {
  252. * echo "Hello! Dede";
  253. * }
  254. * }
  255. * </code>
  256. * 开发中使用这个助手的时候直接使用函数helper('test');初始化它,然后在文件中就可以直接使用:HelloDede();调用
  257. *
  258. * @access public
  259. * @param mix $helpers 助手名称,可以是数组,可以是单个字符串
  260. * @return void
  261. */
  262. $_helpers = array();
  263. function helper($helpers)
  264. {
  265. //如果是数组,则进行递归操作
  266. if (is_array($helpers)) {
  267. foreach ($helpers as $dede) {
  268. helper($dede);
  269. }
  270. return;
  271. }
  272. if (isset($_helpers[$helpers])) {
  273. return;
  274. }
  275. if (file_exists(DEDEINC.'/helpers/'.$helpers.'.helper.php')) {
  276. include_once(DEDEINC.'/helpers/'.$helpers.'.helper.php');
  277. $_helpers[$helpers] = TRUE;
  278. }
  279. //无法载入助手
  280. if (!isset($_helpers[$helpers])) {
  281. exit('Unable to load the requested file: helpers/'.$helpers.'.helper.php');
  282. }
  283. }
  284. function dede_htmlspecialchars($str)
  285. {
  286. global $cfg_soft_lang;
  287. if (version_compare(PHP_VERSION, '5.4.0', '<')) return htmlspecialchars($str);
  288. if ($cfg_soft_lang == 'gb2312') return htmlspecialchars($str, ENT_COMPAT, 'ISO-8859-1');
  289. else return htmlspecialchars($str);
  290. }
  291. /**
  292. * 载入助手,这里会员载入用helps载入多个助手
  293. *
  294. * @access public
  295. * @param string
  296. * @return string
  297. */
  298. function helpers($helpers)
  299. {
  300. helper($helpers);
  301. }
  302. //兼容php4的file_put_contents
  303. if (!function_exists('file_put_contents')) {
  304. function file_put_contents($n, $d)
  305. {
  306. $f = @fopen($n, "w");
  307. if (!$f) {
  308. return FALSE;
  309. } else {
  310. fwrite($f, $d);
  311. fclose($f);
  312. return TRUE;
  313. }
  314. }
  315. }
  316. /**
  317. * 短消息函数,可以在某个动作处理后友好的系统提示
  318. *
  319. * @param string $msg 消息系统提示
  320. * @param string $gourl 跳转地址
  321. * @param int $onlymsg 仅显示信息
  322. * @param int $limittime 限制时间
  323. * @param string $btnmsg 按钮提示
  324. * @param string $target 跳转类型
  325. * @return void
  326. */
  327. function ShowMsg($msg, $gourl, $onlymsg = 0, $limittime = 0)
  328. {
  329. if (isset($GLOBALS['format']) && strtolower($GLOBALS['format'])==='json') {
  330. echo json_encode(array(
  331. "code"=>0,
  332. "msg"=>$msg,
  333. "gourl"=>$gourl,
  334. ));
  335. return;
  336. }
  337. if (empty($GLOBALS['cfg_plus_dir'])) $GLOBALS['cfg_plus_dir'] = '..';
  338. $htmlhead = "<!DOCTYPE html><html><head><meta charset='utf-8'><meta http-equiv='X-UA-Compatible' content='IE=Edge,chrome=1'><meta name='viewport' content='width=device-width,initial-scale=1'><title>系统提示</title><link rel='stylesheet' href='/static/web/css/bootstrap.min.css'><link rel='stylesheet' href='/static/web/css/admin.css'></head><base target='_self'><body class='body-bg'><script>";
  339. $htmlfoot = "</script></body></html>";
  340. $litime = ($limittime == 0 ? 1000 : $limittime);
  341. $func = '';
  342. if ($gourl == '-1') {
  343. if ($limittime == 0) $litime = 5000;
  344. $gourl = "javascript:history.go(-1);";
  345. }
  346. if ($gourl == '' || $onlymsg == 1) {
  347. $msg = "<script>alert(\"".str_replace("\"", "“", $msg)."\");</script>";
  348. } else {
  349. //当网址为:close::objname时,关闭父框架的id=objname元素
  350. if (preg_match('/close::/', $gourl)) {
  351. $tgobj = trim(preg_replace('/close::/', '', $gourl));
  352. $gourl = 'javascript:;';
  353. $func .= "window.parent.document.getElementById('{$tgobj}').style.display='none';\r\n";
  354. }
  355. $func .= "var pgo=0;function JumpUrl(){if (pgo==0){location='$gourl'; pgo=1;}}";
  356. $rmsg = $func;
  357. $rmsg .= "document.write(\"<div class='tips'><div class='tips-box'><div class='tips-head'><p>系统提示</p></div>\");";
  358. $rmsg .= "document.write(\"<div class='tips-body'>\");";
  359. $rmsg .= "document.write(\"".str_replace("\"", "“", $msg)."\");";
  360. $rmsg .= "document.write(\"";
  361. if ($onlymsg == 0) {
  362. if ($gourl != 'javascript:;' && $gourl != '') {
  363. $rmsg .= "<div class='text-center mt-3'><a href='{$gourl}' class='btn btn-success btn-sm'>点击反应</a></div>\");";
  364. $rmsg .= "setTimeout('JumpUrl()', $litime);";
  365. } else {
  366. $rmsg .= "</div>\");";
  367. }
  368. } else {
  369. $rmsg .= "</div></div>\");";
  370. }
  371. $msg = $htmlhead.$rmsg.$htmlfoot;
  372. }
  373. echo $msg;
  374. }
  375. /**
  376. * 表中是否存在某个字段
  377. *
  378. * @param mixed $tablename 表名称
  379. * @param mixed $field 字段名
  380. * @return void
  381. */
  382. function TableHasField($tablename, $field)
  383. {
  384. global $dsql;
  385. $dsql->GetTableFields($tablename,"tfd");
  386. while ($r = $dsql->GetFieldObject("tfd")) {
  387. if ($r->name === $field) {
  388. return true;
  389. }
  390. }
  391. return false;
  392. }
  393. function GetSimpleServerSoftware()
  394. {
  395. if (preg_match("#^php#i",$_SERVER["SERVER_SOFTWARE"])) {
  396. return 'PHP Server';
  397. } else if (preg_match("#^apache#i",$_SERVER["SERVER_SOFTWARE"])){
  398. return 'Apache';
  399. } else if (preg_match("#^nginx#i",$_SERVER["SERVER_SOFTWARE"])){
  400. return 'Nginx';
  401. } else if (preg_match("#^microsoft-iis#i",$_SERVER["SERVER_SOFTWARE"])){
  402. return 'IIS';
  403. } else if (preg_match("#^caddy#i",$_SERVER["SERVER_SOFTWARE"])){
  404. return 'Caddy';
  405. } else {
  406. return 'Other';
  407. }
  408. }
  409. /**
  410. * 获取验证码的session值
  411. *
  412. * @return string
  413. */
  414. function GetCkVdValue()
  415. {
  416. @session_id($_COOKIE['PHPSESSID']);
  417. @session_start();
  418. return isset($_SESSION['securimage_code_value']) ? $_SESSION['securimage_code_value'] : '';
  419. }
  420. /**
  421. * PHP某些版本有Bug,不能在同一作用域中同时读session并改注销它,因此调用后需执行本函数
  422. *
  423. * @return void
  424. */
  425. function ResetVdValue()
  426. {
  427. @session_start();
  428. $_SESSION['securimage_code_value'] = '';
  429. }
  430. function IndexSub($idx, $num)
  431. {
  432. return intval($idx) - intval($num) == 0 ? '0 ' : intval($idx) - intval($num);
  433. }
  434. /**
  435. * HideEmail隐藏邮箱
  436. *
  437. * @param mixed $email
  438. * @return string
  439. */
  440. function HideEmail($email)
  441. {
  442. if (empty($email)) return "暂无";
  443. $em = explode("@",$email);
  444. $name = implode('@', array_slice($em, 0, count($em)-1));
  445. $len = floor(strlen($name)/2);
  446. return substr($name,0, $len).str_repeat('*', $len)."@".end($em);
  447. }
  448. //用来返回index的active
  449. function IndexActive($idx)
  450. {
  451. if ($idx == 1) {
  452. return ' active';
  453. } else {
  454. return '';
  455. }
  456. }
  457. //是否是HTTPS
  458. function IsSSL()
  459. {
  460. if (@$_SERVER['HTTPS'] && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
  461. return true;
  462. } elseif ('https' == @$_SERVER['REQUEST_SCHEME']) {
  463. return true;
  464. } elseif ('443' == $_SERVER['SERVER_PORT']) {
  465. return true;
  466. } elseif ('https' == @$_SERVER['HTTP_X_FORWARDED_PROTO']) {
  467. return true;
  468. }
  469. return false;
  470. }
  471. //获取对应版本号的更新SQL
  472. function GetUpdateSQL()
  473. {
  474. global $cfg_dbprefix, $cfg_dbtype, $cfg_db_language;
  475. $result = array();
  476. $query = '';
  477. $sql4tmp = "ENGINE=MyISAM DEFAULT CHARSET=".$cfg_db_language;
  478. $fp = fopen(DEDEROOT.'/install/update.txt','r');
  479. $sqls = array();
  480. $current_ver = "";
  481. while(!feof($fp))
  482. {
  483. $line = rtrim(fgets($fp,1024));
  484. if (preg_match("/\-\- ([\d\.]+)/",$line,$matches)) {
  485. if (count($sqls) > 0) {
  486. $result[$current_ver] = $sqls;
  487. }
  488. $sqls = array();
  489. $current_ver = $matches[1];
  490. }
  491. if (preg_match("#;$#", $line)) {
  492. $query .= $line."\n";
  493. $query = str_replace('#@__',$cfg_dbprefix,$query);
  494. if ($cfg_dbtype == 'sqlite') {
  495. $query = preg_replace('/character set (.*?) /i','',$query);
  496. $query = preg_replace('/unsigned/i','',$query);
  497. $query = str_replace('TYPE=MyISAM','',$query);
  498. $query = preg_replace ('/TINYINT\(([\d]+)\)/i','INTEGER',$query);
  499. $query = preg_replace ('/mediumint\(([\d]+)\)/i','INTEGER',$query);
  500. $query = preg_replace ('/smallint\(([\d]+)\)/i','INTEGER',$query);
  501. $query = preg_replace('/int\(([\d]+)\)/i','INTEGER',$query);
  502. $query = preg_replace('/auto_increment/i','PRIMARY KEY AUTOINCREMENT',$query);
  503. $query = preg_replace('/,([\t\s ]+)KEY(.*?)MyISAM;/','',$query);
  504. $query = preg_replace('/,([\t\s ]+)KEY(.*?);/',');',$query);
  505. $query = preg_replace('/,([\t\s ]+)UNIQUE KEY(.*?);/',');',$query);
  506. $query = preg_replace('/set\(([^\)]*?)\)/','varchar',$query);
  507. $query = preg_replace('/enum\(([^\)]*?)\)/','varchar',$query);
  508. if (preg_match("/PRIMARY KEY AUTOINCREMENT/",$query)) {
  509. $query = preg_replace('/,([\t\s ]+)PRIMARY KEY([\t\s ]+)\(`([0-9a-zA-Z]+)`\)/i','',$query);
  510. }
  511. $sqls[] = $query;
  512. } else {
  513. if (preg_match('#CREATE#i', $query)) {
  514. $sqls[] = preg_replace("#TYPE=MyISAM#i",$sql4tmp,$query);
  515. } else {
  516. $sqls[] = $query;
  517. }
  518. }
  519. $query='';
  520. } else if (!preg_match("#^(\/\/|--)#", $line)) {
  521. $query .= $line;
  522. }
  523. }
  524. if (count($sqls) > 0) {
  525. $result[$current_ver] = $sqls;
  526. }
  527. fclose($fp);
  528. return $result;
  529. }
  530. /*会员中心调用主题模板<?php obtaintheme('head.htm');?>*/
  531. if (!function_exists('obtaintheme')) {
  532. require_once DEDEINC."/archive/partview.class.php";
  533. function obtaintheme($path)
  534. {
  535. global $cfg_basedir, $cfg_templets_dir, $cfg_df_style;
  536. $tmpfile = $cfg_basedir.$cfg_templets_dir.'/'.$cfg_df_style.'/'.$path;
  537. $dtp = new PartView();
  538. $dtp->SetTemplet($tmpfile);
  539. $dtp->Display();
  540. }
  541. }
  542. //标签调用[field:id function='obtaintags(@me,3)'/]3表示调用文档3个标签
  543. if (!function_exists('obtaintags')) {
  544. function obtaintags($aid, $num = 3)
  545. {
  546. global $dsql, $cfg_cmspath;
  547. $tags = '';
  548. $query = "SELECT * FROM `#@__taglist` WHERE aid='$aid' LIMIT $num";
  549. $dsql->Execute('tag',$query);
  550. while($row = $dsql->GetArray('tag')) {
  551. $link = $cfg_cmspath."/apps/tags.php?/{$row['tid']}";
  552. $tags .= ($tags==''?"<a href='{$link}'>{$row['tag']}</a>" : "<a href='{$link}'>{$row['tag']}</a>");
  553. }
  554. return $tags;
  555. }
  556. }
  557. //提取文档多图片[field:body function='obtainimgs(@me,3)'/]3表示调用文档3张图片,则附加字段需添加body字段调用
  558. if (!function_exists('obtainimgs')) {
  559. function obtainimgs($string, $num)
  560. {
  561. preg_match_all("/<img([^>]*)\s*src=('|\")([^'\"]+)('|\")/", $string, $matches);
  562. $imgsrc_arr = array_unique($matches[3]);
  563. $count = count($imgsrc_arr);
  564. $i = 0;
  565. foreach($imgsrc_arr as $imgsrc)
  566. {
  567. if ($i == $num) break;
  568. $result .= "<img src=\"$imgsrc\">";
  569. $i++;
  570. }
  571. return $result;
  572. }
  573. }
  574. //联动单筛选{dede:php}obtainfilter(模型id,类型,'字段1,字段2');{/dede:php}类型表示前台展现方式对应case值
  575. function obtainfilter($channelid, $type = 1, $fieldsnamef = '', $defaulttid = 0, $toptid = 0, $loadtype = 'autofield')
  576. {
  577. global $tid, $dsql, $id, $aid;
  578. $tid = $defaulttid ? $defaulttid : $tid;
  579. if ($id!="" || $aid!="") {
  580. $arcid = $id!="" ? $id : $aid;
  581. $tidsq = $dsql->GetOne("SELECT * FROM `#@__archives` WHERE id='$arcid'");
  582. $tid = $toptid==0 ? $tidsq["typeid"] : $tidsq["topid"];
  583. }
  584. $nofilter = (isset($_REQUEST['TotalResult']) ? "&TotalResult=".$_REQUEST['TotalResult'] : '').(isset($_REQUEST['PageNo']) ? "&PageNo=".$_REQUEST['PageNo'] : '');
  585. $filterarr = string_filter(stripos($_SERVER['REQUEST_URI'], "list.php?tid=") ? str_replace($nofilter, '', $_SERVER['REQUEST_URI']) : $GLOBALS['cfg_cmsurl']."/apps/list.php?tid=".$tid);
  586. $cInfos = $dsql->GetOne("SELECT * FROM `#@__channeltype` WHERE id='$channelid'");
  587. $fieldset=$cInfos['fieldset'];
  588. $dtp = new DedeTagParse();
  589. $dtp->SetNameSpace('field', '<', '>');
  590. $dtp->LoadSource($fieldset);
  591. $dede_addonfields = '';
  592. if (is_array($dtp->CTags)) {
  593. foreach($dtp->CTags as $tida=>$ctag)
  594. {
  595. $fieldsname = $fieldsnamef ? explode(",", $fieldsnamef) : explode(",", $ctag->GetName());
  596. if (($loadtype!='autofield' || ($loadtype=='autofield' && $ctag->GetAtt('autofield')==1)) && in_array($ctag->GetName(), $fieldsname)) {
  597. $href1 = explode($ctag->GetName().'=', $filterarr);
  598. $href2 = explode('&', $href1[1]);
  599. $fields_value = $href2[0];
  600. switch ($type) {
  601. case 1:
  602. $dede_addonfields .= '<div class="mb-3">';
  603. $dede_addonfields .= (preg_match("/&".$ctag->GetName()."=/is",$filterarr,$regm) ? '<a href="'.str_replace("&".$ctag->GetName()."=".$fields_value,"",$filterarr).'" class="btn btn-outline-success btn-sm">全部</a>' : '<a href="'.str_replace("&".$ctag->GetName()."=".$fields_value,"",$filterarr).'" class="btn btn-success btn-sm">全部</a>');
  604. $addonfields_items = explode(",",$ctag->GetAtt('default'));
  605. for ($i=0; $i<count($addonfields_items); $i++)
  606. {
  607. $href = stripos($filterarr,$ctag->GetName().'=') ? str_replace("=".$fields_value,"=".urlencode($addonfields_items[$i]),$filterarr) : $filterarr.'&'.$ctag->GetName().'='.urlencode($addonfields_items[$i]);
  608. $dede_addonfields .= ($fields_value!=urlencode($addonfields_items[$i]) ? '<a title="'.$addonfields_items[$i].'" href="'.$href.'" class="btn btn-outline-success btn-sm">'.$addonfields_items[$i].'</a>' : '<a href="'.$href.'" class="btn btn-success btn-sm">'.$addonfields_items[$i].'</a>');
  609. }
  610. $dede_addonfields .= '</div>';
  611. break;
  612. case 2:
  613. $dede_addonfields .= '<select name="filter'.$ctag->GetName().'" onchange="window.location=this.options[this.selectedIndex].value" class="form-control w-25 mr-3">
  614. '.'<option value="'.str_replace("&".$ctag->GetName()."=".$fields_value,"",$filterarr).'">全部</option>';
  615. $addonfields_items = explode(",",$ctag->GetAtt('default'));
  616. for ($i=0; $i<count($addonfields_items); $i++)
  617. {
  618. $href = stripos($filterarr,$ctag->GetName().'=') ? str_replace("=".$fields_value,"=".urlencode($addonfields_items[$i]),$filterarr) : $filterarr.'&'.$ctag->GetName().'='.urlencode($addonfields_items[$i]);
  619. $dede_addonfields .= '<option value="'.$href.'"'.($fields_value==urlencode($addonfields_items[$i]) ? ' selected="selected"' : '').'>'.$addonfields_items[$i].'</option>
  620. ';
  621. }
  622. $dede_addonfields .= '</select>';
  623. break;
  624. case 3:
  625. $dede_addonfields .= '<div class="mb-3">';
  626. $dede_addonfields .= (preg_match("/&".$ctag->GetName()."=/is",$filterarr,$regm) ? '<a href="'.str_replace("&".$ctag->GetName()."=".$fields_value,"",$filterarr).'"><input type="radio" name="filter'.$ctag->GetName().'" value="'.str_replace("&".$ctag->GetName()."=".$fields_value,"",$filterarr).'" onclick="window.location=this.value">全部</a>' : '<span><input type="radio" name="filter'.$ctag->GetName().'" checked="checked">全部</span>');
  627. $addonfields_items = explode(",",$ctag->GetAtt('default'));
  628. for ($i=0; $i<count($addonfields_items); $i++)
  629. {
  630. $href = stripos($filterarr,$ctag->GetName().'=') ? str_replace("=".$fields_value,"=".urlencode($addonfields_items[$i]),$filterarr) : $filterarr.'&'.$ctag->GetName().'='.urlencode($addonfields_items[$i]);
  631. $dede_addonfields .= ($fields_value!=urlencode($addonfields_items[$i]) ? '<a title="'.$addonfields_items[$i].'" href="'.$href.'"><input type="radio" name="filter'.$ctag->GetName().'" value="'.$href.'" onclick="window.location=this.value">'.$addonfields_items[$i].'</a>' : '<span><input type="radio" name="filter'.$ctag->GetName().'" checked="checked">'.$addonfields_items[$i].'</span>');
  632. }
  633. $dede_addonfields .= '</div>';
  634. break;
  635. }
  636. }
  637. }
  638. }
  639. echo $dede_addonfields;
  640. }
  641. //联动单筛选获取附加表
  642. function litimgurls($imgid = 0)
  643. {
  644. global $dsql, $lit_imglist;
  645. $row = $dsql->GetOne("SELECT c.addtable FROM `#@__archives` AS a LEFT JOIN `#@__channeltype` AS c ON a.channel=c.id WHERE a.id='$imgid'");
  646. $addtable = trim($row['addtable']);
  647. $row = $dsql->GetOne("SELECT imgurls FROM `$addtable` WHERE aid='$imgid'");
  648. $ChannelUnit = new ChannelUnit(2, $imgid);
  649. $lit_imglist = $ChannelUnit->GetlitImgLinks($row['imgurls']);
  650. return $lit_imglist;
  651. }
  652. //联动单筛选字符过滤函数
  653. function string_filter($str, $stype = "inject")
  654. {
  655. if ($stype == "inject") {
  656. $str = str_replace(
  657. array("select", "insert", "update", "delete", "alter", "cas", "union", "into", "load_file", "outfile", "create", "join", "where", "like", "drop", "modify", "rename", "'", "/*", "*", "../", "./"),
  658. array("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""),
  659. $str
  660. );
  661. } else if ($stype == "xss") {
  662. $farr = array("/\s+/", "/<(\/?)(script|META|STYLE|HTML|HEAD|BODY|STYLE |i?frame|b|strong|style|html|img|P|o:p|iframe|u|em|strike|BR|div|a|TABLE|TBODY|object|tr|td|st1:chsdate|FONT|span|MARQUEE|body|title|\r\n|link|meta|\?|\%)([^>]*?)>/isU", "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU",);
  663. $tarr = array(" ", "", "\\1\\2",);
  664. $str = preg_replace($farr, $tarr, $str);
  665. $str = str_replace(
  666. array("<", ">", "'", "\"", ";", "/*", "*", "../", "./"),
  667. array("&lt;", "&gt;", "", "", "", "", "", "", ""),
  668. $str
  669. );
  670. }
  671. return $str;
  672. }
  673. /**
  674. * GetMimeTypeOrExtension
  675. *
  676. * @param mixed $str 字符串
  677. * @param mixed $t 类型,0获取mime type,1获取扩展名
  678. * @return string
  679. */
  680. function GetMimeTypeOrExtension($str, $t = 0) {
  681. $mime_types = array(
  682. 'aac' => 'audio/aac',
  683. 'abw' => 'application/x-abiword',
  684. 'arc' => 'application/x-freearc',
  685. 'avi' => 'video/x-msvideo',
  686. 'azw' => 'application/vnd.amazon.ebook',
  687. 'bin' => 'application/octet-stream',
  688. 'bmp' => 'image/bmp',
  689. 'bz' => 'application/x-bzip',
  690. 'bz2' => 'application/x-bzip2',
  691. 'csh' => 'application/x-csh',
  692. 'css' => 'text/css',
  693. 'csv' => 'text/csv',
  694. 'doc' => 'application/msword',
  695. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  696. 'eot' => 'application/vnd.ms-fontobject',
  697. 'epub' => 'application/epub+zip',
  698. 'gif' => 'image/gif',
  699. 'htm' => 'text/html',
  700. 'html' => 'text/html',
  701. 'ico' => 'image/vnd.microsoft.icon',
  702. 'ics' => 'text/calendar',
  703. 'jar' => 'application/java-archive',
  704. 'jpeg' => 'image/jpeg',
  705. 'jpg' => 'image/jpeg',
  706. 'js' => 'text/javascript',
  707. 'json' => 'application/json',
  708. 'jsonld' => 'application/ld+json',
  709. 'mid' => 'audio/midi',
  710. 'midi' => 'audio/midi',
  711. 'mjs' => 'text/javascript',
  712. 'mp3' => 'audio/mpeg',
  713. 'mp4' => 'video/mp4',
  714. 'mpeg' => 'video/mpeg',
  715. 'mpkg' => 'application/vnd.apple.installer+xml',
  716. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  717. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  718. 'odt' => 'application/vnd.oasis.opendocument.text',
  719. 'oga' => 'audio/ogg',
  720. 'ogv' => 'video/ogg',
  721. 'ogx' => 'application/ogg',
  722. 'otf' => 'font/otf',
  723. 'png' => 'image/png',
  724. 'pdf' => 'application/pdf',
  725. 'ppt' => 'application/vnd.ms-powerpoint',
  726. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  727. 'rar' => 'application/x-rar-compressed',
  728. 'rtf' => 'application/rtf',
  729. 'sh' => 'application/x-sh',
  730. 'svg' => 'image/svg+xml',
  731. 'swf' => 'application/x-shockwave-flash',
  732. 'tar' => 'application/x-tar',
  733. 'tif' => 'image/tiff',
  734. 'tiff' => 'image/tiff',
  735. 'ttf' => 'font/ttf',
  736. 'txt' => 'text/plain',
  737. 'vsd' => 'application/vnd.visio',
  738. 'wav' => 'audio/wav',
  739. 'weba' => 'audio/webm',
  740. 'webm' => 'video/webm',
  741. 'webp' => 'image/webp',
  742. 'woff' => 'font/woff',
  743. 'woff2' => 'font/woff2',
  744. 'xhtml' => 'application/xhtml+xml',
  745. 'xls' => 'application/vnd.ms-excel',
  746. 'xlsx' => 'application/vnd.ms-excel',
  747. 'xml' => 'application/xml',
  748. 'xul' => 'application/vnd.mozilla.xul+xml',
  749. 'zip' => 'application/zip',
  750. '3gp' => 'video/3gpp',
  751. '3g2' => 'video/3gpp2',
  752. '7z' => 'application/x-7z-compressed',
  753. 'wmv' => 'video/x-ms-asf',
  754. 'wma' => 'audio/x-ms-wma',
  755. 'mov' => 'video/quicktime',
  756. 'rm' => 'application/vnd.rn-realmedia',
  757. 'mpg' => 'video/mpeg',
  758. 'mpga' => 'audio/mpeg',
  759. );
  760. if ($t===0) {
  761. return isset($mime_types[$str])? $mime_types[$str] : 'application/octet-stream';
  762. } else {
  763. foreach ($mime_types as $key => $value) {
  764. if ($value == $str) return $key;
  765. }
  766. return "dedebiz";
  767. }
  768. }
  769. //自定义函数接口
  770. if (file_exists(DEDEINC.'/extend.func.php')) {
  771. require_once(DEDEINC.'/extend.func.php');
  772. }
  773. ?>