Справочник функций

Ваш аккаунт

Войти через: 
Забыли пароль?
Регистрация
Информацию о новых материалах можно получать и без регистрации:

Почтовая рассылка

Подписчиков: -1
Последний выпуск: 19.06.2015

Авто обновление скрипта

74K
04 сентября 2011 года
lSanDl
3 / / 04.09.2011
Всем привет, в общем есть вот такой скрипт, который выдает инфу о играющем треке на радио, как сделать что бы он обновлялся, без обновления всей страницы, обновлять один блок не могу, тк в этом блоке находится еще и плеер, и обновляя его будет обрываться музыка, и еще мб подскажете как сделать что бы плеер не обновлялся когда обновляется вся страница?
скрипт урезал что бы вместить
Код:
<?php
/**
 * Plugin Name: Icecast Now Playing
 * Plugin URI: http://www.galwayland.com/?page_id=140
 * Description: A widget to display Icecast server statistics.
 * Version: 1.6.0
 * Author: Wlliam J. Galway
 * Author URI: http://galwayland.com
 *
 * Icecast Now Playing a widget to display Icecast server connection stats in a Wordpress blog.
 *   Copyright (C) <2010>  <William J. Galway>
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


/**
 * Add function to widgets_init that'll load our widget.
 */

error_reporting(-1);

add_action( 'widgets_init', 'icecast_status_load_widgets' );

/**
 * Register our widget.
 * 'Icecast_Status_Widget' is the widget class used below.
 */

function icecast_status_load_widgets() {
    register_widget( 'Icecast_Status_Widget' );
}

/**
 * Icecast Status Widget class.
 */

error_reporting(1);

class Icecast_Status_Widget extends WP_Widget {

    /**
     * Widget setup.
     */

    function Icecast_Status_Widget() {
        /* Widget settings. */
        $widget_ops = array( 'classname' => 'icecaststatus', 'description' => __('Display Icecast statistics.', 'icecaststatus') );

        /* Widget control settings. */
        $control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'icecast-widget' );

        /* Create the widget. */
        $this->WP_Widget( 'icecast-widget', __('Icecast Now Playing', 'icecaststatus'), $widget_ops, $control_ops );
    }

    /**
     * How to display the widget on the screen.
     */

    function widget( $args, $instance ) {
        extract( $args );

        /* Our variables from the widget settings. */
        $title = apply_filters('widget_title', $instance['title'] );
        $server = $instance['servername'];
        $username = $instance['username'];
        $password = $instance['password'];
        $mount1= $instance['mount1'];
        $mount2= $instance['mount2'];
        $description1= $instance['description1'];
        $description2= $instance['description2'];

        /* Before widget (defined by themes). */
        echo $before_widget;

        /* Display the widget title if one was input (before and after defined by themes). */
         if ( $title )
            echo $before_title . $title . $after_title;
    // Open Icecast stats url
    $fp = fopen("http://$username:$password@$server/admin/stats","r");
    if (!$fp) {
        echo "Error reading Icecast data from $server\n";
    }
    else {
    stream_set_timeout($fp, 2);
    $stats = "";
    while(!feof($fp))
    {  
         $stats .= fread($fp, 8192);
    }
    fclose($fp);

    // Now parse the XML output for our mountpoint
    $xml_parser = xml_parser_create();
    xml_parse_into_struct($xml_parser, $stats, $vals, $index);
    xml_parser_free($xml_parser);
   
    $params = array();
    $level = array();
    foreach ($vals as $xml_elem) {
         if ($xml_elem['type'] == 'open') {
            if (array_key_exists('attributes',$xml_elem)) {
                list($level[$xml_elem['level']],$extra) =
    array_values($xml_elem['attributes']);
             } else {
                 $level[$xml_elem['level']] = $xml_elem['tag'];
             }
         }
         if ($xml_elem['type'] == 'complete') {
             $start_level = 1;
             $php_stmt = '$params';
             while($start_level < $xml_elem['level']) {
                 $php_stmt .= '[$level['.$start_level.']]';
                 $start_level++;
             }
             $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
             eval($php_stmt);
         }

        $info = array(
        'track1' => $params['ICESTATS'][$mount1]['TITLE'],
        'track2' => $params['ICESTATS'][$mount2]['TITLE'],
        'listen1' => $params['ICESTATS'][$mount1]['LISTENURL'],
        'listen2' => $params['ICESTATS'][$mount2]['LISTENURL'],
        'users1' => $params['ICESTATS'][$mount1]['LISTENERS'],
        'users2' => $params['ICESTATS'][$mount2]['LISTENERS'],
        'server1' => $params['ICESTATS'][$mount1]['SERVER_URL'],
        'server2' => $params['ICESTATS'][$mount2]['SERVER_URL']);
}

    /**
     * Begin display Icecast connection statistics in widget
     * Change the widget display layout here
     */

    if ($info['track1']){
    if ($description1){
        echo "<strong>$description1</strong><br/>";
        }
    echo "<a href=\"$info[listen1].m3u\">$info[track1]</a>\n                         ";
    echo "<br/>";
    echo "Слушает:<a href=\"$info[server1]\">$info[users1]</a>";
    echo "<br />";
    }

    if ($info['track2']){
    if ($description2){
    echo "<strong>$description2</strong><br/>";
    }
    echo "<a href=\"$info[listen2].m3u\">$info[track2]</a>\n                         ";
    echo "<br />";
    echo "Слушает:<a href=\"$info[server2]\">$info[users2]</a>";
    echo "<br />";
    }
    }
    // End of display Icecast connection statistics in widget.


        /* After widget (defined by themes). */
        echo $after_widget;
    }

    /**
     * Update the widget settings.
     */

    function update( $new_instance, $old_instance ) {
        $instance = $old_instance;

        /* Strip tags for title and name to remove HTML (important for text inputs). */
        /* Necessary for form data persistance. */
        $instance['title'] = strip_tags( $new_instance['title'] );
        $instance['servername'] = strip_tags( $new_instance['servername'] );
        $instance['username'] = strip_tags( $new_instance['username'] );
        $instance['password'] = strip_tags( $new_instance['password'] );
        $instance['mount1'] = strip_tags( $new_instance['mount1'] );
        $instance['mount2'] = strip_tags( $new_instance['mount2'] );
        $instance['description1'] = strip_tags( $new_instance['description1'] );
        $instance['description2'] = strip_tags( $new_instance['description2'] );

        return $instance;
    }

    /**
     * Displays the widget settings controls on the widget panel.
     * Make use of the get_field_id() and get_field_name() function
     * when creating your form elements. This handles the confusing stuff.
     */

    function form( $instance ) {

        /* Set up some default widget settings. */
        $defaults = array(
            'title' => __('Icecast', 'icecaststatus'),
            'servername' => __('127.0.0.1:8000', 'icecaststatus'),
            'username' => __('admin', 'icecaststatus'),
            'password' => __('password', 'icecaststatus'),
            'mount1' => __('/ices', 'icecaststatus'),
            'mount2' => __('/mpd', 'icecaststatus'),
            'description1' => __('Now Playing', 'icecaststatus'),
            'description2' => __('Now Playing', 'icecaststatus'));


        $instance = wp_parse_args( (array) $instance, $defaults ); ?>
          <!-- Widget Title: Text Input -->
                <p>
                        <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'hybrid'); ?></label>
                        <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width:100%;" />
                </p>


        <!-- Server Name: Text Input -->
        <p>
            <label for="<?php echo $this->get_field_id( 'servername' ); ?>"><?php _e('server name:port', 'icecaststatus'); ?></label>
            <input id="<?php echo $this->get_field_id( 'servername' ); ?>" name="<?php echo $this->get_field_name( 'servername' ); ?>" value="<?php echo $instance['servername']; ?>" style="width:100%;" />
        </p>
       
        <!-- User Name: Text Input -->
        <p>
            <label for="<?php echo $this->get_field_id( 'username' ); ?>"><?php _e('username:', 'icecaststatus'); ?></label>
            <input id="<?php echo $this->get_field_id( 'username' ); ?>" name="<?php echo $this->get_field_name( 'username' ); ?>" value="<?php echo $instance['username']; ?>" style="width:100%;" />
        </p>

        <!-- Password: Text Input -->
        <p>
            <label for="<?php echo $this->get_field_id( 'password' ); ?>"><?php _e('password:', 'icecaststatus'); ?></label>
            <input id="<?php echo $this->get_field_id( 'password' ); ?>" name="<?php echo $this->get_field_name( 'password' ); ?>" value="<?php echo $instance['password']; ?>" style="width:100%;" />
        </p>
       
        <!-- Mount: Text Input -->
        <p>
            <label for="<?php echo $this->get_field_id( 'mount1' ); ?>"><?php _e('mount 1:', 'icecaststatus'); ?></label>
            <input id="<?php echo $this->get_field_id( 'mount1' ); ?>" name="<?php echo $this->get_field_name( 'mount1' ); ?>" value="<?php echo $instance['mount1']; ?>" style="width:100%;" />
        </p>
   
        <!-- Stream Description: Text Input -->
        <p>
            <label for="<?php echo $this->get_field_id( 'description1' ); ?>"><?php _e('stream description:', 'icecaststatus'); ?></label>
            <input id="<?php echo $this->get_field_id( 'description1' ); ?>" name="<?php echo $this->get_field_name( 'description1' ); ?>" value="<?php echo $instance['description1']; ?>" style="width:100%;" />
        </p>
13
04 сентября 2011 года
RussianSpy
3.0K / / 04.07.2006
Без серьезных изменений структуры сайта никак не сделать. Выходов два:
1) Фреймы
2) AJAX-навигация (по аналоги как сделано в контакте)

Первый способ сложен тем, что взаимодействие между фреймами не всегда тривиально и просто. Плюс к этому существуют серьезные ограничения касающиеся оформления и дизайна, которые можно применять к сайту с фреймами. Второй способ сложен тем, что потребует хороших знаний JavaScript - вылезет много подводных камней в работе с разными браузерами, вылезут проблемы с именованием переменных на разных страницах. В общем и целом второй способ надежнее в плане стабильности, первый немного проще в реализации.

PS да ну и еще можно рассмотреть третий способ - открывать плеер на отдельной вкладке браузера
74K
04 сентября 2011 года
lSanDl
3 / / 04.09.2011
а можно ли обновлять только вот эту часть?

Код:
/**    
     * Begin display Icecast connection statistics in widget
     * Change the widget display layout here
     */

    if ($info['track1']){
    if ($description1){
        echo "<strong>$description1</strong><br/>";
        }
    echo "<a href=\"$info[listen1].m3u\">$info[track1]</a>\n                         ";
    echo "<br/>";
    echo "Слушает:<a href=\"$info[server1]\">$info[users1]</a>";
    echo "<br />";
    }

    if ($info['track2']){
    if ($description2){
    echo "<strong>$description2</strong><br/>";
    }
    echo "<a href=\"$info[listen2].m3u\">$info[track2]</a>\n                         ";
    echo "<br />";
    echo "Слушает:<a href=\"$info[server2]\">$info[users2]</a>";
    echo "<br />";
    }
    }
    // End of display Icecast connection statistics in widget.
13
04 сентября 2011 года
RussianSpy
3.0K / / 04.07.2006
Ну вы говорили про плеер который не должен обрываться. PHP тут почти ни при чем - это проблема клиентской стороны а не серверной. Если же вам нужно только получать информацию о текущей песне, то тут однозначно AJAX.
74K
04 сентября 2011 года
lSanDl
3 / / 04.09.2011
я сей час говорю о том куске скрипта, который я показал, как мне обновлять его с периодичностью в 20 сек, о плеере вообще сей час забудьте
271
04 сентября 2011 года
MrXaK
721 / / 31.12.2002
Как вариант - постоянный коннект, max execution time в бесконечность (set_time_limit(0)), бесконечный цикл внутри скрипта, слип на время и отдавать с буферизацией flush()
Но так сейчас никто уже не делает)) RussianSpy говорит вам, что клиентская сторона должна заботиться об этом и запрашивать AJAXом страницу с инфой раз в 20 секунд. А бэкенд, не тягая всего остального, должен отвечать, что проигрывается
Реклама на сайте | Обмен ссылками | Ссылки | Экспорт (RSS) | Контакты
Добавить статью | Добавить исходник | Добавить хостинг-провайдера | Добавить сайт в каталог