小灰ui的杂货铺

我的博客美化日记

[collapse status="false" title="UserAgent插件"]

修改Handsome主题,component目录下的comments.php代码文件,大概第60~80行左右

<span class="comment-author vcard">
    <b class="fn"><?php echo $author; ?></b><?php echo $Identity; ?>
</span>

改为

<span class="comment-author vcard">
    <b class="fn"><?php echo $author; ?></b><?php echo $Identity; ?><?php UserAgent_Plugin::get_useragent($comments->agent,$comments->ip); ?>
</span>

[/collapse]

[collapse status="false" title="在文章顶部添加百度是否收录"]

handsome/functions.php最底部添加代码

if(checkBaidu($url)==1){
    echo "百度已收录";
}
else{
    echo "<a style=\"color:red;\" rel=\"external nofollow\" title=\"点击提交收录!\" target=\"_blank\" href=\"http://zhanzhang.baidu.com/sitesubmit/index?sitename=$url\">百度未收录</a>";}
}
function checkBaidu($url) {
    $url = 'http://www.baidu.com/s?wd=' . urlencode($url);
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $rs = curl_exec($curl);
    curl_close($curl);
    if (!strpos($rs, '没有找到')) { //没有找到说明已被百度收录
        return 1;
    } else {
        return -1;
    }
}

然后在handsome/post.php在63行左右添加代码

<!--百度收录-->
<li><i class="glyphicon glyphicon-globe"></i>&nbsp<?php echo baidu_record() ?></li>

[/collapse]

[collapse status="false" title="在博客顶部添加心知天气"]

首先去心知天气官网注册账号并申请API
之后在/usr/themes/handsome/component/headnav.php文件中的动态日历中<?php endif;?>下方添加以下代码
注意将API信息改成自己的

<div id="tp-weather-widget" class="navbar-form navbar-form-sm navbar-left shift"></div>
<script>(function(T,h,i,n,k,P,a,g,e){g=function(){P=h.createElement(i);a=h.getElementsByTagName(i)[0];P.src=k;P.charset="utf-8";P.async=1;a.parentNode.insertBefore(P,a)};T["ThinkPageWeatherWidgetObject"]=n;T[n]||(T[n]=function(){(T[n].q=T[n].q||[]).push(arguments)});T[n].l=+new Date();if(T.attachEvent){T.attachEvent("onload",g)}else{T.addEventListener("load",g,false)}}(window,document,"script","tpwidget","//widget.seniverse.com/widget/chameleon.js"))</script>
<script>tpwidget("init", {
    "flavor": "slim",
    "location": "WX4FBXXFKE4F",
    "geolocation": "enabled",
    "language": "auto",
    "unit": "c",
    "theme": "chameleon",
    "container": "tp-weather-widget",
    "bubble": "enabled",
    "alarmType": "badge",
    "color": "#C6C6C6",
    "uid": "公钥",
    "hash": "密钥"
});
tpwidget("show");</script>
<!-- 知心结束-->

[/collapse]

[collapse status="false" title="小图模式下的栏目斜切效果"]
首先我们找到网站根目录/usr/themes/handsome/libs/Content.php

<div class="panel-small single-post box-shadow-wrap-normal">
    <div class="index-post-img-small post-feature index-img-small">
        <a href="{$parameterArray['linkUrl']}">
            <div class="item-thumb-small lazy" {$backgroundImageHtml}>
            </div>
        </a>
    </div>

替换成为

<div class="index-post-img-small post-feature index-img-small tt-left-box">
    <a href="{$parameterArray['linkUrl']}">
        <div class="item-thumb-small lazy tt-left-img" {$backgroundImageHtml}></div>
    </a>
</div>

并在自定义CSS里面添加以下代码

.tt-small-blur{position:relative;z-index:1;display:flex;overflow:hidden;background-color:#333;color:#fff;}
.tt-small-blur .tt-left-box{z-index:1;-webkit-clip-path:polygon(0 0,94% 0,100% 100%,0 100%);clip-path:polygon(0 0,94% 0,100% 100%,0 100%);}
.tt-small-blur .tt-left-img{width:100%;height:100%;-o-object-fit:cover;object-fit:cover;}
.tt-small-blur .tt-blur-img{position:absolute;top:0;right:0;bottom:0;left:0;z-index:0;width:100%;height:100%;background-position:center;background-size:cover;transform:scale(1.4);-o-object-fit:cover;object-fit:cover;-webkit-filter:blur(1.275rem) brightness(.83);filter:blur(1.275rem) brightness(.83);}
.tt-small-blur .post-meta{z-index:1;display:flex;color:inherit;flex-direction:column;justify-content:space-between;}
.tt-small-blur .text-title{color:inherit;}
.tt-small-blur .post-meta h2,.tt-small-blur .post-meta p{text-shadow:.1875rem .1875rem .3125rem #333;letter-spacing:.09rem;}
.tt-small-blur .text-muted{color:inherit;}
.tt-small-blur .post-meta {padding: 30px 30px 15px 30px;}
@media (max-width:500px){.tt-small-blur .index-post-title{display:-webkit-box;display:-moz-box;overflow:hidden;margin-bottom:2px;height:48px;text-overflow:ellipsis;white-space:normal;word-wrap:break-word;line-height:1.4;-webkit-line-clamp:2;-webkit-box-orient:vertical;-moz-line-clamp:2;-moz-box-orient:vertical;word-break:break-all;}}
@media (max-width:500px){.tt-small-blur .summary{display:none;}}
@media (max-width:380px){.tt-small-blur .post-meta{padding:10px 15px;}}
@media (min-width:768px) and (max-width: 1199px){.tt-small-blur .summary {height: 55px;}.tt-small-blur .line-lg {margin-top: 1px;margin-bottom: 1px;}}

[/collapse]

[collapse status="false" title="小米社区图片转内链"]
插件找到MultiUpload.php
复制

if (!defined('__TYPECHO_ROOT_DIR__')) exit;
/**
 * 上传动作
 *
 * @category typecho
 * @package Widget
 * @copyright Copyright (c) 2008 Typecho team (http://www.typecho.org)
 * @license GNU General Public License 2.0
 * @version $Id$
 */

/**
 * 上传组件
 *
 * @author qining
 * @category typecho
 * @package Widget
 */
class Handsome_Upload extends Widget_Abstract_Contents implements Widget_Interface_Do
{
    //上传文件目录
    const UPLOAD_DIR = '/usr/uploads';

    /**
     * 创建上传路径
     *
     * @access private
     * @param string $path 路径
     * @return boolean
     */
    private static function makeUploadDir($path)
    {
        $path = preg_replace("/\\\+/", '/', $path);
        $current = rtrim($path, '/');
        $last = $current;

        while (!is_dir($current) && false !== strpos($path, '/')) {
            $last = $current;
            $current = dirname($current);
        }

        if ($last == $current) {
            return true;
        }

        if (!@mkdir($last)) {
            return false;
        }

        $stat = @stat($last);
        $perms = $stat['mode'] & 0007777;
        @chmod($last, $perms);

        return self::makeUploadDir($path);
    }

    /**
     * 获取安全的文件名
     *
     * @param string $name
     * @static
     * @access private
     * @return string
     */
    private static function getSafeName(&$name)
    {
        $name = str_replace(array('"', '<', '>'), '', $name);
        $name = str_replace('\\', '/', $name);
        $name = false === strpos($name, '/') ? ('a' . $name) : str_replace('/', '/a', $name);
        $info = pathinfo($name);
        $name = substr($info['basename'], 1);

        return isset($info['extension']) ? strtolower($info['extension']) : '';
    }

    /**
     * 上传文件处理函数,如果需要实现自己的文件哈希或者特殊的文件系统,请在options表里把uploadHandle改成自己的函数
     *
     * @access public
     * @param array $file 上传的文件
     * @return mixed
     */
    public static function uploadHandle($file)
    {
        if (empty($file['name'])) {
            return false;
        } else {
//            print_r($file);
        }

        $result = Typecho_Plugin::factory('Widget_Upload')->trigger($hasUploaded)->uploadHandle($file);
        if ($hasUploaded) {
            return $result;
        }

        $ext = self::getSafeName($file['name']);

//        var_dump($file['name']);
//        print_r($ext);

        if (!self::checkFileType($ext) || Typecho_Common::isAppEngine()) {
            return false;
        }

        $date = new Typecho_Date();
        $path = Typecho_Common::url(defined('__TYPECHO_UPLOAD_DIR__') ? __TYPECHO_UPLOAD_DIR__ : self::UPLOAD_DIR,
                defined('__TYPECHO_UPLOAD_ROOT_DIR__') ? __TYPECHO_UPLOAD_ROOT_DIR__ : __TYPECHO_ROOT_DIR__)
            . '/' . $date->year . '/' . $date->month;

        //创建上传目录
        if (!is_dir($path)) {
            if (!self::makeUploadDir($path)) {
                return false;
            }
        }

        //获取文件名
        $fileName = sprintf('%u', crc32(uniqid())) . '.' . $ext;
        $path = $path . '/' . $fileName;

        if (isset($file['tmp_name'])) {

            //移动上传文件
            if (!@move_uploaded_file($file['tmp_name'], $path)) {
                return false;
            }
        } else if (isset($file['bytes'])) {

            //直接写入文件
            if (!file_put_contents($path, $file['bytes'])) {
                return false;
            }
        } else {
            return false;
        }

        if (!isset($file['size'])) {
            $file['size'] = filesize($path);
        }

        //返回相对存储路径
        return array(
            'name' => $file['name'],
            'path' => (defined('__TYPECHO_UPLOAD_DIR__') ? __TYPECHO_UPLOAD_DIR__ : self::UPLOAD_DIR)
                . '/' . $date->year . '/' . $date->month . '/' . $fileName,
            'size' => $file['size'],
            'type' => $ext,
            'mime' => Typecho_Common::mimeContentType($path)
        );
    }

    /**
     * 修改文件处理函数,如果需要实现自己的文件哈希或者特殊的文件系统,请在options表里把modifyHandle改成自己的函数
     *
     * @access public
     * @param array $content 老文件
     * @param array $file 新上传的文件
     * @return mixed
     */
    public static function modifyHandle($content, $file)
    {
        if (empty($file['name'])) {
            return false;
        }

        $result = Typecho_Plugin::factory('Widget_Upload')->trigger($hasModified)->modifyHandle($content, $file);
        if ($hasModified) {
            return $result;
        }

        $ext = self::getSafeName($file['name']);

        if ($content['attachment']->type != $ext || Typecho_Common::isAppEngine()) {
            return false;
        }

        $path = Typecho_Common::url($content['attachment']->path,
            defined('__TYPECHO_UPLOAD_ROOT_DIR__') ? __TYPECHO_UPLOAD_ROOT_DIR__ : __TYPECHO_ROOT_DIR__);
        $dir = dirname($path);

        //创建上传目录
        if (!is_dir($dir)) {
            if (!self::makeUploadDir($dir)) {
                return false;
            }
        }

        if (isset($file['tmp_name'])) {

            @unlink($path);

            //移动上传文件
            if (!@move_uploaded_file($file['tmp_name'], $path)) {
                return false;
            }
        } else if (isset($file['bytes'])) {

            @unlink($path);

            //直接写入文件
            if (!file_put_contents($path, $file['bytes'])) {
                return false;
            }
        } else {
            return false;
        }

        if (!isset($file['size'])) {
            $file['size'] = filesize($path);
        }

        //返回相对存储路径
        return array(
            'name' => $content['attachment']->name,
            'path' => $content['attachment']->path,
            'size' => $file['size'],
            'type' => $content['attachment']->type,
            'mime' => $content['attachment']->mime
        );
    }

    /**
     * 删除文件
     *
     * @access public
     * @param array $content 文件相关信息
     * @return string
     */
    public static function deleteHandle(array $content)
    {
        $result = Typecho_Plugin::factory('Widget_Upload')->trigger($hasDeleted)->deleteHandle($content);
        if ($hasDeleted) {
            return $result;
        }

        return !Typecho_Common::isAppEngine()
            && @unlink(__TYPECHO_ROOT_DIR__ . '/' . $content['attachment']->path);
    }

    /**
     * 获取实际文件绝对访问路径
     *
     * @access public
     * @param array $content 文件相关信息
     * @return string
     */
    public static function attachmentHandle(array $content)
    {
        $result = Typecho_Plugin::factory('Widget_Upload')->trigger($hasPlugged)->attachmentHandle($content);
        if ($hasPlugged) {
            return $result;
        }

        $options = Typecho_Widget::widget('Widget_Options');
        return Typecho_Common::url($content['attachment']->path,
            defined('__TYPECHO_UPLOAD_URL__') ? __TYPECHO_UPLOAD_URL__ : $options->siteUrl);
    }

    /**
     * 获取实际文件数据
     *
     * @access public
     * @param array $content
     * @return string
     */
    public static function attachmentDataHandle(array $content)
    {
        $result = Typecho_Plugin::factory('Widget_Upload')->trigger($hasPlugged)->attachmentDataHandle($content);
        if ($hasPlugged) {
            return $result;
        }

        return file_get_contents(Typecho_Common::url($content['attachment']->path,
            defined('__TYPECHO_UPLOAD_ROOT_DIR__') ? __TYPECHO_UPLOAD_ROOT_DIR__ : __TYPECHO_ROOT_DIR__));
    }

    /**
     * 检查文件名
     *
     * @access private
     * @param string $ext 扩展名
     * @return boolean
     */
    public static function checkFileType($ext)
    {
        $options = Typecho_Widget::widget('Widget_Options');
        return in_array($ext, $options->allowedAttachmentTypes);
    }


    public static function getDataFromWebUrl($url)
    {
        $file_contents = "";
        if (function_exists('file_get_contents')) {
            $file_contents = @file_get_contents($url);
        }
        if ($file_contents == "") {
            $ch = curl_init();
            $timeout = 30;
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
            $file_contents = curl_exec($ch);
            curl_close($ch);
        }
        return $file_contents;
    }


    /**
     * 执行升级程序
     *
     * @access public
     * @return void
     */
    public function upload()
    {
        $uploadType = "file";
        $original = "";
        if (!empty($_FILES)) {
            $file = array_pop($_FILES);
//            print_r($file);
            if (is_array($file["error"])) {//处理传过来的是一个file数组
                $file = array(
                    "name" => $file["name"][0],
                    "type" => $file["type"][0],
                    "error" => $file["error"][0],
                    "tmp_name" => $file["tmp_name"][0],
                    "size" => $file["size"][0],
                );
            }
        } else {
            $post = json_decode(file_get_contents("php://input"), true);
//            print_r($post);
            if (@!empty($post["url"])) {
                $imageUrl = $post["url"];
                $original = $imageUrl;
                if (substr($imageUrl, 0, 4) != "http") {//图片地址没有http前缀
                    if (substr($imageUrl,0,2) =="//"){//图片地址是相对路径
                        $imageUrl = "http:".$imageUrl;
                    }else{
                        $imageUrl = "";
                    }
                } else {//正确的url
//                    $imageUrl = "";
                }
//                print_r("imageUrl".$imageUrl);
                if ($imageUrl!=""){
                    $ret = parse_url($imageUrl);
//                    $url = @$ret["scheme"] . "://" . @$ret["host"] . @$ret["path"];
                    $fileName = mb_split("/", @$ret["path"]);
                    $fileName = $fileName[count($fileName) - 1];
                    //todo 智能识别后缀,目前是根据链接地址来的
                    if (strpos($ret["query"],"webp")!==false && strpos($fileName,".")===false){
                        $fileName.=".webp";
                    }
                    $file = array(
                        "name" => $fileName,
                        "error" => 0,
                        "bytes" => self::getDataFromWebUrl($imageUrl),
                    );
                    $uploadType = "web";
//                    print_r($file);
                }

            } else {
                //不需要处理
                print_r("图片外链格式不正确");
            }
        }


        if (!empty($file)) {
            if (0 == $file['error'] && ((isset($file['tmp_name']) && is_uploaded_file($file['tmp_name'])) || isset
                    ($file["bytes"]))) {
                // xhr的send无法支持utf8
                if ($this->request->isAjax()) {
                    $file['name'] = urldecode($file['name']);
                }
                //todo
                $result = self::uploadHandle($file);

                if (false !== $result) {
                    $this->pluginHandle()->beforeUpload($result);

                    $struct = array(
                        'title' => $result['name'],
                        'slug' => $result['name'],
                        'type' => 'attachment',
                        'status' => 'publish',
                        'text' => serialize($result),
                        'allowComment' => 1,
                        'allowPing' => 0,
                        'allowFeed' => 1
                    );

                    if (isset($this->request->cid)) {
                        $cid = $this->request->filter('int')->cid;

                        if ($this->isWriteable($this->db->sql()->where('cid = ?', $cid))) {
                            $struct['parent'] = $cid;
                        }
                    }

                    $insertId = $this->insert($struct);

                    $this->db->fetchRow($this->select()->where('table.contents.cid = ?', $insertId)
                        ->where('table.contents.type = ?', 'attachment'), array($this, 'push'));

                    /** 增加插件接口 */
                    $this->pluginHandle()->upload($this);


                    if ($uploadType == "file") {
                        $this->response->throwJson(array($this->attachment->url, array(
                            'cid' => $insertId,
                            'title' => $this->attachment->name,
                            'type' => $this->attachment->type,
                            'size' => $this->attachment->size,
                            'bytes' => number_format(ceil($this->attachment->size / 1024)) . ' Kb',
                            'isImage' => $this->attachment->isImage,
                            'url' => $this->attachment->url,
                            'permalink' => $this->permalink
                        )));
                    } else {
                        $this->response->throwJson(array(
                                "msg" => "",
                                "code" => 0,
                                "data" => array(
                                    'cid' => $insertId,
                                    "title" => $this->attachment->name,
                                    'type' => $this->attachment->type,
                                    'size' => $this->attachment->size,
                                    'bytes' => number_format(ceil($this->attachment->size / 1024)) . ' Kb',
                                    'isImage' => $this->attachment->isImage,
                                    "url" => $this->attachment->url,
                                    'permalink' => $this->permalink,
                                    "originalURL"=>$original,

                                )
                            )
                        );
                    }
                }else{
                    //todo 显示错误原因
                    $this->response->throwJson(false);
                }
            }
        }else{
            //todo 文件是空的
            $this->response->throwJson(false);
        }

    }

    /**
     * 执行升级程序
     *
     * @access public
     * @return void
     */
    public function modify()
    {
        if (!empty($_FILES)) {
            $file = array_pop($_FILES);
            if (0 == $file['error'] && is_uploaded_file($file['tmp_name'])) {
                $this->db->fetchRow($this->select()->where('table.contents.cid = ?', $this->request->filter('int')->cid)
                    ->where('table.contents.type = ?', 'attachment'), array($this, 'push'));

                if (!$this->have()) {
                    $this->response->setStatus(404);
                    exit;
                }

                if (!$this->allow('edit')) {
                    $this->response->setStatus(403);
                    exit;
                }

                // xhr的send无法支持utf8
                if ($this->request->isAjax()) {
                    $file['name'] = urldecode($file['name']);
                }

                $result = self::modifyHandle($this->row, $file);

                if (false !== $result) {
                    $this->pluginHandle()->beforeModify($result);

                    $this->update(array(
                        'text' => serialize($result)
                    ), $this->db->sql()->where('cid = ?', $this->cid));

                    $this->db->fetchRow($this->select()->where('table.contents.cid = ?', $this->cid)
                        ->where('table.contents.type = ?', 'attachment'), array($this, 'push'));

                    /** 增加插件接口 */
                    $this->pluginHandle()->modify($this);

                    $this->response->throwJson(array($this->attachment->url, array(
                        'cid' => $this->cid,
                        'title' => $this->attachment->name,
                        'type' => $this->attachment->type,
                        'size' => $this->attachment->size,
                        'bytes' => number_format(ceil($this->attachment->size / 1024)) . ' Kb',
                        'isImage' => $this->attachment->isImage,
                        'url' => $this->attachment->url,
                        'permalink' => $this->permalink
                    )));
                }
            }
        }

        $this->response->throwJson(false);
    }

    /**
     * 初始化函数
     *
     * @access public
     * @return void
     */
    public function action()
    {
        if ($this->user->pass('contributor', true) && $this->request->isPost()) {
            if ($this->request->is('do=modify&cid')) {
                $this->security->protect();
                $this->modify();
            } else if ($this->request->is('do=uploadfile')) {
                $this->security->protect();
                $this->upload();
            }else{
                return ;
            }
        }
    }
}

[/collapse]

[collapse status="false" title="网站底部添加ICP备案号"]
打开这个文件

/www/wwwroot/**你的域名/usr/themes/handsome/component/footer.php

然后搜索找到这一段

<div class="wrapper bg-light">
      <span class="pull-right hidden-xs text-ellipsis">
      <?php $this->options->BottomInfo();
      // 可以去除主题版权信息,最好保留版权信息或者添加主题信息到友链,谢谢你的理解
      ?>
      
       Powered by <a target="_blank" href="http://www.typecho.org">Typecho</a>&nbsp;| Theme by handsome</a>
       <!--    <网站底部左侧信息">-->
       <!--    <网站底部左侧信息">-->
      </span>
      
        <span class="text-ellipsis">&copy;&nbsp;<?php echo date("Y"); ?> Copyright&nbsp;<?php
            $this->options->BottomleftInfo(); ?></span>
            
    </div>

修改就可以
参考代码
ICP部分

<span style="color: #606266; font-family: &quot;Microsoft YaHei&quot;; font-size: 14px; text-align: center; text-decoration-thickness: initial; display: inline !important;"><img src="https://zengmenghui.cn/usr/uploads/2022/01/1978574531.png" style="vertical-align:inherit;" alt="image.png" data-ratio="1.1428571428571428" data-w="14"/>赣ICP备<a href="https://beian.miit.gov.cn/#/Integrated/recordQuery" target="_blank" style="color: rgb(96, 98, 102);" >18006020号</a></span>

[/collapse]

[collapse status="false" title="添加返回顶部代码"]
usr /themes /handsome /index.php

这个位置添加

//返回顶部
<a href="javascript:void(0);" class="back-to-top" target="_self"></a>
//返回顶部按钮

<script>
(function () {
// 移动端不显示
//   if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
//     return
//   }

  var isShow = false, lock = false;
  var $btn = $('.back-to-top');

  $(document).scroll(function () {
    if (lock) return

    if ($(this).scrollTop() >= 1) {
      if (!isShow) $btn.addClass('load')
      isShow = true
    } else {
      if (isShow) {
        $btn.removeClass('load')
        isShow = false
      }
    }
  })

  $btn.click(function () {
    lock = true
    $btn.addClass('ani-leave')

    $("html, body").animate({ scrollTop: 0 }, 800);

    setTimeout(function () {
      $btn.removeClass('ani-leave').addClass('leaved')
    }, 390)

    setTimeout(function () {
      $btn.addClass('ending')
    }, 120)

    setTimeout(function () {
      $btn.removeClass('load')
    }, 1500);

    setTimeout(function () {
      lock = false
      isShow = false
      $btn.removeClass('leaved ending')
    }, 2000);
  })
})();
</script>

然后在css添加

.back-to-top {
position: fixed;
z-index: 2;
right: -108px;
bottom: 0;
width: 108px;
height: 150px;
background: url("https://cdn.muyu.love/Blog/Handsome/img/back-to-top.png?v=1") no-repeat 0 0;
background-size: 108px 450px;
opacity: 0.6;
transition: opacity 0.3s, right 0.8s;
}
.back-to-top:hover {
background-position: 0 -150px;
opacity: 1;
}
.back-to-top.load {
right: 0;
}
.back-to-top.ani-leave {
background-position: 0 -150px;
animation: ani-leave 390ms ease-in-out;
animation-fill-mode: forwards;
}
.back-to-top.leaved {
pointer-events: none;
background: none;
transition: none;
}
.back-to-top.ending {
pointer-events: none;
}
.back-to-top.ending::after {
opacity: 1;
}
.back-to-top::after {
content: '';
position: fixed;
z-index: 2;
right: 0;
bottom: 0;
width: 108px;
height: 150px;
background: url("https://cdn.muyu.love/Blog/Handsome/img/back-to-top.png?v=1") no-repeat 0 0;
background-size: 108px 450px;
background-position: 0 -300px;
transition: opacity 0.3s;
opacity: 0;
pointer-events: none;
}

[/collapse]

[collapse status="false" title="给侧边栏添加一个倒计时"]
这个位置修改侧边栏信息usr/themes/handsome/component/sidebar.php

[/collapse]

[collapse status="false" title="在博客信息添加全站字数、在线人数、访客总数和网站加载耗时"]

首先将以下代码加到themes/handsome/libs/Content.php中放在class Content{}之前。

//require("component/Recent.php");
    /**
     * 全站字数
     */
    function allOfCharacters() {
        $chars = 0;
        $db = Typecho_Db::get();
        $select = $db ->select('text')->from('table.contents');
        $rows = $db->fetchAll($select);
        foreach ($rows as $row) { $chars += mb_strlen(trim($row['text']), 'UTF-8'); }
        $unit = '';
        if($chars >= 10000)     { $chars /= 10000; $unit = '万'; } 
        else if($chars >= 1000) { $chars /= 1000;  $unit = '千'; }
        $out = sprintf('%.2lf %s',$chars, $unit);
        return $out;
    } 
/**
     * 在线人数
     */
    function online_users() {
        $filename='online.txt'; //数据文件
        $cookiename='Nanlon_OnLineCount'; //Cookie名称
        $onlinetime=30; //在线有效时间
        $online=file($filename); 
        $nowtime=$_SERVER['REQUEST_TIME']; 
        $nowonline=array(); 
        foreach($online as $line){ 
            $row=explode('|',$line); 
            $sesstime=trim($row[1]); 
            if(($nowtime - $sesstime)<=$onlinetime){
                $nowonline[$row[0]]=$sesstime;
            } 
        } 
        if(isset($_COOKIE[$cookiename])){
            $uid=$_COOKIE[$cookiename]; 
        }else{
            $vid=0;
            do{
                $vid++; 
                $uid='U'.$vid; 
            }while(array_key_exists($uid,$nowonline)); 
            setcookie($cookiename,$uid); 
        } 
        $nowonline[$uid]=$nowtime;
        $total_online=count($nowonline); 
        if($fp=@fopen($filename,'w')){ 
            if(flock($fp,LOCK_EX)){ 
                rewind($fp); 
                foreach($nowonline as $fuid=>$ftime){ 
                    $fline=$fuid.'|'.$ftime."\n"; 
                    @fputs($fp,$fline); 
                } 
                flock($fp,LOCK_UN); 
                fclose($fp); 
            } 
        } 
        echo "$total_online"; 
    }      
    
    /**
     * 访客总数
     */
     function theAllViews(){
             $db = Typecho_Db::get();
             $row = $db->fetchAll('SELECT SUM(VIEWS) FROM `typecho_contents`');
                 echo number_format($row[0]['SUM(VIEWS)']);
     }

    /**
     * 加载耗时
     */
    function timer_start() {
        global $timestart;
        $mtime = explode( ' ', microtime()  );
        $timestart = $mtime[1] + $mtime[0];
        return true; 
    }
    timer_start();
    function timer_stop( $display = 0, $precision = 3  ) {
        global $timestart, $timeend;
        $mtime = explode( ' ', microtime()  );
        $timeend = $mtime[1] + $mtime[0];
        $timetotal = number_format( $timeend - $timestart, $precision  );
        $r = $timetotal < 1 ? $timetotal * 1000 . " ms" : $timetotal . " s";
        if ( $display  ) {
            echo $r;
        }
        return $r;
    }

sidebar.php添加代码

<li class="list-group-item text-second"><span class="blog-info-icons"><i data-feather="edit-3"></i></span><span class="badge pull-right"><?php echo allOfCharacters(); ?></span><?php _me("全站字数") ?></li>
<li class="list-group-item"> <i class="glyphicon glyphicon-user text-muted text-muted"></i> <span class="badge pull-right"><?php echo online_users() ?></span><?php _me("在线人数") ?></li>
<li class="list-group-item text-second"><span class="blog-info-icons"> <i data-feather="user"></i></span><span class="badge pull-right"><?php echo theAllViews();?></span><?php _me("访客总数") ?></li>
<li class="list-group-item text-second"><span class="blog-info-icons"> <i data-feather="clock"></i></span> <span class="badge pull-right"><?php echo timer_stop();?></span><?php _me("加载耗时") ?></li>

[/collapse]

[collapse status="false" title="自定义文章头图"]
到你服务器文件路径usr/themes/handsome/assets/img/sj文件夹里面的图片都可以替换
下面的sj2图片是自定义右侧图标

[/collapse]

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »