返回列表 发帖
查看: 12819|回复: 2

discuz缓存应用详解.

83

主题

-6

回帖

329

积分

炉火纯青

贡献
2 点
金币
241 个
发表于 2019-6-2 16:52:33 | 显示全部楼层 |阅读模式
example.php 测试文件解释
  1. <?php
  2. require_once './include/common.inc.php';
  3. require_once './include/cache.func.php';

  4. //参数说明:  缓存标识名, 内置数据取得标识, 缓存数据(string), 缓存前缀.
  5. //writetocache('文件名', $cachenames, $cachedata = '', $prefix = 'cache_')

  6. // 第一种模式. 指针转成变量,写入到test.php当中, 目录在forundata/cache/
  7. writetocache('test','',getcachevars(array('var'=>'变量值','phps'=>'discuz.net')), $prefix = 'caches_');

  8. //第二种模式,这种比较好, 生成一个数组, 写在文件test2.php中.
  9. writetocache('test2', '', '$_DCACHE[\'settings\'] = '.arrayeval(range(1,20)).";\n\n", $prefix = 'caches_');

  10. //第三种模式,$cachedata内容是什么, 就写入是什么, 很强悍.
  11. writetocache('test3', '',"array('var1'=>'mysql php','var2'=>'fenanr')", $prefix = 'caches_');

  12. //第四种模式,当没有$prefix值时, 默认生成cache_xxxx.php的缓存命名.
  13. writetocache('test4', '',"array('var1'=>'php 6','var2'=>'discuz')");
  14. ?>
复制代码
总结:
   为了支撑高压力及访问量下的程序动作正常, discuz的缓存结构写得非常复杂. 当然, 不同的人思考方式不相同.
   这次用了几个常用例子讲解缓存系统的应用, 希望可以帮助到需要的朋友.
   由于限制了字节, 所以函数解释放二楼.
回复

使用道具 举报

83

主题

-6

回帖

329

积分

炉火纯青

贡献
2 点
金币
241 个
 楼主| 发表于 2019-6-2 17:04:37 | 显示全部楼层

cache.func.php文件详解
  1. <?php

  2. /*
  3.         [Discuz!] (C)2001-2009 Comsenz Inc.
  4.         This is NOT a freeware, use is subject to license terms

  5.         $Id: cache.func.php 21311 2009-11-26 01:35:43Z liulanbo $
  6. */

  7. define('DISCUZ_KERNEL_VERSION', '7.2');
  8. define('DISCUZ_KERNEL_RELEASE', '20091126');


  9. function updatecache($cachename = '') {
  10.         //分别引入 mysql操作库存,论坛名称,数据库前缀,最大论坛时间(估计是授权用户专用)
  11.         global $db, $bbname, $tablepre, $maxbdays;
  12.         //静态化一下数组,比如$cachename = setings     就读到这个数组  'settings'        => array('settings'),
  13.         static $cachescript = array
  14.                 (

  15.                 'settings'        => array('settings'),
  16.                 'forums'        => array('forums'),
  17.                 'icons'                => array('icons'),
  18.                 'stamps'        => array('stamps'),
  19.                 'ranks'                => array('ranks'),
  20.                 'usergroups'        => array('usergroups'),
  21.                 'request'        => array('request'),
  22.                 'medals'        => array('medals'),
  23.                 'magics'        => array('magics'),
  24.                 'topicadmin'        => array('modreasons', 'stamptypeid'),
  25.                 'archiver'        => array('advs_archiver'),
  26.                 'register'        => array('advs_register', 'ipctrl'),
  27.                 'faqs'                => array('faqs'),
  28.                 'secqaa'        => array('secqaa'),
  29.                 'censor'        => array('censor'),
  30.                 'ipbanned'        => array('ipbanned'),
  31.                 'smilies'        => array('smilies_js'),
  32.                 'forumstick' => array('forumstick'),

  33.                 'index'                => array('announcements', 'onlinelist', 'forumlinks', 'advs_index', 'heats'),
  34.                 'forumdisplay'        => array('smilies', 'announcements_forum', 'globalstick', 'forums', 'icons', 'onlinelist', 'advs_forumdisplay', 'forumstick'),
  35.                 'viewthread'        => array('smilies', 'smileytypes', 'forums', 'usergroups', 'ranks', 'stamps', 'bbcodes', 'smilies', 'advs_viewthread', 'tags_viewthread', 'custominfo', 'groupicon', 'focus', 'stamps'),
  36.                 'post'                => array('bbcodes_display', 'bbcodes', 'smileycodes', 'smilies', 'smileytypes', 'icons', 'domainwhitelist'),
  37.                 'profilefields'        => array('fields_required', 'fields_optional'),
  38.                 'viewpro'        => array('fields_required', 'fields_optional', 'custominfo'),
  39.                 'bbcodes'        => array('bbcodes', 'smilies', 'smileytypes'),
  40.                 );
  41.         //当最大时间有值时,就将在$cachescript 增加两段
  42.         if($maxbdays) {
  43.                 $cachescript['birthdays'] = array('birthdays');
  44.                 $cachescript['index'][]   = 'birthdays_index';
  45.         }
  46.         // 组成更新数组.
  47.         $updatelist = empty($cachename) ? array_values($cachescript) : (is_array($cachename) ? array('0' => $cachename) : array(array('0' => $cachename)));
  48.         $updated = array();
  49.         // 现在循环. 由于是二维数组, 所以循环两次.
  50.         foreach($updatelist as $value) {
  51.                 foreach($value as $cname) {
  52.                         //判断如果$updated数组为假,或者$updated中没有$cname的值,就进入, 目的是为了防止重复
  53.                         if(empty($updated) || !in_array($cname, $updated)) {
  54.                                 $updated[] = $cname;  //进来一次, 就丢进数组, 以便循环中再次使用.
  55.                                 getcachearray($cname);   // 取得相应的值,并且生成缓存.
  56.                         }
  57.                 }
  58.         }
  59.         
  60.         // 假如是空参数进入, 就对所有的缓存标识作判断.
  61.         foreach($cachescript as $script => $cachenames) {
  62.                 if(empty($cachename) || (!is_array($cachename) && in_array($cachename, $cachenames)) || (is_array($cachename) && array_intersect($cachename, $cachenames))) {
  63.                         $cachedata = '';
  64.                         $query = $db->query("SELECT data FROM {$tablepre}caches WHERE cachename in(".implodeids($cachenames).")");
  65.                         while($data = $db->fetch_array($query)) {
  66.                                 $cachedata .= $data['data'];
  67.                         }
  68.                         writetocache($script, $cachenames, $cachedata);
  69.                 }
  70.         }
  71.         
  72.         //假如参数为空,或者参数为styles 就处理模板风格等缓存
  73.         if(!$cachename || $cachename == 'styles') {
  74.                 $stylevars = $styledata = $styleicons = array();
  75.                 $defaultstyleid = $db->result_first("SELECT value FROM {$tablepre}settings WHERE variable = 'styleid'");
  76.                 list(, $imagemaxwidth) = explode("\t", $db->result_first("SELECT value FROM {$tablepre}settings WHERE variable = 'zoomstatus'"));
  77.                 $imagemaxwidth = $imagemaxwidth ? $imagemaxwidth : 600;
  78.                 $imagemaxwidthint = intval($imagemaxwidth);
  79.                 $query = $db->query("SELECT sv.* FROM {$tablepre}stylevars sv LEFT JOIN {$tablepre}styles s ON s.styleid = sv.styleid AND (s.available=1 OR s.styleid='$defaultstyleid')");
  80.                 while($var = $db->fetch_array($query)) {
  81.                         $stylevars[$var['styleid']][$var['variable']] = $var['substitute'];
  82.                 }
  83.                 $query = $db->query("SELECT s.*, t.directory AS tpldir FROM {$tablepre}styles s LEFT JOIN {$tablepre}templates t ON s.templateid=t.templateid WHERE s.available=1 OR s.styleid='$defaultstyleid'");
  84.                 while($data = $db->fetch_array($query)) {
  85.                         $data = array_merge($data, $stylevars[$data['styleid']]);
  86.                         $datanew = array();
  87.                         $data['imgdir'] = $data['imgdir'] ? $data['imgdir'] : 'images/default';
  88.                         $data['styleimgdir'] = $data['styleimgdir'] ? $data['styleimgdir'] : $data['imgdir'];
  89.                         foreach($data as $k => $v) {
  90.                                 if(substr($k, -7, 7) == 'bgcolor') {
  91.                                         $newkey = substr($k, 0, -7).'bgcode';
  92.                                         $datanew[$newkey] = setcssbackground($data, $k);
  93.                                 }
  94.                         }
  95.                         $data = array_merge($data, $datanew);
  96.                         $styleicons[$data['styleid']] = $data['menuhover'];
  97.                         if(strstr($data['boardimg'], ',')) {
  98.                                 $flash = explode(",", $data['boardimg']);
  99.                                 $flash[0] = trim($flash[0]);
  100.                                 $flash[0] = preg_match('/^http:\/\//i', $flash[0]) ? $flash[0] : $data['styleimgdir'].'/'.$flash[0];
  101.                                 $data['boardlogo'] = "<embed src="".$flash[0]."" width="".trim($flash[1])."" height="".trim($flash[2])."" type="application/x-shockwave-flash" wmode="transparent"></embed>";
  102.                         } else {
  103.                                 $data['boardimg'] = preg_match('/^http:\/\//i', $data['boardimg']) ? $data['boardimg'] : $data['styleimgdir'].'/'.$data['boardimg'];
  104.                                 $data['boardlogo'] = "<img src="$data[boardimg]" alt="$bbname" border="0" />";
  105.                         }
  106.                         $data['bold'] = $data['nobold'] ? 'normal' : 'bold';
  107.                         $contentwidthint = intval($data['contentwidth']);
  108.                         $contentwidthint = $contentwidthint ? $contentwidthint : 600;
  109.                         if(substr(trim($data['contentwidth']), -1, 1) != '%') {
  110.                                 if(substr(trim($imagemaxwidth), -1, 1) != '%') {
  111.                                         $data['imagemaxwidth'] = $imagemaxwidthint > $contentwidthint ? $contentwidthint : $imagemaxwidthint;
  112.                                 } else {
  113.                                         $data['imagemaxwidth'] = intval($contentwidthint * $imagemaxwidthint / 100);
  114.                                 }
  115.                         } else {
  116.                                 if(substr(trim($imagemaxwidth), -1, 1) != '%') {
  117.                                         $data['imagemaxwidth'] = '%'.$imagemaxwidthint;
  118.                                 } else {
  119.                                         $data['imagemaxwidth'] = ($imagemaxwidthint > $contentwidthint ? $contentwidthint : $imagemaxwidthint).'%';
  120.                                 }
  121.                         }
  122.                         $data['verhash'] = random(3);
  123.                         $styledata[] = $data;
  124.                 }
  125.                 foreach($styledata as $data) {
  126.                         $data['styleicons'] = $styleicons;
  127.                         writetocache($data['styleid'], '', getcachevars($data, 'CONST'), 'style_');
  128.                         writetocsscache($data);
  129.                 }
  130.         }
  131.         //假如参数为空,或者参数为usergroups 就处理用户组等缓存
  132.         if(!$cachename || $cachename == 'usergroups') {
  133.                 @include_once DISCUZ_ROOT.'forumdata/cache/cache_settings.php';
  134.                 $threadplugins = !isset($_DCACHE['settings']) ? $GLOBALS['threadplugins'] : $_DCACHE['settings'];
  135.                 $allowthreadplugin = $threadplugins ? unserialize($db->result_first("SELECT value FROM {$tablepre}settings WHERE variable='allowthreadplugin'")) : array();

  136.                 $query = $db->query("SELECT * FROM {$tablepre}usergroups u
  137.                                         LEFT JOIN {$tablepre}admingroups a ON u.groupid=a.admingid");
  138.                 while($data = $db->fetch_array($query)) {
  139.                         $ratearray = array();
  140.                         if($data['raterange']) {
  141.                                 foreach(explode("\n", $data['raterange']) as $rating) {
  142.                                         $rating = explode("\t", $rating);
  143.                                         $ratearray[$rating[0]] = array('min' => $rating[1], 'max' => $rating[2], 'mrpd' => $rating[3]);
  144.                                 }
  145.                         }
  146.                         $data['raterange'] = $ratearray;
  147.                         $data['grouptitle'] = $data['color'] ? '<font color="'.$data['color'].'">'.$data['grouptitle'].'</font>' : $data['grouptitle'];
  148.                         $data['grouptype'] = $data['type'];
  149.                         $data['grouppublic'] = $data['system'] != 'private';
  150.                         $data['groupcreditshigher'] = $data['creditshigher'];
  151.                         $data['groupcreditslower'] = $data['creditslower'];
  152.                         $data['allowthreadplugin'] = $threadplugins ? $allowthreadplugin[$data['groupid']] : array();
  153.                         unset($data['type'], $data['system'], $data['creditshigher'], $data['creditslower'], $data['color'], $data['groupavatar'], $data['admingid']);
  154.                         writetocache($data['groupid'], '', getcachevars($data), 'usergroup_');
  155.                 }
  156.         }

  157.         //假如参数为空,或者参数为admingroups 就处理管理用户组等缓存
  158.         if(!$cachename || $cachename == 'admingroups') {
  159.                 $query = $db->query("SELECT * FROM {$tablepre}admingroups");
  160.                 while($data = $db->fetch_array($query)) {
  161.                         writetocache($data['admingid'], '', getcachevars($data), 'admingroup_');
  162.                 }
  163.         }

  164.         if(!$cachename || $cachename == 'plugins') {
  165.                 $query = $db->query("SELECT pluginid, available, adminid, name, identifier, datatables, directory, copyright, modules FROM {$tablepre}plugins");
  166.                 while($plugin = $db->fetch_array($query)) {
  167.                         $data = array_merge($plugin, array('modules' => array()), array('vars' => array()));
  168.                         $plugin['modules'] = unserialize($plugin['modules']);
  169.                         if(is_array($plugin['modules'])) {
  170.                                 foreach($plugin['modules'] as $module) {
  171.                                         $data['modules'][$module['name']] = $module;
  172.                                 }
  173.                         }
  174.                         $queryvars = $db->query("SELECT variable, value FROM {$tablepre}pluginvars WHERE pluginid='$plugin[pluginid]'");
  175.                         while($var = $db->fetch_array($queryvars)) {
  176.                                 $data['vars'][$var['variable']] = $var['value'];
  177.                         }
  178.                         writetocache($plugin['identifier'], '', "\$_DPLUGIN['$plugin[identifier]'] = ".arrayeval($data), 'plugin_');
  179.                 }
  180.         }
  181.         //假如参数为空,或者参数为threadsorts 就处理主题信息等缓存
  182.         if(!$cachename || $cachename == 'threadsorts') {
  183.                 $sortlist = $templatedata = array();
  184.                 $query = $db->query("SELECT t.typeid AS sortid, tt.optionid, tt.title, tt.type, tt.unit, tt.rules, tt.identifier, tt.description, tv.required, tv.unchangeable, tv.search, tv.subjectshow
  185.                         FROM {$tablepre}threadtypes t
  186.                         LEFT JOIN {$tablepre}typevars tv ON t.typeid=tv.sortid
  187.                         LEFT JOIN {$tablepre}typeoptions tt ON tv.optionid=tt.optionid
  188.                         WHERE t.special='1' AND tv.available='1'
  189.                         ORDER BY tv.displayorder");
  190.                 while($data = $db->fetch_array($query)) {
  191.                         $data['rules'] = unserialize($data['rules']);
  192.                         $sortid = $data['sortid'];
  193.                         $optionid = $data['optionid'];
  194.                         $sortlist[$sortid][$optionid] = array(
  195.                                 'title' => dhtmlspecialchars($data['title']),
  196.                                 'type' => dhtmlspecialchars($data['type']),
  197.                                 'unit' => dhtmlspecialchars($data['unit']),
  198.                                 'identifier' => dhtmlspecialchars($data['identifier']),
  199.                                 'description' => dhtmlspecialchars($data['description']),
  200.                                 'required' => intval($data['required']),
  201.                                 'unchangeable' => intval($data['unchangeable']),
  202.                                 'search' => intval($data['search']),
  203.                                 'subjectshow' => intval($data['subjectshow']),
  204.                                 );

  205.                         if(in_array($data['type'], array('select', 'checkbox', 'radio'))) {
  206.                                 if($data['rules']['choices']) {
  207.                                         $choices = array();
  208.                                         foreach(explode("\n", $data['rules']['choices']) as $item) {
  209.                                                 list($index, $choice) = explode('=', $item);
  210.                                                 $choices[trim($index)] = trim($choice);
  211.                                         }
  212.                                         $sortlist[$sortid][$optionid]['choices'] = $choices;
  213.                                 } else {
  214.                                         $typelist[$sortid][$optionid]['choices'] = array();
  215.                                 }
  216.                         } elseif(in_array($data['type'], array('text', 'textarea'))) {
  217.                                 $sortlist[$sortid][$optionid]['maxlength'] = intval($data['rules']['maxlength']);
  218.                         } elseif($data['type'] == 'image') {
  219.                                 $sortlist[$sortid][$optionid]['maxwidth'] = intval($data['rules']['maxwidth']);
  220.                                 $sortlist[$sortid][$optionid]['maxheight'] = intval($data['rules']['maxheight']);
  221.                         } elseif($data['type'] == 'number') {
  222.                                 $sortlist[$sortid][$optionid]['maxnum'] = intval($data['rules']['maxnum']);
  223.                                 $sortlist[$sortid][$optionid]['minnum'] = intval($data['rules']['minnum']);
  224.                         }
  225.                 }
  226.                 $query = $db->query("SELECT typeid, description, template, stemplate FROM {$tablepre}threadtypes WHERE special='1'");
  227.                 while($data = $db->fetch_array($query)) {
  228.                         $templatedata[$data['typeid']] = $data['template'];
  229.                         $stemplatedata[$data['typeid']] = $data['stemplate'];
  230.                         $threaddesc[$data['typeid']] = dhtmlspecialchars($data['description']);
  231.                 }

  232.                 foreach($sortlist as $sortid => $option) {
  233.                         writetocache($sortid, '', "\$_DTYPE = ".arrayeval($option).";\n\n\$_DTYPETEMPLATE = "".str_replace('"', '"', $templatedata[$sortid])."";\n\n\$_DSTYPETEMPLATE = "".str_replace('"', '"', $stemplatedata[$sortid])."";\n", 'threadsort_');
  234.                 }
  235.         }

  236. }

  237. // 这是css缓存文件生成需要的处理css背景颜色函数
  238. function setcssbackground(&$data, $code) {
  239.         $codes = explode(' ', $data[$code]);
  240.         $css = $codevalue = '';
  241.         for($i = 0; $i < count($codes); $i++) {
  242.                 if($i < 2) {
  243.                         if($codes[$i] != '') {
  244.                                 if($codes[$i]{0} == '#') {
  245.                                         $css .= strtoupper($codes[$i]).' ';
  246.                                         $codevalue = strtoupper($codes[$i]);
  247.                                 } elseif(preg_match('/^http:\/\//i', $codes[$i])) {
  248.                                         $css .= 'url("'.$codes[$i].'") ';
  249.                                 } else {
  250.                                         $css .= 'url("'.$data['styleimgdir'].'/'.$codes[$i].'") ';
  251.                                 }
  252.                         }
  253.                 } else {
  254.                         $css .= $codes[$i].' ';
  255.                 }
  256.         }
  257.         $data[$code] = $codevalue;
  258.         $css = trim($css);
  259.         return $css ? 'background: '.$css : '';
  260. }
  261. // 更新系统配置缓存
  262. function updatesettings() {
  263.         global $_DCACHE;
  264.         if(isset($_DCACHE['settings']) && is_array($_DCACHE['settings'])) {
  265.                 writetocache('settings', '', '$_DCACHE[\'settings\'] = '.arrayeval($_DCACHE['settings']).";\n\n");
  266.         }
  267. }

  268. // 写入缓存文件, 详解一下.
  269. function writetocache($script, $cachenames, $cachedata = '', $prefix = 'cache_') {
  270.         global $authkey;
  271.         //假如$cachenames是数组,并且$cachedata为假
  272.         if(is_array($cachenames) && !$cachedata) {
  273.                 foreach($cachenames as $name) {
  274.                         //赋予内置函数的指定标识, 即可有数据返回
  275.                         $cachedata .= getcachearray($name, $script);
  276.                 }
  277.         }
  278.         $dir = DISCUZ_ROOT.'./forumdata/cache/';
  279.         //如果缓存目录不存在, 就生成一个.
  280.         if(!is_dir($dir)) {
  281.                 @mkdir($dir, 0777);
  282.         }
  283.         if($fp = @fopen("$dir$prefix$script.php", 'wb')) {
  284.                 fwrite($fp, "<?php\n//Discuz! cache file, DO NOT modify me!".
  285.                         "\n//Created: ".date("M j, Y, G:i").
  286.                         "\n//Identify: ".md5($prefix.$script.'.php'.$cachedata.$authkey)."\n\n$cachedata?>");
  287.                 fclose($fp);
  288.         } else {
  289.                 exit('Can not write to cache files, please check directory ./forumdata/ and ./forumdata/cache/ .');
  290.         }
  291. }
  292. // 更新css缓存生成过程中, 里面的路径问题, 参数为css.htm的内容.
  293. function writetocsscache($data) {
  294.         $cssdata = '';
  295.         foreach(array('_common' => array('css_common', 'css_append'),
  296.                         '_special' => array('css_special', 'css_special_append'),
  297.                         '_wysiwyg' => array('css_wysiwyg', '_wysiwyg_append'),
  298.                         '_seditor' => array('css_seditor', 'css_seditor_append'),
  299.                         '_calendar' => array('css_calendar', 'css_calendar_append'),
  300.                         '_moderator' => array('css_moderator', 'css_moderator_append'),
  301.                         '_script' => array('css_script', 'css_script_append'),
  302.                         '_task_newbie' => array('css_task_newbie', 'css_task_newbie_append')
  303.                 ) as $extra => $cssfiles) {
  304.                 $cssdata = '';
  305.                 foreach($cssfiles as $css) {
  306.                         $cssfile = DISCUZ_ROOT.'./'.$data['tpldir'].'/'.$css.'.htm';
  307.                         !file_exists($cssfile) && $cssfile = DISCUZ_ROOT.'./templates/default/'.$css.'.htm';
  308.                         if(file_exists($cssfile)) {
  309.                                 $fp = fopen($cssfile, 'r');
  310.                                 $cssdata .= @fread($fp, filesize($cssfile))."\n\n";
  311.                                 fclose($fp);
  312.                         }
  313.                 }
  314.                 $cssdata = preg_replace("/\{([A-Z0-9]+)\}/e", '\$data[strtolower(\'\1\')]', $cssdata);
  315.                 $cssdata = preg_replace("/<\?.+?\?>\s*/", '', $cssdata);
  316.                 $cssdata = !preg_match('/^http:\/\//i', $data['styleimgdir']) ? str_replace("url("$data[styleimgdir]", "url("../../$data[styleimgdir]", $cssdata) : $cssdata;
  317.                 $cssdata = !preg_match('/^http:\/\//i', $data['styleimgdir']) ? str_replace("url($data[styleimgdir]", "url(../../$data[styleimgdir]", $cssdata) : $cssdata;
  318.                 $cssdata = !preg_match('/^http:\/\//i', $data['imgdir']) ? str_replace("url("$data[imgdir]", "url("../../$data[imgdir]", $cssdata) : $cssdata;
  319.                 $cssdata = !preg_match('/^http:\/\//i', $data['imgdir']) ? str_replace("url($data[imgdir]", "url(../../$data[imgdir]", $cssdata) : $cssdata;
  320.                 if($extra != '_script') {
  321.                         $cssdata = preg_replace(array('/\s*([,;:\{\}])\s*/', '/[\t\n\r]/', '/\/\*.+?\*\//'), array('\\1', '',''), $cssdata);
  322.                 }
  323.                 if(@$fp = fopen(DISCUZ_ROOT.'./forumdata/cache/style_'.$data['styleid'].$extra.'.css', 'w')) {
  324.                         fwrite($fp, $cssdata);
  325.                         fclose($fp);
  326.                 } else {
  327.                         exit('Can not write to cache files, please check directory ./forumdata/ and ./forumdata/cache/ .');
  328.                 }
  329.         }

  330. }

  331. // 将js文件复制到缓存目录.
  332. function writetojscache() {
  333.         $dir = DISCUZ_ROOT.'include/js/';
  334.         $dh = opendir($dir);
  335.         $remove = array(
  336.                 '/(^|\r|\n)\/\*.+?(\r|\n)\*\/(\r|\n)/is',
  337.                 '/\/\/note.+?(\r|\n)/i',
  338.                 '/\/\/debug.+?(\r|\n)/i',
  339.                 '/(^|\r|\n)(\s|\t)+/',
  340.                 '/(\r|\n)/',
  341.         );
  342.         while(($entry = readdir($dh)) !== false) {
  343.                 if(fileext($entry) == 'js') {
  344.                         $jsfile = $dir.$entry;
  345.                         $fp = fopen($jsfile, 'r');
  346.                         $jsdata = @fread($fp, filesize($jsfile));
  347.                         fclose($fp);
  348.                         $jsdata = preg_replace($remove, '', $jsdata);
  349.                         if(@$fp = fopen(DISCUZ_ROOT.'./forumdata/cache/'.$entry, 'w')) {
  350.                                 fwrite($fp, $jsdata);
  351.                                 fclose($fp);
  352.                         } else {
  353.                                 exit('Can not write to cache files, please check directory ./forumdata/ and ./forumdata/cache/ .');
  354.                         }
  355.                 }
  356.         }
  357. }

  358. //取得缓存数组, 内置.  标识名,及文件名.
  359. function getcachearray($cachename, $script = '') {
  360.         global $db, $timestamp, $tablepre, $timeoffset, $maxbdays, $smcols, $smrows, $charset, $scriptlang;
  361.         //省略上千代码.
  362. }

  363. //组成缓存文件需要的数据数组.
  364. function getcachevars($data, $type = 'VAR') {
  365.         $evaluate = '';
  366.         foreach($data as $key => $val) {
  367.                 if(!preg_match("/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/", $key)) {
  368.                         continue;
  369.                 }
  370.                 if(is_array($val)) {
  371.                         $evaluate .= "\$key = ".arrayeval($val).";\n";
  372.                 } else {
  373.                         $val = addcslashes($val, '\'\\');
  374.                         $evaluate .= $type == 'VAR' ? "\$key = '$val';\n" : "define('".strtoupper($key)."', '$val');\n";
  375.                 }
  376.         }
  377.         return $evaluate;
  378. }

  379. //取得广告设置的内容数组.
  380. function advertisement($range) {
  381.         global $db, $tablepre, $timestamp;

  382.         $advs = array();
  383.         $query = $db->query("SELECT * FROM {$tablepre}advertisements WHERE available>'0' AND starttime<='$timestamp' ORDER BY displayorder");
  384.         if($db->num_rows($query)) {
  385.                 while($adv = $db->fetch_array($query)) {
  386.                         if(in_array($adv['type'], array('footerbanner', 'thread'))) {
  387.                                 $parameters = unserialize($adv['parameters']);
  388.                                 $position = isset($parameters['position']) && in_array($parameters['position'], array(2, 3)) ? $parameters['position'] : 1;
  389.                                 $type = $adv['type'].$position;
  390.                         } else {
  391.                                 $type = $adv['type'];
  392.                         }
  393.                         $adv['targets'] = in_array($adv['targets'], array('', 'all')) ? ($type == 'text' ? 'forum' : (substr($type, 0, 6) == 'thread' ? 'forum' : 'all')) : $adv['targets'];
  394.                         foreach(explode("\t", $adv['targets']) as $target) {
  395.                                 if($range == 'index' && substr($target, 0, 3) == 'gid') {
  396.                                         $advs['cat'][$type][substr($target, 3)][] = $adv['advid'];
  397.                                         $advs['items'][$adv['advid']] = $adv['code'];
  398.                                 }
  399.                                 $target = $target == '0' || $type == 'intercat' ? 'index' : (in_array($target, array('all', 'index', 'forumdisplay', 'viewthread', 'register', 'redirect', 'archiver')) ? $target : ($target == 'forum' ? 'forum_all' : 'forum_'.$target));
  400.                                 if((($range == 'forumdisplay' && !in_array($adv['type'], array('thread', 'interthread'))) || $range == 'viewthread') &&  substr($target, 0, 6) == 'forum_') {
  401.                                         if($adv['type'] == 'thread') {
  402.                                                 foreach(isset($parameters['displayorder']) ? explode("\t", $parameters['displayorder']) : array('0') as $postcount) {
  403.                                                         $advs['type'][$type.'_'.$postcount][$target][] = $adv['advid'];
  404.                                                 }
  405.                                         } else {
  406.                                                 $advs['type'][$type][$target][] = $adv['advid'];
  407.                                         }
  408.                                         $advs['items'][$adv['advid']] = $adv['code'];
  409.                                 } elseif($range == 'all' && in_array($target, array('all', 'redirect'))) {
  410.                                         $advs[$target]['type'][$type][] = $adv['advid'];
  411.                                         $advs[$target]['items'][$adv['advid']] = $adv['code'];
  412.                                 } elseif($range == 'index' && $type == 'intercat') {
  413.                                         $parameters = unserialize($adv['parameters']);
  414.                                         foreach(is_array($parameters['position']) ? $parameters['position'] : array('0') as $position) {
  415.                                                 $advs['type'][$type][$position][] = $adv['advid'];
  416.                                                 $advs['items'][$adv['advid']] = $adv['code'];
  417.                                         }
  418.                                 } elseif($target == $range || ($range == 'index' && $target == 'forum_all' && $type == 'text')) {
  419.                                         $advs['type'][$type][] = $adv['advid'];
  420.                                         $advs['items'][$adv['advid']] = $adv['code'];
  421.                                 }
  422.                         }
  423.                 }
  424.         }

  425.         return $advs;
  426. }

  427. // 简单判断.
  428. function pluginmodulecmp($a, $b) {
  429.         return $a['displayorder'] > $b['displayorder'] ? 1 : -1;
  430. }
  431. // 计算长宽的函数
  432. function smthumb($size, $smthumb = 50) {
  433.         if($size[0] <= $smthumb && $size[1] <= $smthumb) {
  434.                 return array('w' => $size[0], 'h' => $size[1]);
  435.         }
  436.         $sm = array();
  437.         $x_ratio = $smthumb / $size[0];
  438.         $y_ratio = $smthumb / $size[1];
  439.         if(($x_ratio * $size[1]) < $smthumb) {
  440.                 $sm['h'] = ceil($x_ratio * $size[1]);
  441.                 $sm['w'] = $smthumb;
  442.         } else {
  443.                 $sm['w'] = ceil($y_ratio * $size[0]);
  444.                 $sm['h'] = $smthumb;
  445.         }
  446.         return $sm;
  447. }

  448. // 处理缓存生成时部分内容样式的解析
  449. function parsehighlight($highlight) {
  450.         if($highlight) {
  451.                 $colorarray = array('', 'red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple', 'gray');
  452.                 $string = sprintf('%02d', $highlight);
  453.                 $stylestr = sprintf('%03b', $string[0]);

  454.                 $style = ' style="';
  455.                 $style .= $stylestr[0] ? 'font-weight: bold;' : '';
  456.                 $style .= $stylestr[1] ? 'font-style: italic;' : '';
  457.                 $style .= $stylestr[2] ? 'text-decoration: underline;' : '';
  458.                 $style .= $string[1] ? 'color: '.$colorarray[$string[1]] : '';
  459.                 $style .= '"';
  460.         } else {
  461.                 $style = '';
  462.         }
  463.         return $style;
  464. }
  465. //  这就是传说的array的立体型输出.
  466. function arrayeval($array, $level = 0) {
  467.         if(!is_array($array)) {
  468.                 return "'".$array."'";
  469.         }
  470.         if(is_array($array) && function_exists('var_export')) {
  471.                 return var_export($array, true);
  472.         }

  473.         $space = '';
  474.         for($i = 0; $i <= $level; $i++) {
  475.                 $space .= "\t";
  476.         }
  477.         $evaluate = "Array\n$space(\n";
  478.         $comma = $space;
  479.         if(is_array($array)) {
  480.                 foreach($array as $key => $val) {
  481.                         $key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
  482.                         $val = !is_array($val) && (!preg_match("/^\-?[1-9]\d*$/", $val) || strlen($val) > 12) ? '\''.addcslashes($val, '\'\\').'\'' : $val;
  483.                         if(is_array($val)) {
  484.                                 $evaluate .= "$comma$key => ".arrayeval($val, $level + 1);
  485.                         } else {
  486.                                 $evaluate .= "$comma$key => $val";
  487.                         }
  488.                         $comma = ",\n$space";
  489.                 }
  490.         }
  491.         $evaluate .= "\n$space)";
  492.         return $evaluate;
  493. }

  494. ?>
复制代码
回复 支持 反对

使用道具 举报

3

主题

118

回帖

183

积分

应用开发者

贡献
0 点
金币
58 个
发表于 2019-6-9 08:43:57 | 显示全部楼层
干活多多,收藏一下
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

  • 关注公众号
  • 有偿服务微信
  • 有偿服务QQ

手机版|小黑屋|Discuz! 官方交流社区 ( 皖ICP备16010102号 |皖公网安备34010302002376号 )|网站地图|star

GMT+8, 2024-3-29 05:01 , Processed in 0.035970 second(s), 5 queries , Redis On.

Powered by Discuz! W1.0 Licensed

Cpoyright © 2001-2024 Discuz! Team.

关灯 快速发帖
有偿服务QQ
有偿服务微信
返回顶部
快速回复 返回顶部 返回列表