Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何为Wordpress聊天室插件中的特定单词添加背景/突出显示颜色?_Javascript_Php_Wordpress_Chatroom - Fatal编程技术网

Javascript 如何为Wordpress聊天室插件中的特定单词添加背景/突出显示颜色?

Javascript 如何为Wordpress聊天室插件中的特定单词添加背景/突出显示颜色?,javascript,php,wordpress,chatroom,Javascript,Php,Wordpress,Chatroom,大纲- 我正在运行WordPressV4安装,并安装了聊天室插件:(下面是完整代码) 我希望能够突出显示用户发布消息时聊天中出现的特定单词。例如,每次用户发布带有“Dog”一词的消息时,它都会有背景色,以便向所有人突出显示 由于插件的HTML输出是纯HTML,因此我找到的最佳解决方案是以下工作示例: 问题- 当在聊天室所在的页面上使用上面JSFIDLE中的脚本时,该脚本似乎找不到单词或无法替换它们。我不明白为什么,因为聊天室脚本输出的HTML是纯HTML(正如JSFIDLE中所示)。还值得注意的

大纲-
我正在运行WordPressV4安装,并安装了聊天室插件:(下面是完整代码)

我希望能够突出显示用户发布消息时聊天中出现的特定单词。例如,每次用户发布带有“Dog”一词的消息时,它都会有背景色,以便向所有人突出显示

由于插件的HTML输出是纯HTML,因此我找到的最佳解决方案是以下工作示例:

问题-
当在聊天室所在的页面上使用上面JSFIDLE中的脚本时,该脚本似乎找不到单词或无法替换它们。我不明白为什么,因为聊天室脚本输出的HTML是纯HTML(正如JSFIDLE中所示)。还值得注意的是,脚本将查找并替换在同一页面上写入HTML源代码的单词

代码-
下面是聊天室插件的PHP、Javascript和示例HTML输出。我没有写这个插件,而原作者提供的支持非常有限

PHP:

课堂聊天室{
函数_u构造(){
注册激活钩子(uu文件,数组($this,'activation_钩子');
寄存器去激活挂钩(uu文件,数组($this,'deactivation_挂钩'));
添加操作('init',数组('this',register\u post\u types');
添加_操作('wp_排队_脚本',数组($this,'enqueue_脚本'));
添加操作('save_post',数组('this'maybe_create_chatroom_log_file'),10,2);
添加动作('wp_head',数组('define_javascript_variables');
添加动作('wp\uajax\ucheck\uupdates',数组('ajax\ucheck\uupdates\uhandler');
添加动作('wp_ajax_send_message',数组('ajax_send_message_handler');
添加_过滤器('the_content',array($this,'the_content_filter'));
}
函数激活_hook(){
$this->register_post_types();
刷新或重写规则();
}
功能停用_hook(){
刷新或重写规则();
}
函数寄存器\u post\u类型(){
$labels=数组(
'name'=>x('chattrooms','post type general name','chattroom'),
'singular_name'=>_x('Chat Room','post type singular name','Chat Room'),
'add_new'=>\u x('add new','book','chattroom'),
'add_new_item'=>\('add new Chat Room','Chat Room'),
'edit_item'=>'('edit Chat Room','Chat Room'),
“新建项目”=>(“新建聊天室”、“聊天室”),
'all_items'=>'('all Chat room','Chat room'),
“查看项目”=>“(“查看聊天室”、“聊天室”),
“搜索项目”=>“(“搜索聊天室”、“聊天室”),
“未找到”=>“(“未找到聊天室”,“聊天室”),
'not_found_in_trash'=>,
“父项冒号”=>“”,
'菜单名称'=>\('聊天室','聊天室')
);
$args=数组(
“标签”=>$labels,
“public”=>正确,
“公开可查询”=>正确,
'show_ui'=>true,
“在菜单中显示”=>true,
'query_var'=>true,
“能力类型”=>“职位”,
“has_archive”=>true,
“分层”=>false,
“菜单位置”=>null,
“在导航菜单中显示”=>true,
'支持'=>数组('title')
);
注册发布类型('chattroom',$args);
}
函数排队_脚本(){
全球$员额;
如果($post->post_type!=“聊天室”)
回来
wp_排队_脚本('jquery');
wp_enqueue_脚本('chattroom',plugins_url('chattroom.js',uu文件_uu));
wp_enqueue_样式(‘聊天室样式’、插件_url(‘chat-room.css’、文件_uuu));
}
函数可能\u创建\u聊天室\u日志\u文件($post\u id,$post){
if(空($post->post_-type)| |$post->post_-type!=“聊天室”)
回来
$upload_dir=wp_upload_dir();
$log_filename=$upload_dir['basedir']./chatter/'.$post->post_name.-'.date('m-d-y',time());
如果(文件存在($log\u文件名))
回来
wp_mkdir_p($upload_dir['basedir']./chatter/');
$handle=fopen($log_文件名,'w');
fwrite($handle,json_encode(array());
//TODO在用户无法创建文件时创建警告,并建议在wp config中放置FTP凭据
}
函数define_javascript_variables(){
全球$员额;
if(空($post->post_-type)| |$post->post_-type!=“聊天室”)
返回;?>
var ajaxurl='';
var聊天室_slug='';

我假设“函数聊天室\发送\消息()”将消息发送到php脚本,然后“函数聊天室\检查\更新()用更新后的消息替换聊天盒中的所有消息?我相信是这样,但我没有制作这个插件,正如前面提到的,我对Javascript/PHP的知识相当有限。您能否编辑您的帖子,将:var chats in chatroom_check_updates()的输出包括在内@Bioto我已经编辑并添加了当用户发送消息时存储在文件中的代码。我对此很陌生,因此如果我不完全理解你要求我做的事情,我深表歉意。-你必须这样做。在添加到聊天框之前,我会做所有的更改。这样从一开始所有如果进行了更改,则不必运行任何额外的脚本。
Class Chatroom {
    function __construct() {
        register_activation_hook( __FILE__, array( $this, 'activation_hook' ) );
        register_deactivation_hook( __FILE__, array( $this, 'deactivation_hook' ) );
        add_action( 'init', array( $this, 'register_post_types' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
        add_action( 'save_post', array( $this, 'maybe_create_chatroom_log_file' ), 10, 2 );
        add_action( 'wp_head', array( $this, 'define_javascript_variables' ) );
        add_action( 'wp_ajax_check_updates', array( $this, 'ajax_check_updates_handler' ) );
        add_action( 'wp_ajax_send_message', array( $this, 'ajax_send_message_handler' ) );
        add_filter( 'the_content', array( $this, 'the_content_filter' ) );
    }
    function activation_hook() {
        $this->register_post_types();
        flush_rewrite_rules();
    }
    function deactivation_hook() {
        flush_rewrite_rules();
    }
    function register_post_types() {
        $labels = array(
            'name' => _x( 'Chat Rooms', 'post type general name', 'chatroom' ),
            'singular_name' => _x( 'Chat Room', 'post type singular name', 'chatroom' ),
            'add_new' => _x( 'Add New', 'book', 'chatroom' ),
            'add_new_item' => __( 'Add New Chat Room', 'chatroom' ),
            'edit_item' => __( 'Edit Chat Room', 'chatroom' ),
            'new_item' => __( 'New Chat Room', 'chatroom' ),
            'all_items' => __( 'All Chat Rooms', 'chatroom' ),
            'view_item' => __( 'View Chat Room', 'chatroom' ),
            'search_items' => __( 'Search Chat Rooms', 'chatroom' ),
            'not_found' => __( 'No Chat Rooms found', 'chatroom' ),
            'not_found_in_trash' => __( 'No Chat Rooms found in Trash', 'chatroom' ),
            'parent_item_colon' => '',
            'menu_name' => __( 'Chat Rooms', 'chatroom' )
        );
        $args = array(
            'labels' => $labels,
            'public' => true,
            'publicly_queryable' => true,
            'show_ui' => true,
            'show_in_menu' => true,
            'query_var' => true,
            'capability_type' => 'post',
            'has_archive' => true,
            'hierarchical' => false,
            'menu_position' => null,
            'show_in_nav_menus' => true,
            'supports' => array( 'title' )
        );
        register_post_type( 'chat-room', $args );
    }
    function enqueue_scripts() {
        global $post;
        if ( $post->post_type != 'chat-room' )
            return;
        wp_enqueue_script( 'jquery' );
        wp_enqueue_script( 'chat-room', plugins_url( 'chat-room.js', __FILE__ ) );
        wp_enqueue_style( 'chat-room-styles', plugins_url( 'chat-room.css', __FILE__ ) );
    }
    function maybe_create_chatroom_log_file( $post_id, $post ) {
        if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
            return;
        $upload_dir = wp_upload_dir();
        $log_filename = $upload_dir['basedir'] . '/chatter/' . $post->post_name . '-' . date( 'm-d-y', time() );
        if ( file_exists( $log_filename ) )
            return;
        wp_mkdir_p( $upload_dir['basedir'] . '/chatter/' );
        $handle = fopen( $log_filename, 'w' );
        fwrite( $handle, json_encode( array() ) );
        // TODO create warnings if the user can't create a file, and suggest putting FTP creds in wp-config
    }
    function define_javascript_variables() {
        global $post;
        if ( empty( $post->post_type ) || $post->post_type != 'chat-room' )
            return; ?>
        <script>
        var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
        var chatroom_slug = '<?echo $post->post_name; ?>';
        </script>
        <?php
    }
    function ajax_check_updates_handler() {
        $upload_dir = wp_upload_dir();
        $log_filename = $this->get_log_filename( $_POST['chatroom_slug'] );
        $contents = $this->parse_messages_log_file( $log_filename );
        $messages = json_decode( $contents );
        foreach ( $messages as $key => $message ) {
            if ( $message->id <= $_POST['last_update_id'] )
                unset( $messages[$key] );
        }
        $messages = array_values( $messages );
        echo json_encode( $messages );
        die;
    }
    /**
     * AJAX server-side handler for sending a message.
     *
     * Stores the message in a recent messages file.
     *
     * Clears out cache of any messages older than 10 seconds.
     */
    function ajax_send_message_handler() {
        $current_user = wp_get_current_user();
        $this->save_message( $_POST['chatroom_slug'], $current_user->id, $_POST['message'] );
        die;
    }
    function save_message( $chatroom_slug, $user_id, $content ) {
        $user = get_userdata( $user_id );
        if ( ! $user_text_color = get_user_meta( $user_id, 'user_color', true ) ) {
            // Set random color for each user
            $red = rand( 0, 16 );
            $green = 16 - $red;
            $blue = rand( 0, 16 );
            $user_text_color = '#' . dechex( $red^2 ) . dechex( $green^2 ) . dechex( $blue^2 );
            update_user_meta( $user_id, 'user_color', $user_text_color );
        }
        $content = esc_attr( $content );
        // Save the message in recent messages file
        $log_filename = $this->get_log_filename( $chatroom_slug );
        $contents = $this->parse_messages_log_file( $log_filename );
        $messages = json_decode( $contents );
        $last_message_id = 0; // Helps determine the new message's ID
        foreach ( $messages as $key => $message ) {
            if ( time() - $message->time > 10 ) {
                $last_message_id = $message->id;
                unset( $messages[$key] );
            }
            else {
                break;
            }
        }
        $messages = array_values( $messages );
        if ( ! empty( $messages ) )
            $last_message_id = end( $messages )->id;
        $new_message_id = $last_message_id + 1;
        $messages[] = array(
            'id' => $new_message_id,
            'time' => time(),
            'sender' => $user_id,
            'contents' => $content,
            'html' => '<div class="chat-message-' . $new_message_id . '"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
        );
        $this->write_log_file( $log_filename, json_encode( $messages ) );
        // Save the message in the daily log
        $log_filename = $this->get_log_filename( $chatroom_slug, date( 'm-d-y', time() ) );
        $contents = $this->parse_messages_log_file( $log_filename );
        $messages = json_decode( $contents );
        $messages[] = array(
            'id' => $new_message_id,
            'time' => time(),
            'sender' => $user_id,
            'contents' => $content,
            'html' => '<div class="chat-message-' . $new_message_id .'"><strong style="color: ' . $user_text_color . ';">' . $user->user_login . '</strong>: ' . $content . '</div>',
        );
        $this->write_log_file( $log_filename, json_encode( $messages ) );
    }
    function write_log_file( $log_filename, $content ) {
        $handle = fopen( $log_filename, 'w' );
        fwrite( $handle, $content );
    }
    function get_log_filename( $chatroom_slug, $date = 'recent' ) {
        $upload_dir = wp_upload_dir();
        $log_filename = $upload_dir['basedir'] . '/chatter/' . $chatroom_slug . '-' . $date;
        return $log_filename;
    }
    function parse_messages_log_file( $log_filename ) {
        $upload_dir = wp_upload_dir();
        $handle = fopen( $log_filename, 'r' );
        $contents = fread( $handle, filesize( $log_filename ) );
        fclose( $handle );
        return $contents;
    }
    function the_content_filter( $content ) {
        global $post;
        if ( $post->post_type != 'chat-room' )
            return $content;
        if ( ! is_user_logged_in() )  {
            ?>You need to be logged in to participate in the chatroom.<?php
            return;
        }
        ?>
        <div class="chat-container">
        </div>
        <textarea class="chat-text-entry"></textarea>
        <?php
        return '';
    }
}
$chatroom = new Chatroom();
var last_update_received = 0;
function chatroom_check_updates() {
    jQuery.post(
        ajaxurl,
        {
            action: 'check_updates',
            chatroom_slug: chatroom_slug,
            last_update_id: last_update_id
        },
        function (response) {
            chats = jQuery.parseJSON( response );
            if ( chats !== null ) {
                for ( i = 0; i < chats.length; i++ ) {
                    if ( jQuery('div.chat-container div.chat-message-'+chats[i].id).length )
                        continue;
                    jQuery('div.chat-container').html( jQuery('div.chat-container').html() + chatroom_strip_slashes(chats[i].html) );
                    last_update_id = chats[i].id;
                    jQuery('div.chat-container').animate({ scrollTop: jQuery('div.chat-container')[0].scrollHeight - jQuery('div.chat-container').height() }, 100);
                }
            }
        }
    );
    setTimeout( "chatroom_check_updates()", 1000 );
}

function chatroom_strip_slashes(str) {
    return (str + '').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
        case '\\':
            return '\\';
        case '0':
            return '\u0000';
        case '':
            return '';
        default:
            return n1;
        }
    });
}

jQuery(document).ready( function() {
    last_update_id = 0;
    chatroom_check_updates();
    jQuery( 'textarea.chat-text-entry' ).keypress( function( event ) {
        if ( event.charCode == 13 || event.keyCode == 13 ) {
            chatroom_send_message();
            return false;
        }
    });
});

function chatroom_send_message() {
    message = jQuery( 'textarea.chat-text-entry' ).val();
    jQuery( 'textarea.chat-text-entry' ).val('');
    jQuery.post(
        ajaxurl,
        {
            action: 'send_message',
            chatroom_slug: chatroom_slug,
            message: message
        },
        function (response) {
        }
    );

}
<div class="chat-container">
    <div class="chat chat-message-111"><strong style="color: #840;">User 1</strong>: What is your favourite animal?</div>
    <div class="chat chat-message-112"><strong style="color: #840;">User 2</strong>: I vote for #dog. </div>
     <div class="chat chat-message-113"><strong style="color: #840;">User 3</strong>: I have a #cat!</div>
        </div>
[{"id":129,"time":1428340673,"sender":1,"contents":"What is your favourite animal?","html":"<div class=\"chat chat-message-129\"><strong style=\"color: #840;\">User 1<\/strong>: What is your favourite animal?<\/div>"},
{"id":130,"time":1428351683,"sender":2,"contents":"I vote for #dog.","html":"<div class=\"chat chat-message-130\"><strong style=\"color: #840;\">User 2<\/strong>: I vote for #dog.<\/div>"},
{"id":131,"time":1428352376,"sender":3,"contents":"I have a #cat!","html":"<div class=\"chat chat-message-131\"><strong style=\"color: #840;\">User 3<\/strong>: I have a #cat!<\/div>"}]