Commit e5347e53 authored by Vadim's avatar Vadim

Version 2.1

1.Обновление счетчков онлайн посетителей каждые 3 сек. 2. неразрывные пробелы в данных на экране 3. Запрет вывода на экран счетчиков для постов-ссылок на внешние ресурсы
parent 8043811b
......@@ -3,7 +3,7 @@
Plugin Name: Bg Az-Counter
Plugin URI: https://bogaiskov.ru
Description: Подсчет количества посещений страниц на базе stat.azbyka.ru
Version: 2.0.2
Version: 2.1
Author: VBog
Author URI: https://bogaiskov.ru
License: GPL2
......@@ -37,7 +37,8 @@
if ( !defined('ABSPATH') ) {
die( 'Sorry, you are not allowed to access this page directly.' );
}
define('BG_COUNTER_VERSION', '2.0.2');
define('BG_COUNTER_VERSION', '2.1');
define('BG_COUNTER_LOG', dirname(__FILE__ ).'/bg_counter.log');
define('BG_COUNTER_STAT_COUNTERS','https://stat.azbyka.ru/counters');
define('BG_COUNTER_STAT_RATING','https://stat.azbyka.ru/rating');
......@@ -49,6 +50,7 @@ define('BG_COUNTER_STAT_SCORELIST','https://stat.azbyka.ru/scores-list');
define('BG_COUNTER_STAT_SET','https://stat.azbyka.ru/set-counter');
define('BG_COUNTER_STAT_SET_RATINGS','https://stat.azbyka.ru/set-rating');
define('BG_COUNTER_REALTIME_VIEW','wss://stat.azbyka.ru/realtime-view');
define('BG_COUNTER_REALTIME_UPDATES','wss://stat.azbyka.ru/updates');
$upload_dir = wp_upload_dir();
define('BG_COUNTER_ARCHIVE_COUNTER',str_replace(ABSPATH, '', $upload_dir['basedir']).'/bg_az_counter.json');
define('BG_COUNTER_ARCHIVE_RATING',str_replace(ABSPATH, '', $upload_dir['basedir']).'/bg_az_rating.json');
......@@ -102,6 +104,7 @@ function bg_counter_enqueue_frontend_scripts () {
'rateurl' => BG_COUNTER_STAT_RATE, // Всегда 'https://stat.azbyka.ru/rate'
'scoreurl' => BG_COUNTER_STAT_SCORE, // Всегда 'https://stat.azbyka.ru/item-score'
'websocket' => BG_COUNTER_REALTIME_VIEW, // Всегда 'wss://stat.azbyka.ru/realtime-view'
'updatesocket' => BG_COUNTER_REALTIME_UPDATES, // Всегда 'wss://stat.azbyka.ru/updates'
'project' => $project, // Имя текущего проекта, например, '/propovedi'
'type' => $type, // Пока только 'post' или пусто
'ID' => $postID, // ID поста
......
......@@ -144,6 +144,7 @@ function setAllCounts ($request) {
и кол-ва читающих пост пользователей
******************************************************************************************/
function bg_az_counter_views ($type=null, $id=null, $now=null) {
global $project;
if (is_single() || is_page()) {
if (is_null($id)) {
......@@ -158,6 +159,21 @@ function bg_az_counter_views ($type=null, $id=null, $now=null) {
$option = get_option('bg_counter_options');
$now = $option['now'];
}
$link = get_permalink($id);
// Получить имя проекта по ссылке
if (wp_parse_url( $link, PHP_URL_HOST ) == 'azbyka.ru') {
$proj = wp_parse_url( dirname($link), PHP_URL_PATH );
if (!$proj) $proj = '/main'; // Главный сайт
$proj = '/project'.$proj;
} else {
$proj = dirname($link);
$proj = wp_parse_url( $proj, PHP_URL_HOST ).wp_parse_url( $proj, PHP_URL_PATH );
$proj = preg_replace('#[\.\/\\\\]#i', '_', $proj) ;
$proj = '/project/'.$proj;
}
if ($project != $proj) $id = null; // Заглушка для ссылок на другие проекты
if (get_post_meta( $id, 'link', true )) $id = null;
if (!is_null($type) && !is_null($id)) {
$views = '<i title="Просмотры страницы" class="fa fa-eye"></i> <span class="bg-az-counter-views"></span>';
$users = ' <i title="Сейчас читают страницу" class="fa fa-user-o"></i> <span class="bg-az-counter-now"></span>';
......@@ -203,11 +219,11 @@ function bg_counter_top_posts_shortcode( $atts ) {
function bg_counter_number_format ($num) {
$num = floatval ($num);
if ($num > 1000000000.0) {
$num = round($num/1000000000.0, 1)." млрд.";
$num = round($num/1000000000.0, 1)."&nbsp;млрд.";
} elseif ($num > 1000000.0) {
$num = round($num/1000000.0, 1)." млн.";
$num = round($num/1000000.0, 1)."&nbsp;млн.";
} elseif ($num > 10000.0) {
$num = round($num/1000.0, 1)." тыс.";
$num = round($num/1000.0, 1)."&nbsp;тыс.";
} else {
$num = number_format($num, 0, ',', '&nbsp;');
}
......
......@@ -89,8 +89,7 @@ echo <<<HTML
<meta content="{$score}" itemprop="ratingValue">
<meta content="{$votes}" itemprop="ratingCount">
(<span id="bg_counter_votes">{$votes}</span> <span id="bg_counter_votes_txt">{$txt_votes}</span>:
<span id="bg_counter_score" data-voted="{$alreadyVoted}">{$score}</span> из <span id="bg_counter_rating_max">5</span>)
(<span id="bg_counter_votes">{$votes}</span>&nbsp;<span id="bg_counter_votes_txt">{$txt_votes}</span>:&nbsp;<span id="bg_counter_score" data-voted="{$alreadyVoted}">{$score}</span>&nbsp;из&nbsp;<span id="bg_counter_rating_max">5</span>)
</span></div>
<div id="bg_counter_popup_help"></div>
</div>
......@@ -148,18 +147,26 @@ function getPostRating ($limit, $offset=0, $number=false) {
if ($number) $quote = '<ol class="bg-az-top-posts">'. PHP_EOL;
else $quote = '<ul class="bg-az-top-posts">'. PHP_EOL;
foreach ($response->data as $p) {
if ($p->type!='post') continue;
if ($p->type!='post') {
error_log( PHP_EOL .date("Y-m-d H:i:s ", time())." SCORES-LIST. Неверный тип:\n".$p->type, 3, BG_COUNTER_LOG );
continue;
}
$id = intval($p->id);
$votes = intval($p->votes);
$votes = intval($p->votes);
if (!$id) continue;
if (!$id) {
error_log( PHP_EOL .date("Y-m-d H:i:s ", time())." SCORES-LIST. Неверный ID:\n".$p->id, 3, BG_COUNTER_LOG );
continue;
}
$post = get_post($id);
if (!$post) continue;
if (!$post) {
error_log( PHP_EOL .date("Y-m-d H:i:s ", time())." SCORES-LIST. Нет записи: \n".$p->id, 3, BG_COUNTER_LOG );
continue;
}
$title = $post->post_title;
$link = '<a href="'. get_permalink($post).'" title="'.$title.'" data-ID="'.$p->id.'" data-type="'.$p->type.'" data-score="'.$p->score.'" data-status="'.$post->post_status.'">'.$title.'</a>';
$txt_votes = bg_counter_txt_votes($votes);
$txt_score = $votes.' '.$txt_votes.': '.number_format((float)$p->score, 1, ',', '').' из 5';
$quote .= '<li>'.$link.' - <span class="bg-az-count">'.$txt_score.'</span></li>'. PHP_EOL;
$txt_score = $votes.'&nbsp;'.$txt_votes.':&nbsp;'.number_format((float)$p->score, 1, ',', '&nbsp;').'&nbsp;из&nbsp;5';
$quote .= '<li>'.$link.' -&nbsp;<span class="bg-az-count">'.$txt_score.'</span></li>'. PHP_EOL;
}
if ($number) $quote .= '</ol>'. PHP_EOL;
else $quote .= '</ul>'. PHP_EOL;
......
......@@ -9,11 +9,96 @@ jQuery( document ).ready(function() {
// используем вызов:
var socket = new ReconnectingWebSocket(request);
socket.onopen = function() {
if (bg_counter.debug) console.log(" Соединение установлено. "+request);
if (bg_counter.debug) console.log(" Соединение установлено: "+request);
GetAllCounters();
};
// Обработка ошибок
if (bg_counter.debug) {
socket.onerror = function(error) {
console.log("Ошибка " + error.message);
};
socket.onclose = function(event) {
if (event.wasClean) {
console.log('Соединение закрыто чисто: '+request);
} else {
console.log('Обрыв соединения: '+request);
}
console.log('Код: ' + event.code + ' причина: ' + event.reason);
};
}
} else GetAllCounters();
/*********************************************************************************
Просомтр счетчиков читающих в реальном времени.
Подключаемся к /updates/ после подключения webscoket будет ожидать
массив из путей счётчиков:
["/project/test", "/project/test/author/1"]
Теперь webscoket каждые 3 секунды будет присылать обновления по этим счетчиками
в формате:
{
"/project:test": 12,
"/project:test/author:1": 6
}
Поменять список отслеживаемых счетчиков можно повторно отправив массив и путей.
**********************************************************************************/
// Массив из путей счётчиков
var data = new Array();
var i = 0;
jQuery('span.bg-az-counter').each (function () {
var el = jQuery(this);
var type = el.attr('data-type');
var id = el.attr('data-ID');
if (!type || !id) var path = bg_counter.project;
else var path = bg_counter.project+"/"+type+"/"+id;
data[i] = path;
i++;
});
var json = JSON.stringify(data);
var request = bg_counter.updatesocket;
// Создаем сокет
var updatesocket = new ReconnectingWebSocket(request);
// Отправляем данные, как только сокет будет подключен
updatesocket.onopen = function() {
if (bg_counter.debug) console.log(" Соединение установлено: "+request);
updatesocket.send(json);
};
// Слушаем сокет
updatesocket.onmessage = function(e) {
if (bg_counter.debug) console.log(" Пришло сообщение: "+e.data);
var online = JSON.parse(e.data);
jQuery('span.bg-az-counter').each (function () {
var el = jQuery(this);
var type = el.attr('data-type');
var id = el.attr('data-ID');
if (!type || !id) var path = bg_counter.project;
else var path = bg_counter.project+"/"+type+"/"+id;
for (var key in online) {
if(path == key) {
el.find('span.bg-az-counter-now').text(online[key]);
}
}
});
};
// Обработка ошибок
if (bg_counter.debug) {
updatesocket.onerror = function(error) {
console.log("Ошибка " + error.message);
};
updatesocket.onclose = function(event) {
if (event.wasClean) {
console.log('Соединение закрыто чисто: '+request);
} else {
console.log('Обрыв соединения: '+request);
}
console.log('Код: ' + event.code + ' причина: ' + event.reason);
};
}
});
/*********************************************************************************
POST /counters/<path>
......@@ -45,7 +130,7 @@ function SendOnce(type, id) {
xhr.open("POST", request, true);
if (bg_counter.debug) console.log('POST REQUEST: '+request);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText) {
var response = JSON.parse(xhr.responseText);
if (response.success) {
......@@ -94,7 +179,7 @@ function GetAllCounters() {
var xhr = new XMLHttpRequest();
xhr.open("GET", request, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText) {
var response = JSON.parse(xhr.responseText);
if (response.success) {
......@@ -153,13 +238,13 @@ function bg_counter_number_format (num) {
num = parseFloat (num);
if (num > 1000000000.0) {
num = num/1000000000;
num = num.toFixed(1)+" млрд.";
num = num.toFixed(1)+"\xa0млрд.";
} else if (num > 1000000.0) {
num = num/1000000;
num = num.toFixed(1)+" млн.";
num = num.toFixed(1)+"\xa0млн.";
} else if (num > 10000.0) {
num = num/1000;
num = num.toFixed(1)+" тыс.";
num = num.toFixed(1)+"\xa0тыс.";
} else {
num = addDelimiter(num);
}
......
......@@ -92,7 +92,7 @@ function getRate(type, id) {
xhr.open("GET", request, true);
if (bg_counter.debug) console.log('GET REQUEST: '+request);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText) {
var response = JSON.parse(xhr.responseText);
if (response.success) {
......@@ -153,7 +153,7 @@ function sendRate(type, id, number) {
xhr.open("POST", request, true);
if (bg_counter.debug) console.log('POST REQUEST: '+request);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText) {
var response = JSON.parse(xhr.responseText);
if (response.success) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment