美文网首页
DokuWiki安装+集成markdown编辑器editor.m

DokuWiki安装+集成markdown编辑器editor.m

作者: 大大大大槐树 | 来源:发表于2019-05-17 17:28 被阅读0次

    安装

    1. 官网下载安装包https://www.dokuwiki.org/
    2. 安装php和nginx yum install -y php70w php70w-gd php70w-xml php70w-fpm nginx
    3. 开机自启动 systemctl enable nginx php-fpm
    4. 配置nginx
        server {
            listen       80;
            server_name  localhost;
            # Maximum file upload size is 4MB - change accordingly if needed
            client_max_body_size 4M;
            client_body_buffer_size 128k;
    
            root /dokuwiki;
            index doku.php;
    
            #Remember to comment the below out when you're installing, and uncomment it when done.
            location ~ /(conf/|bin/|inc/|install.php) { deny all; }
    
            #Support for X-Accel-Redirect
            location ~ ^/data/ { internal ; }
    
            location ~ ^/lib.*\.(js|css|gif|png|ico|jpg|jpeg)$ {
                 expires 365d;
            }
    
            location / { try_files $uri $uri/ @dokuwiki; }
    
            location @dokuwiki {
                # rewrites "doku.php/" out of the URLs if you set the userwrite setting to .htaccess in dokuwiki config page
                rewrite ^/_media/(.*) /lib/exe/fetch.php?media=$1 last;
                rewrite ^/_detail/(.*) /lib/exe/detail.php?media=$1 last;
                rewrite ^/_export/([^/]+)/(.*) /doku.php?do=export_$1&id=$2 last;
                rewrite ^/(.*) /doku.php?id=$1&$args last;
            }
    
            location ~ \.php$ {
                try_files $uri $uri/ /doku.php;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param REDIRECT_STATUS 200;
                fastcgi_pass 127.0.0.1:9000;
            }
        }
    
    1. 启动nginx和php-fpm systemctl start php-fpm nginx
    2. 在网站一栏输入:http://你的ip地址/install.php 在右上角选好语言,简体中文zh,按照提示安装即可。如果打开页面保存,请修改conf、data、lib目前的权限。

    安装插件

    1. 新增页面Add New Page插件

    2. Markdown插件Markdown Page Plugin

    3. 侧边栏

      • 安装Indexmenu Plugin插件
      • 新建data\pages\sidebar.txt,内容如下:
          ===== 导航目录 =====
          {{indexmenu>..|navbar}}
          ===== 添加新页面 =====
          {{NEWPAGE}}
      

    中文文件名乱码

    修改dokuwiki/conf/local.php在最后一行加上:

    $conf['fnencode']='utf-8';
    

    此处是centos系统(系统默认字符编码utf-8)下修改乱码,windows系统请参考文章末尾的原文地址。

    集成editor.md

    1. 下载editor.md
      https://github.com/pandao/editor.md/archive/v1.5.0.tar.gz
    2. 解压到dokuwiki\lib\editor.md\
    3. 替换/inc/form.php里的函数form_wikitext($attrs),修改return结果
        function form_wikitext($attrs) {
            // mandatory attributes
            unset($attrs['name']);
            unset($attrs['id']);
            $text = str_replace("<markdown>\n",'',$attrs['_text']);
            $text = str_replace("\n</markdown>",'',$text);
            return '<div id="editormd" contenteditable="true"><textarea name="wikitext">'.DOKU_LF.formText($text).'</textarea></div>';
        }
    

    代码中id="editormd"是后面editor.md实例需要的id

    1. 在/inc/parser/xhtml.php里更改cdata函数
        function cdata($text) {
            //$this->doc .= $this->_xmlEntities($text);
            return $this->doc.=$text;
        }
    

    替换原因是:因为以前是纯字符编辑器,会将一些特殊符号进行过滤,比如:<>等等.而替换之后的xheditor本身已经做了一次过滤了,再次过滤就会导致字符<变成&lt,因此去掉这段之后,就只过滤一次

    1. inc/Action/Save.php的
        saveWikiText($ID,con($PRE,$TEXT,$SUF,true),$SUM,$INPUT->bool('minor')); //use pretty mode for con
        替换成
        saveWikiText($ID,con($PRE,"<markdown>\n".$TEXT."\n</markdown>",$SUF,true),$SUM,$INPUT->bool('minor')); //use pretty mode for con
    
    1. lib/tpl/dokuwiki/main.php添加editor.md包
    • head节中添加
    <link rel="stylesheet" href="<?php echo DOKU_BASE;?>lib/editor.md/css/editormd.min.css" />
    
    • body节中添加
        <script src="<?php echo DOKU_BASE;?>lib/editor.md/editormd.js"></script>
        <script type="text/javascript">
        $ = jQuery
            var testEditor;
            $(function(md) {
            if (document.getElementById("editormd")) {
                testEditor = editormd("editormd", {
                    width: "100%",
                    height: 740,
                    path: '<?php echo DOKU_BASE;?>lib/editor.md/lib/',
                    syncScrolling : "single",
                    imageUpload: true,
                    imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
                    imageUploadURL: "<?php echo DOKU_BASE;?>uploadimg.php",
                    onload: function() {}
                });
            }
            });
    
            window.onload = function() {
                //document.getElementById("editormd").addEventListener('paste', function (event) {
                $("#editormd").on('paste', function(event) {
                    //console.log(event);
                    var items = (event.clipboardData || event.originalEvent.clipboardData).items;
                    for (var index in items) {
                        var item = items[index];
                        //console.log(item);
                        if (item.kind === 'file') {
                            var blob = item.getAsFile();                        
                            var reader = new FileReader();
                            reader.onload = function(event) {                            
                                var base64 = event.target.result;
                                console.log(base64);
                                //ajax上传图片
                                $.post("<?php echo DOKU_BASE;?>uploadimg.php", {
                                    screenshots: base64
                                }, function(rets) {
                                    ret = JSON.parse(rets);
                                    //layer.msg(ret.msg);
                                    console.log(ret);
                                    if (ret.success === 1) {
                                        //新一行的图片显示
                                        testEditor.insertValue("\n![](" + ret.url + ")");
                                    } else {
                                        alert("截图上传失败:" + ret.message);
                                    }
                                });
                            };
                            reader.readAsDataURL(blob);
                        }
                    }
                });
            }
        </script>
    
    
    1. 图片上传支持
      将如下代码保存到uploadimg.php文件,放到dokuwiki根目录下
    <?php
    if(!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__).'/');
    require_once(DOKU_INC.'inc/init.php');
    
    $INFO = pageinfo();
    $hostpath=getBaseURL(false);
    $attachDir='/data/media/editor/';//上传文件保存路径,结尾不要带/
    $maxAttachSize = 2*1024*1024;  //最大上传大小,默认是2M
    
    function upEditorImg(){
        global $hostpath, $attachDir, $maxAttachSize;
        //获取文件的大小
        $file_size=$_FILES['editormd-image-file']['size'];
        //echo "$file_size $maxAttachSize";
        if($file_size > $maxAttachSize) {
            echo '{"success":0,"message":"不能上传大于2M的文件"}';
            return false;
        }
    
        //获取文件类型
        $file_type=$_FILES['editormd-image-file']['type'];
        if($file_type!="image/jpeg" && $file_type!='image/pjpeg' && $file_type!="image/png") {
            echo '{"success":0,"message":"图片格式异常"}';
            return false;
        }
    
        //判断是否上传成功(是否使用post方式上传)
        if(is_uploaded_file($_FILES['editormd-image-file']['tmp_name'])) {
            //把文件转存到你希望的目录(不要使用copy函数)
            $uploaded_file=$_FILES['editormd-image-file']['tmp_name'];
    
            //我们给每个用户动态的创建一个文件夹
            $save_path=$_SERVER['DOCUMENT_ROOT'].$hostpath.$attachDir;
            //判断该用户文件夹是否已经有这个文件夹
            if(!file_exists($save_path)) {
                mkdir($save_path);
            }
    
            //$move_to_file=$save_path."/".$_FILES['editormd-image-file']['name'];
            $file_true_name=$_FILES['editormd-image-file']['name'];
            $move_file_name=time().rand(1,1000).substr($file_true_name,strrpos($file_true_name,"."));
            $move_to_file=$save_path.$move_file_name;
            //echo "$uploaded_file   $move_to_file";
            if(move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_to_file))) {
                //echo $_FILES['editormd-image-file']['name']."上传成功";
                //echo '{"success":1,"message":"上传成功", "url":"'.$hostpath.$attachDir.$move_file_name.'"}';
                $result=array(
                  'success'=> 1,
                  'message'=>'上传成功',
                  'url'=>'editor:'.$move_file_name
                );
                echo json_encode($result);
            } else {
                //echo "上传失败";
                echo '{"success":0,"message":"服务器保存文件失败"}';
            }
        } else {
            //echo "上传失败";
            echo '{"success":0,"message":"上传失败"}';
            return false;
        }
    }
    
    //$_POST= [screenshots] => data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAI0AAACcCAYAAABC1CibAAAL6UlEQVR4Ae2dbUiU6RrH...
    function upEditorScreenshots(){
        global $hostpath, $attachDir, $maxAttachSize;
    
        $content = $_POST['screenshots'];
    
        if (preg_match('/^data:image\/(\w+);base64,(\S+)/', $content, $result)) {
            $file_type = $result[1];
            $base64data = $result[2];
    
            //echo "$file_type $base64data";
            $save_path = $_SERVER['DOCUMENT_ROOT'].$hostpath.$attachDir;
            if (!is_dir($save_path)) {
                mkdir($save_path, 0777);
            }
    
            $filedata = base64_decode($base64data);
            $filename = time().rand(1,1000).".".$file_type;
            if (!file_put_contents($save_path . $filename, $filedata)) {
                echo '{"success":0,"message":"服务器保存文件失败"}';
                return false;
            }
            unset($filedata);
    
            echo '{"success":1,"message":"上传成功", "url":"editor:'.$move_file_name.$filename.'"}';
            return true;
        } else {
            echo '{"success":0,"message":"图片格式异常"}';
            return false;
        }
    }
    
    //print_r($_POST);
    //print_r($_FILES);
    
    if(isset($_FILES['editormd-image-file'])){
        global $INFO;
        if($INFO['writable'] && !$INFO['locked']) {
            upEditorImg();
        } else {
        echo '{"success":0,"message":"没有权限"}';
        }
        exit();
    }
    
    if(isset($_POST['screenshots'])){
        global $INFO;
        if($INFO['writable'] && !$INFO['locked']) {
            upEditorScreenshots();
        } else  {
        echo '{"success":0,"message":",没有权限"}';
        }
        exit();
    }
    ?>
    

    代码中添加了权限校验和兼容dokuwiki获取图片url

    1. 修改图片加载地址
      修改lib/editor.md/lib/marked.min.js文件中img标签生成的方法,在
        var out='<img src="'+href+'" alt="'+text+'"';
    

    代码前添加

        if(href.indexOf(':')>0&&href.indexOf("/")<0){href='/lib/exe/fetch.php?cache=&media='+href;}
    

    总结

    • 在原来参考文章基础上添加了未登录用户不能通过editor上传图片
    • 针对Markdown Page Plugin插件,修改了图片显示问题(dokuwiki的图片资源是统一通过lib/exe/fetch.php文件获取的,需要传入特殊的参数namespace:文件名称)
    • markdown的插件会出现排版不正确问题
    • dokuwiki对中文分词支持不太好,集成中文分词见DokuWiki集成中文分词SCWS

    参考链接

    dokuwiki安装使用教程(支持中文、editor.md、粘贴上传图片)

    相关文章

      网友评论

          本文标题:DokuWiki安装+集成markdown编辑器editor.m

          本文链接:https://www.haomeiwen.com/subject/dmvoaqtx.html