Ajax Chat v1

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

Ajax Chat v1

Сообщение NycuDR » 03 авг 2008, 10:49

Итак я зделал чат надеюсь вам понравится я уже видел на форуме один чат но у него пара моментов которые мне не понравились:
во первых мне не нравится интерфейс потому что меню с лева там ищё какието штуки,
во вторых мне не понравилось ник в чате он не соответствует имени на трекере!!
там я не помню чтото еще было но я давно тестировал вот сейчас решил подарить мой чат всем!!
Итак начнём:
в директории трекера создаём файл chat.php с кодом:
Код: Выделить всё
<?php
$tracker_root_path = './';
require($tracker_root_path . 'include/config.php');
@include ($tracker_root_path . 'include/overall_header.php');
@include ($tracker_root_path . 'include/overall_footer.php');
$userdata = session_pagestart($user_ip);
init_userprefs($userdata);

stdhead($lang['chat']);
$template->set_filenames(array(
   'body' => 'chat.html')
);
        $template->assign_vars(array(
                'CHAT_NICK' => $userdata['name'] )
        );
stdfoot();
?>


после создаём chat.css с этим кодом:
Код: Выделить всё
#daddy-shoutbox {
      padding: 5px;
      background: #3E5468;
      color: white;
      width: 600px;
      font-family: Arial,Helvetica,sans-serif;
      font-size: 11px;
    }
    .shoutbox-list {
      border-bottom: 1px solid #627C98;
     
      padding: 5px;
      display: none;
    }
    #daddy-shoutbox-list {
      text-align: left;
      margin: 0px auto;
    }
    #daddy-shoutbox-form {
      text-align: left;
     
    }
    .shoutbox-list-time {
      color: #8DA2B4;
    }
    .shoutbox-list-nick {
      margin-left: 5px;
      font-weight: bold;
    }
    .shoutbox-list-message {
      margin-left: 5px;
    }



после заходим в директорию темы (templates/ваша тема/) и там есть файл chat.html с коекаким кодом но мы стираем тот код и вместо него ставим:
Код: Выделить всё
<!-- INCLUDE overall_header.html -->

<div id="daddy-shoutbox">
    <div id="daddy-shoutbox-list"></div>
    <br />
    <center><form id="daddy-shoutbox-form" action="shoutbox/daddy-shoutbox.php?action=add&nick={CHAT_NICK}" method="post">
    Say: <input type="text" name="message" size="60" />
    <input type="submit" value="Submit" />
    <span id="daddy-shoutbox-response"></span>
    </form></center>
  </div>
  </center>
 
  <script type="text/javascript">
        var count = 0;
        var files = 'shoutbox/';
        var lastTime = 0;
       
        function prepare(response) {
          var d = new Date();
          count++;
          d.setTime(response.time*1000);
          var mytime = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
          var string = '<div class="shoutbox-list" id="list-'+count+'">'
              + '<span class="shoutbox-list-time">'+mytime+'</span>'
              + '<span class="shoutbox-list-nick">'+response.nickname+':</span>'
              + '<span class="shoutbox-list-message">'+response.message+'</span>'
              +'</div>';
         
          return string;
        }
       
        function success(response, status)  {
          if(status == 'success') {
            lastTime = response.time;
            $('#daddy-shoutbox-response').html('<img src="'+files+'images/accept.png" />');
            $('#daddy-shoutbox-list').append(prepare(response));
            $('input[@name=message]').attr('value', '').focus();
            $('#list-'+count).fadeIn('slow');
            timeoutID = setTimeout(refresh, 3000);
          }
        }
       
        function validate(formData, jqForm, options) {
          for (var i=0; i < formData.length; i++) {
              if (!formData[i].value) {
                  alert('Please fill in all the fields');
                  $('input[@name='+formData[i].name+']').css('background', 'red');
                  return false;
              }
          }
          $('#daddy-shoutbox-response').html('<img src="'+files+'images/loader.gif" />');
          clearTimeout(timeoutID);
        }

        function refresh() {
          $.getJSON(files+"daddy-shoutbox.php?action=view&time="+lastTime, function(json) {
            if(json.length) {
              for(i=0; i < json.length; i++) {
                $('#daddy-shoutbox-list').append(prepare(json[i]));
                $('#list-' + count).fadeIn('slow');
              }
              var j = i-1;
              lastTime = json[j].time;
            }
            //alert(lastTime);
          });
          timeoutID = setTimeout(refresh, 3000);
        }
       
        // wait for the DOM to be loaded
        $(document).ready(function() {
            var options = {
              dataType:       'json',
              beforeSubmit:   validate,
              success:        success
            };
            $('#daddy-shoutbox-form').ajaxForm(options);
            timeoutID = setTimeout(refresh, 100);
        });
  </script>
<!-- INCLUDE overall_footer.html -->


потом открываем файл overeall_header.html и после:
Код: Выделить всё
<title>{PAGE_TITLE}</title>

ставим:
Код: Выделить всё
<link rel="stylesheet" href="chat.css" type="text/css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
Последний раз редактировалось NycuDR 03 авг 2008, 11:58, всего редактировалось 2 раз(а).
NycuDR
 
Сообщения: 86
Зарегистрирован: 29 янв 2008, 00:45
Адрес трекера: http://xbitlord.co.cc/

Re: Ajax Chat v1

Сообщение NycuDR » 03 авг 2008, 10:52

И в той же папке создаём файл jquery.form.js с кодом:
Код: Выделить всё
jQuery.fn.ajaxSubmit = function(options) {
    if (typeof options == 'function')
        options = { success: options };

    options = jQuery.extend({
        url:    this.attr('action') || '',
        method: this.attr('method') || 'GET'
    }, options || {});

    // remap deprecated options (temporarily)
    options.success = options.success || options.after;
    options.beforeSubmit = options.beforeSubmit || options.before;
    options.type = options.type || options.method;

    var a = this.formToArray(options.semantic);

    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) return this;

    var q = jQuery.param(a);

    if (options.type.toUpperCase() == 'GET') {
        // if url already has a '?' then append args after '&'
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'

    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data, status) {
            jQuery(options.target).attr("innerHTML", data).evalScripts().each(oldSuccess, [data, status]);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i](data, status);
    };

    jQuery.ajax(options);
    return this;
};


jQuery.fn.ajaxForm = function(options) {
    return this.each(function() {
        jQuery("input:submit,input:image,button:submit", this).click(function(ev) {
            var $form = this.form;
            $form.clk = this;
            if (this.type == 'image') {
                if (ev.offsetX != undefined) {
                    $form.clk_x = ev.offsetX;
                    $form.clk_y = ev.offsetY;
                } else if (typeof jQuery.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = jQuery(this).offset();
                    $form.clk_x = ev.pageX - offset.left;
                    $form.clk_y = ev.pageY - offset.top;
                } else {
                    $form.clk_x = ev.pageX - this.offsetLeft;
                    $form.clk_y = ev.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() {
                $form.clk = $form.clk_x = $form.clk_y = null;
                }, 10);
        })
    }).submit(function(e) {
        jQuery(this).ajaxSubmit(options);
        return false;
    });
};


jQuery.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }
        var v = jQuery.fieldValue(el, true);
        if (v === null) continue;
        if (v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};


jQuery.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return jQuery.param(this.formToArray(semantic));
};


jQuery.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = jQuery.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return jQuery.param(a);
};


jQuery.fn.fieldValue = function(successful) {
    var cbVal, cbName;

    // loop until we find a value
    for (var i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = jQuery.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;

        // for checkboxes, consider multiple elements, for everything else just return first valid value
        if (el.type != 'checkbox') return v;

        cbName = cbName || el.name;
        if (cbName != el.name) // return if we hit a checkbox with a different name
            return cbVal;
        cbVal = cbVal || [];
        cbVal.push(v);
    }
    return cbVal;
};

jQuery.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && ( !n || el.disabled || t == 'reset' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                // extra pain for IE...
                var v = jQuery.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};



jQuery.fn.clearForm = function() {
    return this.each(function() {
        jQuery('input,select,textarea', this).clearFields();
    });
};


jQuery.fn.clearFields = jQuery.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};


jQuery.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};
NycuDR
 
Сообщения: 86
Зарегистрирован: 29 янв 2008, 00:45
Адрес трекера: http://xbitlord.co.cc/

Re: Ajax Chat v1

Сообщение NycuDR » 03 авг 2008, 10:52

потом в директории трекера создаём папку shoutbox
в ней создаём файл JSON.php с следуюшим кодом:
Код: Выделить всё
/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_SLICE',   1);

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_IN_STR',  2);

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_IN_ARR',  3);

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_IN_OBJ',  4);

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_IN_CMT', 5);

/**
 * Behavior switch for Services_JSON::decode()
 */
define('SERVICES_JSON_LOOSE_TYPE', 16);

/**
 * Behavior switch for Services_JSON::decode()
 */
define('SERVICES_JSON_SUPPRESS_ERRORS', 32);

/**
 * Converts to and from JSON format.
 *
 * Brief example of use:
 *
 * <code>
 * // create a new instance of Services_JSON
 * $json = new Services_JSON();
 *
 * // convert a complexe value to JSON notation, and send it to the browser
 * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
 * $output = $json->encode($value);
 *
 * print($output);
 * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
 *
 * // accept incoming POST data, assumed to be in JSON notation
 * $input = file_get_contents('php://input', 1000000);
 * $value = $json->decode($input);
 * </code>
 */
class Services_JSON
{
   /**
    * constructs a new JSON instance
    *
    * @param    int     $use    object behavior flags; combine with boolean-OR
    *
    *                           possible values:
    *                           - SERVICES_JSON_LOOSE_TYPE:  loose typing.
    *                                   "{...}" syntax creates associative arrays
    *                                   instead of objects in decode().
    *                           - SERVICES_JSON_SUPPRESS_ERRORS:  error suppression.
    *                                   Values which can't be encoded (e.g. resources)
    *                                   appear as NULL instead of throwing errors.
    *                                   By default, a deeply-nested resource will
    *                                   bubble up with an error, so all return values
    *                                   from encode() should be checked with isError()
    */
    function Services_JSON($use = 0)
    {
        $this->use = $use;
    }

   /**
    * convert a string from one UTF-16 char to one UTF-8 char
    *
    * Normally should be handled by mb_convert_encoding, but
    * provides a slower PHP-only method for installations
    * that lack the multibye string extension.
    *
    * @param    string  $utf16  UTF-16 character
    * @return   string  UTF-8 character
    * @access   private
    */
    function utf162utf8($utf16)
    {
        // oh please oh please oh please oh please oh please
        if(function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
        }

        $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});

        switch(true) {
            case ((0x7F & $bytes) == $bytes):
                // this case should never be reached, because we are in ASCII range
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                return chr(0x7F & $bytes);

            case (0x07FF & $bytes) == $bytes:
                // return a 2-byte UTF-8 character
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                return chr(0xC0 | (($bytes >> 6) & 0x1F))
                     . chr(0x80 | ($bytes & 0x3F));

            case (0xFFFF & $bytes) == $bytes:
                // return a 3-byte UTF-8 character
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                return chr(0xE0 | (($bytes >> 12) & 0x0F))
                     . chr(0x80 | (($bytes >> 6) & 0x3F))
                     . chr(0x80 | ($bytes & 0x3F));
        }

        // ignoring UTF-32 for now, sorry
        return '';
    }

   /**
    * convert a string from one UTF-8 char to one UTF-16 char
    *
    * Normally should be handled by mb_convert_encoding, but
    * provides a slower PHP-only method for installations
    * that lack the multibye string extension.
    *
    * @param    string  $utf8   UTF-8 character
    * @return   string  UTF-16 character
    * @access   private
    */
    function utf82utf16($utf8)
    {
        // oh please oh please oh please oh please oh please
        if(function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
        }

        switch(strlen($utf8)) {
            case 1:
                // this case should never be reached, because we are in ASCII range
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                return $utf8;

            case 2:
                // return a UTF-16 character from a 2-byte UTF-8 char
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                return chr(0x07 & (ord($utf8{0}) >> 2))
                     . chr((0xC0 & (ord($utf8{0}) << 6))
                         | (0x3F & ord($utf8{1})));

            case 3:
                // return a UTF-16 character from a 3-byte UTF-8 char
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                return chr((0xF0 & (ord($utf8{0}) << 4))
                         | (0x0F & (ord($utf8{1}) >> 2)))
                     . chr((0xC0 & (ord($utf8{1}) << 6))
                         | (0x7F & ord($utf8{2})));
        }

        // ignoring UTF-32 for now, sorry
        return '';
    }

   /**
    * encodes an arbitrary variable into JSON format
    *
    * @param    mixed   $var    any number, boolean, string, array, or object to be encoded.
    *                           see argument 1 to Services_JSON() above for array-parsing behavior.
    *                           if var is a strng, note that encode() always expects it
    *                           to be in ASCII or UTF-8 format!
    *
    * @return   mixed   JSON string representation of input var or an error if a problem occurs
    * @access   public
    */
    function encode($var)
    {
        switch (gettype($var)) {
            case 'boolean':
                return $var ? 'true' : 'false';

            case 'NULL':
                return 'null';

            case 'integer':
                return (int) $var;

            case 'double':
            case 'float':
                return (float) $var;

            case 'string':
                // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
                $ascii = '';
                $strlen_var = strlen($var);

               /*
                * Iterate over every character in the string,
                * escaping with a slash or encoding to UTF-8 where necessary
                */
                for ($c = 0; $c < $strlen_var; ++$c) {

                    $ord_var_c = ord($var{$c});

                    switch (true) {
                        case $ord_var_c == 0x08:
                            $ascii .= '\b';
                            break;
                        case $ord_var_c == 0x09:
                            $ascii .= '\t';
                            break;
                        case $ord_var_c == 0x0A:
                            $ascii .= '\n';
                            break;
                        case $ord_var_c == 0x0C:
                            $ascii .= '\f';
                            break;
                        case $ord_var_c == 0x0D:
                            $ascii .= '\r';
                            break;

                        case $ord_var_c == 0x22:
                        case $ord_var_c == 0x2F:
                        case $ord_var_c == 0x5C:
                            // double quote, slash, slosh
                            $ascii .= '\\'.$var{$c};
                            break;

                        case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
                            // characters U-00000000 - U-0000007F (same as ASCII)
                            $ascii .= $var{$c};
                            break;

                        case (($ord_var_c & 0xE0) == 0xC0):
                            // characters U-00000080 - U-000007FF, mask 110XXXXX
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
                            $c += 1;
                            $utf16 = $this->utf82utf16($char);
                            $ascii .= sprintf('\u%04s', bin2hex($utf16));
                            break;

                        case (($ord_var_c & 0xF0) == 0xE0):
                            // characters U-00000800 - U-0000FFFF, mask 1110XXXX
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            $char = pack('C*', $ord_var_c,
                                         ord($var{$c + 1}),
                                         ord($var{$c + 2}));
                            $c += 2;
                            $utf16 = $this->utf82utf16($char);
                            $ascii .= sprintf('\u%04s', bin2hex($utf16));
                            break;

                        case (($ord_var_c & 0xF8) == 0xF0):
                            // characters U-00010000 - U-001FFFFF, mask 11110XXX
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            $char = pack('C*', $ord_var_c,
                                         ord($var{$c + 1}),
                                         ord($var{$c + 2}),
                                         ord($var{$c + 3}));
                            $c += 3;
                            $utf16 = $this->utf82utf16($char);
                            $ascii .= sprintf('\u%04s', bin2hex($utf16));
                            break;

                        case (($ord_var_c & 0xFC) == 0xF8):
                            // characters U-00200000 - U-03FFFFFF, mask 111110XX
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            $char = pack('C*', $ord_var_c,
                                         ord($var{$c + 1}),
                                         ord($var{$c + 2}),
                                         ord($var{$c + 3}),
                                         ord($var{$c + 4}));
                            $c += 4;
                            $utf16 = $this->utf82utf16($char);
                            $ascii .= sprintf('\u%04s', bin2hex($utf16));
                            break;

                        case (($ord_var_c & 0xFE) == 0xFC):
                            // characters U-04000000 - U-7FFFFFFF, mask 1111110X
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            $char = pack('C*', $ord_var_c,
                                         ord($var{$c + 1}),
                                         ord($var{$c + 2}),
                                         ord($var{$c + 3}),
                                         ord($var{$c + 4}),
                                         ord($var{$c + 5}));
                            $c += 5;
                            $utf16 = $this->utf82utf16($char);
                            $ascii .= sprintf('\u%04s', bin2hex($utf16));
                            break;
                    }
                }

                return '"'.$ascii.'"';

            case 'array':
               /*
                * As per JSON spec if any array key is not an integer
                * we must treat the the whole array as an object. We
                * also try to catch a sparsely populated associative
                * array with numeric keys here because some JS engines
                * will create an array with empty indexes up to
                * max_index which can cause memory issues and because
                * the keys, which may be relevant, will be remapped
                * otherwise.
                *
                * As per the ECMA and JSON specification an object may
                * have any string as a property. Unfortunately due to
                * a hole in the ECMA specification if the key is a
                * ECMA reserved word or starts with a digit the
                * parameter is only accessible using ECMAScript's
                * bracket notation.
                */

                // treat as a JSON object
                if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
                    $properties = array_map(array($this, 'name_value'),
                                            array_keys($var),
                                            array_values($var));

                    foreach($properties as $property) {
                        if(Services_JSON::isError($property)) {
                            return $property;
                        }
                    }

                    return '{' . join(',', $properties) . '}';
                }

                // treat it like a regular array
                $elements = array_map(array($this, 'encode'), $var);

                foreach($elements as $element) {
                    if(Services_JSON::isError($element)) {
                        return $element;
                    }
                }

                return '[' . join(',', $elements) . ']';

            case 'object':
                $vars = get_object_vars($var);

                $properties = array_map(array($this, 'name_value'),
                                        array_keys($vars),
                                        array_values($vars));

                foreach($properties as $property) {
                    if(Services_JSON::isError($property)) {
                        return $property;
                    }
                }

                return '{' . join(',', $properties) . '}';

            default:
                return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
                    ? 'null'
                    : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
        }
    }

   /**
    * array-walking function for use in generating JSON-formatted name-value pairs
    *
    * @param    string  $name   name of key to use
    * @param    mixed   $value  reference to an array element to be encoded
    *
    * @return   string  JSON-formatted name-value pair, like '"name":value'
    * @access   private
    */
    function name_value($name, $value)
    {
        $encoded_value = $this->encode($value);

        if(Services_JSON::isError($encoded_value)) {
            return $encoded_value;
        }

        return $this->encode(strval($name)) . ':' . $encoded_value;
    }

   /**
    * reduce a string by removing leading and trailing comments and whitespace
    *
    * @param    $str    string      string value to strip of comments and whitespace
    *
    * @return   string  string value stripped of comments and whitespace
    * @access   private
    */
    function reduce_string($str)
    {
        $str = preg_replace(array(

                // eliminate single line comments in '// ...' form
                '#^\s*//(.+)$#m',

                // eliminate multi-line comments in '/* ... */' form, at start of string
                '#^\s*/\*(.+)\*/#Us',

                // eliminate multi-line comments in '/* ... */' form, at end of string
                '#/\*(.+)\*/\s*$#Us'

            ), '', $str);

        // eliminate extraneous space
        return trim($str);
    }

   /**
    * decodes a JSON string into appropriate variable
    *
    * @param    string  $str    JSON-formatted string
    *
    * @return   mixed   number, boolean, string, array, or object
    *                   corresponding to given JSON input string.
    *                   See argument 1 to Services_JSON() above for object-output behavior.
    *                   Note that decode() always returns strings
    *                   in ASCII or UTF-8 format!
    * @access   public
    */
    function decode($str)
    {
        $str = $this->reduce_string($str);

        switch (strtolower($str)) {
            case 'true':
                return true;

            case 'false':
                return false;

            case 'null':
                return null;

            default:
                $m = array();

                if (is_numeric($str)) {
                    // Lookie-loo, it's a number

                    // This would work on its own, but I'm trying to be
                    // good about returning integers where appropriate:
                    // return (float)$str;

                    // Return float or int, as appropriate
                    return ((float)$str == (integer)$str)
                        ? (integer)$str
                        : (float)$str;

                } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
                    // STRINGS RETURNED IN UTF-8 FORMAT
                    $delim = substr($str, 0, 1);
                    $chrs = substr($str, 1, -1);
                    $utf8 = '';
                    $strlen_chrs = strlen($chrs);

                    for ($c = 0; $c < $strlen_chrs; ++$c) {

                        $substr_chrs_c_2 = substr($chrs, $c, 2);
                        $ord_chrs_c = ord($chrs{$c});

                        switch (true) {
                            case $substr_chrs_c_2 == '\b':
                                $utf8 .= chr(0x08);
                                ++$c;
                                break;
                            case $substr_chrs_c_2 == '\t':
                                $utf8 .= chr(0x09);
                                ++$c;
                                break;
                            case $substr_chrs_c_2 == '\n':
                                $utf8 .= chr(0x0A);
                                ++$c;
                                break;
                            case $substr_chrs_c_2 == '\f':
                                $utf8 .= chr(0x0C);
                                ++$c;
                                break;
                            case $substr_chrs_c_2 == '\r':
                                $utf8 .= chr(0x0D);
                                ++$c;
                                break;

                            case $substr_chrs_c_2 == '\\"':
                            case $substr_chrs_c_2 == '\\\'':
                            case $substr_chrs_c_2 == '\\\\':
                            case $substr_chrs_c_2 == '\\/':
                                if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
                                   ($delim == "'" && $substr_chrs_c_2 != '\\"')) {
                                    $utf8 .= $chrs{++$c};
                                }
                                break;

                            case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
                                // single, escaped unicode character
                                $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
                                       . chr(hexdec(substr($chrs, ($c + 4), 2)));
                                $utf8 .= $this->utf162utf8($utf16);
                                $c += 5;
                                break;

                            case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
                                $utf8 .= $chrs{$c};
                                break;

                            case ($ord_chrs_c & 0xE0) == 0xC0:
                                // characters U-00000080 - U-000007FF, mask 110XXXXX
                                //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                                $utf8 .= substr($chrs, $c, 2);
                                ++$c;
                                break;

                            case ($ord_chrs_c & 0xF0) == 0xE0:
                                // characters U-00000800 - U-0000FFFF, mask 1110XXXX
                                // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                                $utf8 .= substr($chrs, $c, 3);
                                $c += 2;
                                break;

                            case ($ord_chrs_c & 0xF8) == 0xF0:
                                // characters U-00010000 - U-001FFFFF, mask 11110XXX
                                // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                                $utf8 .= substr($chrs, $c, 4);
                                $c += 3;
                                break;

                            case ($ord_chrs_c & 0xFC) == 0xF8:
                                // characters U-00200000 - U-03FFFFFF, mask 111110XX
                                // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                                $utf8 .= substr($chrs, $c, 5);
                                $c += 4;
                                break;

                            case ($ord_chrs_c & 0xFE) == 0xFC:
                                // characters U-04000000 - U-7FFFFFFF, mask 1111110X
                                // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                                $utf8 .= substr($chrs, $c, 6);
                                $c += 5;
                                break;

                        }

                    }

                    return $utf8;

                } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
                    // array, or object notation

                    if ($str{0} == '[') {
                        $stk = array(SERVICES_JSON_IN_ARR);
                        $arr = array();
                    } else {
                        if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
                            $stk = array(SERVICES_JSON_IN_OBJ);
                            $obj = array();
                        } else {
                            $stk = array(SERVICES_JSON_IN_OBJ);
                            $obj = new stdClass();
                        }
                    }

                    array_push($stk, array('what'  => SERVICES_JSON_SLICE,
                                           'where' => 0,
                                           'delim' => false));

                    $chrs = substr($str, 1, -1);
                    $chrs = $this->reduce_string($chrs);

                    if ($chrs == '') {
                        if (reset($stk) == SERVICES_JSON_IN_ARR) {
                            return $arr;

                        } else {
                            return $obj;

                        }
                    }

                    //print("\nparsing {$chrs}\n");

                    $strlen_chrs = strlen($chrs);

                    for ($c = 0; $c <= $strlen_chrs; ++$c) {

                        $top = end($stk);
                        $substr_chrs_c_2 = substr($chrs, $c, 2);

                        if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
                            // found a comma that is not inside a string, array, etc.,
                            // OR we've reached the end of the character list
                            $slice = substr($chrs, $top['where'], ($c - $top['where']));
                            array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
                            //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");

                            if (reset($stk) == SERVICES_JSON_IN_ARR) {
                                // we are in an array, so just push an element onto the stack
                                array_push($arr, $this->decode($slice));

                            } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
                                // we are in an object, so figure
                                // out the property name and set an
                                // element in an associative array,
                                // for now
                                $parts = array();
                               
                                if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
                                    // "name":value pair
                                    $key = $this->decode($parts[1]);
                                    $val = $this->decode($parts[2]);

                                    if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
                                        $obj[$key] = $val;
                                    } else {
                                        $obj->$key = $val;
                                    }
                                } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
                                    // name:value pair, where name is unquoted
                                    $key = $parts[1];
                                    $val = $this->decode($parts[2]);

                                    if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
                                        $obj[$key] = $val;
                                    } else {
                                        $obj->$key = $val;
                                    }
                                }

                            }

                        } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
                            // found a quote, and we are not inside a string
                            array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
                            //print("Found start of string at {$c}\n");

                        } elseif (($chrs{$c} == $top['delim']) &&
                                 ($top['what'] == SERVICES_JSON_IN_STR) &&
                                 ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
                            // found a quote, we're in a string, and it's not escaped
                            // we know that it's not escaped becase there is _not_ an
                            // odd number of backslashes at the end of the string so far
                            array_pop($stk);
                            //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");

                        } elseif (($chrs{$c} == '[') &&
                                 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
                            // found a left-bracket, and we are in an array, object, or slice
                            array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
                            //print("Found start of array at {$c}\n");

                        } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
                            // found a right-bracket, and we're in an array
                            array_pop($stk);
                            //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");

                        } elseif (($chrs{$c} == '{') &&
                                 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
                            // found a left-brace, and we are in an array, object, or slice
                            array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
                            //print("Found start of object at {$c}\n");

                        } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
                            // found a right-brace, and we're in an object
                            array_pop($stk);
                            //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");

                        } elseif (($substr_chrs_c_2 == '/*') &&
                                 in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
                            // found a comment start, and we are in an array, object, or slice
                            array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
                            $c++;
                            //print("Found start of comment at {$c}\n");

                        } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
                            // found a comment end, and we're in one now
                            array_pop($stk);
                            $c++;

                            for ($i = $top['where']; $i <= $c; ++$i)
                                $chrs = substr_replace($chrs, ' ', $i, 1);

                            //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");

                        }

                    }

                    if (reset($stk) == SERVICES_JSON_IN_ARR) {
                        return $arr;

                    } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
                        return $obj;

                    }

                }
        }
    }

    /**
     * @todo Ultimately, this should just call PEAR::isError()
     */
    function isError($data, $code = null)
    {
        if (class_exists('pear')) {
            return PEAR::isError($data, $code);
        } elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
                                 is_subclass_of($data, 'services_json_error'))) {
            return true;
        }

        return false;
    }
}

if (class_exists('PEAR_Error')) {

    class Services_JSON_Error extends PEAR_Error
    {
        function Services_JSON_Error($message = 'unknown error', $code = null,
                                     $mode = null, $options = null, $userinfo = null)
        {
            parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
        }
    }

} else {

    /**
     * @todo Ultimately, this class shall be descended from PEAR_Error
     */
    class Services_JSON_Error
    {
        function Services_JSON_Error($message = 'unknown error', $code = null,
                                     $mode = null, $options = null, $userinfo = null)
        {

        }
    }

}

и файл daddy-shoutbox.php:
Код: Выделить всё
<?php
  function replace(&$item, $key) {
    $item = str_replace('|', '-', $item);
  }
 
  if (!function_exists('file_put_contents')) {
      function file_put_contents($fileName, $data) {
         if (is_array($data)) {
            $data = join('', $data);
         }
         $res = @fopen($fileName, 'w+b');
         if ($res) {
            $write = @fwrite($res, $data);
            if($write === false) {
               return false;
            } else {
               return $write;
            }
         }
      }
   }
 
  //file_put_contents('debug.txt', print_r($_GET, true));
  switch($_GET['action']) {
    case 'add':
      array_walk($_POST, 'replace');
      $arr = file('messages.txt');
     
      if(count($arr) > 10)
        array_shift($arr);
     
      $_GET['nick'] = htmlentities($_GET['nick']);
      $_POST['message'] = htmlentities($_POST['message']);
      $time = time();
      $arr[] = $time.'|'.$_GET['nick'].'|'.$_POST['message'].'|'.$_SERVER['REMOTE_ADDR']."\n";
      file_put_contents('messages.txt', implode('', $arr));

      $data['response'] = 'Good work';
      $data['nickname'] = $_GET['nick'];
      $data['message'] = $_POST['message'];
      $data['time'] = $time;
    break;
   
    case 'view':
      $data = array();
      $arr = file('messages.txt');
      if(!$_GET['time'])
        $_GET['time'] = 0;
      foreach($arr as $row) {
        $aTemp = null;
        list($aTemp['time'], $aTemp['nickname'], $aTemp['message']) = explode('|', $row);
        if($aTemp['message'] AND $aTemp['time'] > $_GET['time'])
          $data[] = $aTemp;
      }
      //file_put_contents('debug.txt', print_r($data, true));
    break;
  }
 
  require_once('JSON.php');
  $json = new Services_JSON();
  $out = $json->encode($data);
  print $out;
?>

и создаём чистый файл messages.txt
потом там же в папке shoutbox создаём папку images и туда кидаем 2 картинки которые я прикрепил
accept.png
loader.gif

Ставьте линк на chat.php куда хотите вы!!!

Скрин:Изображение

Простите но есть один баг который я не могу исправить не идут русские буквы :(
У вас нет необходимых прав для просмотра вложений в этом сообщении.
NycuDR
 
Сообщения: 86
Зарегистрирован: 29 янв 2008, 00:45
Адрес трекера: http://xbitlord.co.cc/

Re: Ajax Chat v1

Сообщение simiys » 03 авг 2008, 11:00

уверен что
после заходим в директорию темы (templates/ваша тема/) и там есть файл chat.php с коекаким кодом но мы стираем тот код и вместо него ставим:
может chat.html :lol:
Аватара пользователя
simiys
 
Сообщения: 120
Зарегистрирован: 20 мар 2008, 14:57
Адрес трекера: http://coolnarod.7sk.ru/

Re: Ajax Chat v1

Сообщение simiys » 03 авг 2008, 11:18

И как поставить ссылку т.е куда чтоб чат был между : Приветствуем нового пользователя и Последние новости ;) Зарание спасибо!
А права надо ставить на файлы?
Аватара пользователя
simiys
 
Сообщения: 120
Зарегистрирован: 20 мар 2008, 14:57
Адрес трекера: http://coolnarod.7sk.ru/

Re: Ajax Chat v1

Сообщение NycuDR » 03 авг 2008, 12:49

<a href="chat.php">Чат</a> :D
NycuDR
 
Сообщения: 86
Зарегистрирован: 29 янв 2008, 00:45
Адрес трекера: http://xbitlord.co.cc/

Re: Ajax Chat v1

Сообщение simiys » 03 авг 2008, 13:01

А мона для танкистов! В каком файле.... :D Чтоб между приветствием нового пользователя и новости! :D
Аватара пользователя
simiys
 
Сообщения: 120
Зарегистрирован: 20 мар 2008, 14:57
Адрес трекера: http://coolnarod.7sk.ru/

Re: Ajax Chat v1

Сообщение titan » 03 авг 2008, 15:01

http://streamzone.ru/tracker/chat.php - на стримзоне чат...

только Нафаня не хочет им делится пока что...
titan
 
Сообщения: 26
Зарегистрирован: 19 дек 2007, 06:28

Re: Ajax Chat v1

Сообщение simiys » 03 авг 2008, 15:22

titan писал(а):http://streamzone.ru/tracker/chat.php - на стримзоне чат...

только Нафаня не хочет им делится пока что...

Он канал жрёт намного сильнее и этот чат лучше и удобнее... :)

Вот толька он пока не пашет у меня! Вроде ссылку поставил!См скрин! :x
У вас нет необходимых прав для просмотра вложений в этом сообщении.
Аватара пользователя
simiys
 
Сообщения: 120
Зарегистрирован: 20 мар 2008, 14:57
Адрес трекера: http://coolnarod.7sk.ru/

Re: Ajax Chat v1

Сообщение simiys » 03 авг 2008, 15:23

NycuDR Постучи мне в асю есть некотрые у тя не понятности в коде! Моя ICQ 483420805! :D
Аватара пользователя
simiys
 
Сообщения: 120
Зарегистрирован: 20 мар 2008, 14:57
Адрес трекера: http://coolnarod.7sk.ru/

Re: Ajax Chat v1

Сообщение Nafania » 03 авг 2008, 16:14

titan писал(а):http://streamzone.ru/tracker/chat.php - на стримзоне чат...

только Нафаня не хочет им делится пока что...

:D http://www.pjirc.com/main.php
Аватара пользователя
Nafania
Администратор
 
Сообщения: 1207
Зарегистрирован: 30 июн 2007, 16:10

Re: Ajax Chat v1

Сообщение simiys » 03 авг 2008, 17:37

Nafania писал(а):
titan писал(а):http://streamzone.ru/tracker/chat.php - на стримзоне чат...

только Нафаня не хочет им делится пока что...

:D http://www.pjirc.com/main.php

Он жрёт много.... надо найти что нить.... полегче!
Аватара пользователя
simiys
 
Сообщения: 120
Зарегистрирован: 20 мар 2008, 14:57
Адрес трекера: http://coolnarod.7sk.ru/

Re: Ajax Chat v1

Сообщение Nafania » 03 авг 2008, 18:19

Чего он много жрет-то? Обычный ява-гейт в ирц
Аватара пользователя
Nafania
Администратор
 
Сообщения: 1207
Зарегистрирован: 30 июн 2007, 16:10

Re: Ajax Chat v1

Сообщение simiys » 03 авг 2008, 18:25

Nafania писал(а):Чего он много жрет-то? Обычный ява-гейт в ирц

Лучше подскажи что с шутбоксом почему он не работает у меня а пишет Чат(( я уже всё проверял .... на правельность установки! :cry:
Аватара пользователя
simiys
 
Сообщения: 120
Зарегистрирован: 20 мар 2008, 14:57
Адрес трекера: http://coolnarod.7sk.ru/

Re: Ajax Chat v1

Сообщение sider » 04 авг 2008, 11:05

Nafania писал(а): :D http://www.pjirc.com/main.php


А можно поподробнее как его правильно установить используя наши каналы в irc, и желательно chat.php просто в 3 версии его нет. Помоги пожалуйста очень нужно, вещь действительно хорошая.
Аватара пользователя
sider
 
Сообщения: 22
Зарегистрирован: 14 июл 2007, 17:53
Адрес трекера: http://torrentzone.ru

Re: Ajax Chat v1

Сообщение simiys » 04 авг 2008, 16:02

NycuDR писал(а):Итак я зделал чат надеюсь вам понравится я уже видел на форуме один чат но у него пара моментов которые мне не понравились:
во первых мне не нравится интерфейс потому что меню с лева там ищё какието штуки,
во вторых мне не понравилось ник в чате он не соответствует имени на трекере!!
там я не помню чтото еще было но я давно тестировал вот сейчас решил подарить мой чат всем!!
Итак начнём:
в директории трекера создаём файл chat.php с кодом:
Код: Выделить всё
<?php
$tracker_root_path = './';
require($tracker_root_path . 'include/config.php');
@include ($tracker_root_path . 'include/overall_header.php');
@include ($tracker_root_path . 'include/overall_footer.php');
$userdata = session_pagestart($user_ip);
init_userprefs($userdata);

stdhead($lang['chat']);
$template->set_filenames(array(
   'body' => 'chat.html')
);
        $template->assign_vars(array(
                'CHAT_NICK' => $userdata['name'] )
        );
stdfoot();
?>


после создаём chat.css с этим кодом:
Код: Выделить всё
#daddy-shoutbox {
      padding: 5px;
      background: #3E5468;
      color: white;
      width: 600px;
      font-family: Arial,Helvetica,sans-serif;
      font-size: 11px;
    }
    .shoutbox-list {
      border-bottom: 1px solid #627C98;
     
      padding: 5px;
      display: none;
    }
    #daddy-shoutbox-list {
      text-align: left;
      margin: 0px auto;
    }
    #daddy-shoutbox-form {
      text-align: left;
     
    }
    .shoutbox-list-time {
      color: #8DA2B4;
    }
    .shoutbox-list-nick {
      margin-left: 5px;
      font-weight: bold;
    }
    .shoutbox-list-message {
      margin-left: 5px;
    }



после заходим в директорию темы (templates/ваша тема/) и там есть файл chat.html с коекаким кодом но мы стираем тот код и вместо него ставим:
Код: Выделить всё
<!-- INCLUDE overall_header.html -->

<div id="daddy-shoutbox">
    <div id="daddy-shoutbox-list"></div>
    <br />
    <center><form id="daddy-shoutbox-form" action="shoutbox/daddy-shoutbox.php?action=add&nick={CHAT_NICK}" method="post">
    Say: <input type="text" name="message" size="60" />
    <input type="submit" value="Submit" />
    <span id="daddy-shoutbox-response"></span>
    </form></center>
  </div>
  </center>
 
  <script type="text/javascript">
        var count = 0;
        var files = 'shoutbox/';
        var lastTime = 0;
       
        function prepare(response) {
          var d = new Date();
          count++;
          d.setTime(response.time*1000);
          var mytime = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
          var string = '<div class="shoutbox-list" id="list-'+count+'">'
              + '<span class="shoutbox-list-time">'+mytime+'</span>'
              + '<span class="shoutbox-list-nick">'+response.nickname+':</span>'
              + '<span class="shoutbox-list-message">'+response.message+'</span>'
              +'</div>';
         
          return string;
        }
       
        function success(response, status)  {
          if(status == 'success') {
            lastTime = response.time;
            $('#daddy-shoutbox-response').html('<img src="'+files+'images/accept.png" />');
            $('#daddy-shoutbox-list').append(prepare(response));
            $('input[@name=message]').attr('value', '').focus();
            $('#list-'+count).fadeIn('slow');
            timeoutID = setTimeout(refresh, 3000);
          }
        }
       
        function validate(formData, jqForm, options) {
          for (var i=0; i < formData.length; i++) {
              if (!formData[i].value) {
                  alert('Please fill in all the fields');
                  $('input[@name='+formData[i].name+']').css('background', 'red');
                  return false;
              }
          }
          $('#daddy-shoutbox-response').html('<img src="'+files+'images/loader.gif" />');
          clearTimeout(timeoutID);
        }

        function refresh() {
          $.getJSON(files+"daddy-shoutbox.php?action=view&time="+lastTime, function(json) {
            if(json.length) {
              for(i=0; i < json.length; i++) {
                $('#daddy-shoutbox-list').append(prepare(json[i]));
                $('#list-' + count).fadeIn('slow');
              }
              var j = i-1;
              lastTime = json[j].time;
            }
            //alert(lastTime);
          });
          timeoutID = setTimeout(refresh, 3000);
        }
       
        // wait for the DOM to be loaded
        $(document).ready(function() {
            var options = {
              dataType:       'json',
              beforeSubmit:   validate,
              success:        success
            };
            $('#daddy-shoutbox-form').ajaxForm(options);
            timeoutID = setTimeout(refresh, 100);
        });
  </script>
<!-- INCLUDE overall_footer.html -->


потом открываем файл overeall_header.html и после:
Код: Выделить всё
<title>{PAGE_TITLE}</title>

ставим:
Код: Выделить всё
<link rel="stylesheet" href="chat.css" type="text/css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>

У меня не работает! Кто нить подскажите! :o
Аватара пользователя
simiys
 
Сообщения: 120
Зарегистрирован: 20 мар 2008, 14:57
Адрес трекера: http://coolnarod.7sk.ru/

Re: Ajax Chat v1

Сообщение Nafania » 04 авг 2008, 19:53

sider писал(а):
Nafania писал(а): :D http://www.pjirc.com/main.php


А можно поподробнее как его правильно установить используя наши каналы в irc, и желательно chat.php просто в 3 версии его нет. Помоги пожалуйста очень нужно, вещь действительно хорошая.

chat.php
Код: Выделить всё
<?php
$tracker_root_path = './';
require($tracker_root_path . 'include/config.php');
@include ($tracker_root_path . 'include/overall_header.php');
@include ($tracker_root_path . 'include/overall_footer.php');
$userdata = session_pagestart($user_ip);
init_userprefs($userdata);
loggedinorreturn();

setcookie($config['cookie_name'] . '_cgiircnick', $userdata['name'], time() + 63072000000, $config['cookie_path'], $config['cookie_domain'], $config['cookie_secure']);

$template->assign_vars(array(
   'USERDATA_NAME' => $userdata['name'])
);
stdhead($lang['chat']);
$template->set_filenames(array(
        'body' => 'chat.html')
);
stdfoot();
?>


chat.html
Код: Выделить всё
<!-- INCLUDE overall_header.html -->

<applet code="IRCApplet.class" codebase="{TRACKER_URL}/pjirc/" archive="irc.jar,pixx.jar" width="640" height="600">
<param name="CABINETS" value="irc.cab,securedirc.cab,pjirc/pixx.cab">

<param name="nick" value="{USERDATA_NAME}">
<param name="alternatenick" value="{USERDATA_NAME}???">
<param name="name" value="SZ User">
<param name="host" value="irc.p2p-network.net">
<param name="gui" value="pixx">
<param name="quitmessage" value="Streamzone forever!">
<param name="asl" value="true">
<param name="command1" value="/join #streamzone">
<param name="coding" value="3">
<param name="language" value="russian">
<param name="languageencoding" value="windows-1251">

<param name="style:bitmapsmileys" value="true">
<param name="style:smiley1" value=":) {TRACKER_URL}/pjirc/img/sourire.gif">
<param name="style:smiley2" value=":-) {TRACKER_URL}/pjirc/img/sourire.gif">
<param name="style:smiley3" value=":-D {TRACKER_URL}/pjirc/img/content.gif">
<param name="style:smiley4" value=":d {TRACKER_URL}/pjirc/img/content.gif">
<param name="style:smiley5" value=":-O {TRACKER_URL}/pjirc/img/OH-2.gif">
<param name="style:smiley6" value=":o {TRACKER_URL}/pjirc/img/OH-1.gif">
<param name="style:smiley7" value=":-P {TRACKER_URL}/pjirc/img/langue.gif">
<param name="style:smiley8" value=":p {TRACKER_URL}/pjirc/img/langue.gif">
<param name="style:smiley9" value=";-) {TRACKER_URL}/pjirc/img/clin-oeuil.gif">
<param name="style:smiley10" value=";) {TRACKER_URL}/pjirc/img/clin-oeuil.gif">
<param name="style:smiley11" value=":-( {TRACKER_URL}/pjirc/img/triste.gif">
<param name="style:smiley12" value=":( {TRACKER_URL}/pjirc/img/triste.gif">
<param name="style:smiley13" value=":-| {TRACKER_URL}/pjirc/img/OH-3.gif">
<param name="style:smiley14" value=":| {TRACKER_URL}/pjirc/img/OH-3.gif">
<param name="style:smiley15" value=":'( {TRACKER_URL}/pjirc/img/pleure.gif">
<param name="style:smiley16" value=":$ {TRACKER_URL}/pjirc/img/rouge.gif">
<param name="style:smiley17" value=":-$ {TRACKER_URL}/pjirc/img/rouge.gif">
<param name="style:smiley18" value="(H) {TRACKER_URL}/pjirc/img/cool.gif">
<param name="style:smiley19" value="(h) {TRACKER_URL}/pjirc/img/cool.gif">
<param name="style:smiley20" value=":-@ {TRACKER_URL}/pjirc/img/enerve1.gif">
<param name="style:smiley21" value=":@ {TRACKER_URL}/pjirc/img/enerve2.gif">
<param name="style:smiley22" value=":-S {TRACKER_URL}/pjirc/img/roll-eyes.gif">
<param name="style:smiley23" value=":s {TRACKER_URL}/pjirc/img/roll-eyes.gif">
<param name="style:floatingasl" value="true">

<param name="pixx:highlight" value="true">
<param name="pixx:highlightnick" value="true">

</applet>

<!-- INCLUDE overall_footer.html -->


pjirc качаем с офф сайта и кладем в папку с трекером прям как есть, то есть в папке с трекером появляется папка pjirc в chat.html исправляем строки
Код: Выделить всё
<param name="host" value="irc.p2p-network.net">
<param name="quitmessage" value="Streamzone forever!">
<param name="command1" value="/join #streamzone">

на свои, то есть указываем адрес сервера, сообщение при выходе и команду при заходе на сервер (в моем случае это автоджоин на канал)
Аватара пользователя
Nafania
Администратор
 
Сообщения: 1207
Зарегистрирован: 30 июн 2007, 16:10

Re: Ajax Chat v1

Сообщение sider » 04 авг 2008, 22:39

Все понял спасибо огромное, все пошло.
Аватара пользователя
sider
 
Сообщения: 22
Зарегистрирован: 14 июл 2007, 17:53
Адрес трекера: http://torrentzone.ru

Re: Ajax Chat v1

Сообщение Hedin » 10 авг 2008, 18:17

NycuDR, вопрос с отображением русских букв не решил?
Hedin
 
Сообщения: 105
Зарегистрирован: 10 фев 2008, 16:15

Re: Ajax Chat v1

Сообщение simiys » 12 авг 2008, 21:19

Вот чё пишет когда нажимаю отправить
/** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_SLICE', 1); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_STR', 2); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_ARR', 3); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_OBJ', 4); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_CMT', 5); /** * Behavior switch for Services_JSON::decode() */ define('SERVICES_JSON_LOOSE_TYPE', 16); /** * Behavior switch for Services_JSON::decode() */ define('
Тут всё не помещаеться!
Аватара пользователя
simiys
 
Сообщения: 120
Зарегистрирован: 20 мар 2008, 14:57
Адрес трекера: http://coolnarod.7sk.ru/

След.

Вернуться в Готовые модификации

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 0

cron