Add "statistics" controller

This commit is contained in:
Dmitriy Simushev 2014-05-16 08:28:25 +00:00
parent 797fc7a3c0
commit 3e01b98388
7 changed files with 324 additions and 230 deletions

View File

@ -0,0 +1,190 @@
<?php
/*
* Copyright 2005-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Mibew\Controller;
use Mibew\Http\Exception\BadRequestException;
use Mibew\Settings;
use Symfony\Component\HttpFoundation\Request;
/**
* Display all statistics-related pages
*/
class StatisticsController extends AbstractController
{
const TYPE_BY_DATE = 'by-date';
const TYPE_BY_PAGE = 'by-page';
const TYPE_BY_OPERATOR = 'by-operator';
/**
* Generates content for "statistics" route.
*
* @param Request $request
* @return string Rendered page content
*/
public function indexAction(Request $request)
{
$operator = $request->attributes->get('_operator');
$statistics_type = $request->attributes->get('type');
setlocale(LC_TIME, getstring("time.locale"));
$page = array();
$page['operator'] = get_operator_name($operator);
$page['availableDays'] = range(1, 31);
$page['availableMonth'] = get_month_selection(
time() - 400 * 24 * 60 * 60,
time() + 50 * 24 * 60 * 60
);
$page['showresults'] = false;
$page['type'] = $statistics_type;
$page['showbydate'] = ($statistics_type == self::TYPE_BY_DATE);
$page['showbyagent'] = ($statistics_type == self::TYPE_BY_OPERATOR);
$page['showbypage'] = ($statistics_type == self::TYPE_BY_PAGE);
$page['pageDescription'] = getlocal2(
'statistics.description.full',
array(
date_to_text(Settings::get('_last_cron_run')),
cron_get_uri(Settings::get('cron_key')),
)
);
$page['show_invitations_info'] = (bool) Settings::get('enabletracking');
$page['errors'] = array();
// Get and validate time interval
$time_interval = $this->extractTimeInterval($request);
$start = $time_interval['start'];
$end = $time_interval['end'];
if ($start > $end) {
$page['errors'][] = getlocal('statistics.wrong.dates');
}
$page = array_merge(
$page,
set_form_date($start, 'start'),
set_form_date($end - 24 * 60 * 60, 'end')
);
// Get statistics info
if ($statistics_type == self::TYPE_BY_DATE) {
$statistics = get_by_date_statistics($start, $end);
$page['reportByDate'] = $statistics['records'];
$page['reportByDateTotal'] = $statistics['total'];
} elseif ($statistics_type == self::TYPE_BY_OPERATOR) {
$page['reportByAgent'] = get_by_operator_statistics($start, $end);
} elseif ($statistics_type == self::TYPE_BY_PAGE) {
$page['reportByPage'] = get_by_page_statistics($start, $end);
}
$page['showresults'] = count($page['errors']) == 0;
$page['title'] = getlocal("statistics.title");
$page['menuid'] = "statistics";
$page = array_merge($page, prepare_menu($operator));
$page['tabs'] = $this->buildTabs($request);
return $this->render('statistics', $page);
}
/**
* Builds list of the statistics tabs.
*
* @param Request $request Current request.
* @return array Tabs list. The keys of the array are tabs titles and the
* values are tabs URLs.
*/
protected function buildTabs(Request $request)
{
$tabs = array();
$args = $request->query->all();
$type = $request->attributes->get('type');
$tabs[getlocal('report.bydate.title')] = $type != self::TYPE_BY_DATE
? $this->generateUrl('statistics', ($args + array('type' => self::TYPE_BY_DATE)))
: '';
$tabs[getlocal('report.byoperator.title')] = $type != self::TYPE_BY_OPERATOR
? $this->generateUrl('statistics', ($args + array('type' => self::TYPE_BY_OPERATOR)))
: '';
if (Settings::get('enabletracking')) {
$tabs[getlocal('report.bypage.title')] = $type != self::TYPE_BY_PAGE
? $this->generateUrl('statistics', ($args + array('type' => self::TYPE_BY_PAGE)))
: '';
}
return $tabs;
}
/**
* Extracts start and end timestamps from the interval related with the
* request.
*
* @param Request $request Incoming request
* @return array Associative array with the following keys:
* - "start": int, timestamp for beginning of the interval.
* - "end": int, timestamp for ending of the interval.
*/
protected function extractTimeInterval(Request $request)
{
if ($request->query->has('startday')) {
// The request contains info about interval.
$start_day = $request->query->get('startday');
$start_month = $request->query->get('startmonth');
$end_day = $request->query->get('endday');
$end_month = $request->query->get('endmonth');
// Check if all necessary info is specified.
$bad_request = !preg_match("/^\d+$/", $start_day)
|| !preg_match("/^\d{2}.\d{2}$/", $start_month)
|| !preg_match("/^\d+$/", $end_day)
|| !preg_match("/^\d{2}.\d{2}$/", $end_month);
if ($bad_request) {
throw new BadRequestException();
}
return array(
'start' => get_form_date($start_day, $start_month),
'end' => get_form_date($end_day, $end_month) + 24 * 60 * 60,
);
}
// The request does not contain info about interval. Use defaults.
$curr = getdate(time());
if ($curr['mday'] < 7) {
// Use previous month if it is the first week of the month
if ($curr['mon'] == 1) {
$month = 12;
$year = $curr['year'] - 1;
} else {
$month = $curr['mon'] - 1;
$year = $curr['year'];
}
return array(
'start' => mktime(0, 0, 0, $month, 1, $year),
'end' => mktime(0, 0, 0, $month, date('t', $start), $year) + 24 * 60 * 60,
);
}
// Use the current month
return array(
'start' => mktime(0, 0, 0, $curr['mon'], 1, $curr['year']),
'end' => time() + 24 * 60 * 60,
);
}
}

View File

@ -44,6 +44,15 @@ password_recovery_reset:
defaults: defaults:
_controller: Mibew\Controller\PasswordRecoveryController::resetAction _controller: Mibew\Controller\PasswordRecoveryController::resetAction
statistics:
path: /operator/statistics/{type}
defaults:
type: "by-date"
_controller: Mibew\Controller\StatisticsController::indexAction
_access_check: Mibew\AccessControl\Check\LoggedInCheck
requirements:
type: by-date|by-operator|by-page
updates: updates:
path: /operator/updates path: /operator/updates
defaults: defaults:

View File

@ -20,44 +20,139 @@ use Mibew\Database;
use Mibew\Settings; use Mibew\Settings;
use Mibew\Thread; use Mibew\Thread;
function get_statistics_query($type) /**
* Loads statistics about system usage aggregated by dates for the time between
* $start and $end timestamps.
*
* @param int $start Timestamp for beginning of the interval of interest.
* @param int $end Timestamp for ending of the interval of interest.
* @return array Associative array with the following keys:
* - "records": array of associative arrays, set of statistics records
* - "total": associative array, aggregated statistics for the interval of
* interest.
*/
function get_by_date_statistics($start, $end)
{ {
$query = $_SERVER['QUERY_STRING']; $db = Database::getInstance();
if (!empty($query)) {
$query = '?' . $query;
$query = preg_replace("/\?type=\w+\&/", "?", $query);
$query = preg_replace("/(\?|\&)type=\w+/", "", $query);
}
$query .= strstr($query, "?") ? "&type=$type" : "?type=$type";
return $query; // Get statistics records aggregated by date
$records = $db->query(
("SELECT DATE(FROM_UNIXTIME(date)) AS date, "
. "threads, "
. "missedthreads, "
. "sentinvitations, "
. "acceptedinvitations, "
. "rejectedinvitations, "
. "ignoredinvitations, "
. "operatormessages AS agents, "
. "usermessages AS users, "
. "averagewaitingtime AS avgwaitingtime, "
. "averagechattime AS avgchattime "
. "FROM {chatthreadstatistics} s "
. "WHERE s.date >= :start "
. "AND s.date < :end "
. "GROUP BY DATE(FROM_UNIXTIME(date)) "
. "ORDER BY s.date DESC"),
array(
':start' => $start,
':end' => $end,
),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
// Get statistics aggregated for all accessed interval
$total = $db->query(
("SELECT DATE(FROM_UNIXTIME(date)) AS date, "
. "SUM(threads) AS threads, "
. "SUM(missedthreads) AS missedthreads, "
. "SUM(sentinvitations) AS sentinvitations, "
. "SUM(acceptedinvitations) AS acceptedinvitations, "
. "SUM(rejectedinvitations) AS rejectedinvitations, "
. "SUM(ignoredinvitations) AS ignoredinvitations, "
. "SUM(operatormessages) AS agents, "
. "SUM(usermessages) AS users, "
. "ROUND(SUM(averagewaitingtime * s.threads) / SUM(s.threads),1) AS avgwaitingtime, "
. "ROUND(SUM(averagechattime * s.threads) / SUM(s.threads),1) AS avgchattime "
. "FROM {chatthreadstatistics} s "
. "WHERE s.date >= :start "
. "AND s.date < :end"),
array(
':start' => $start,
':end' => $end,
),
array('return_rows' => Database::RETURN_ONE_ROW)
);
return array(
'records' => $records,
'total' => $total,
);
} }
/** /**
* Builds list of the statistics tabs. The keys of the resulting array are * Loads statistics about operators for the time between $start and $end
* tabs titles and the values are tabs URLs. * timestamps.
* *
* @param int $active Number of the active tab. The count starts from 0. * @param int $start Timestamp for beginning of the interval of interest.
* @return array Tabs list * @param int $end Timestamp for ending of the interval of interest.
* @return array Set of statistics records
*/ */
function setup_statistics_tabs($active) function get_by_operator_statistics($start, $end)
{ {
$tabs = array( $db = Database::getInstance();
getlocal("report.bydate.title") => ($active != 0 $result = $db->query(
? (MIBEW_WEB_ROOT . "/operator/statistics.php" . get_statistics_query('bydate')) ("SELECT o.vclocalename AS name, "
: ""), . "SUM(s.threads) AS threads, "
getlocal("report.byoperator.title") => ($active != 1 . "SUM(s.messages) AS msgs, "
? (MIBEW_WEB_ROOT . "/operator/statistics.php" . get_statistics_query('byagent')) . "ROUND( "
: "") . "SUM(s.averagelength * s.messages) / SUM(s.messages), "
. "1) AS avglen, "
. "SUM(sentinvitations) AS sentinvitations, "
. "SUM(acceptedinvitations) AS acceptedinvitations, "
. "SUM(rejectedinvitations) AS rejectedinvitations, "
. "SUM(ignoredinvitations) AS ignoredinvitations "
. "FROM {chatoperatorstatistics} s, {chatoperator} o "
. "WHERE s.operatorid = o.operatorid "
. "AND s.date >= :start "
. "AND s.date < :end "
. "GROUP BY s.operatorid"),
array(
':start' => $start,
':end' => $end,
),
array('return_rows' => Database::RETURN_ALL_ROWS)
); );
if (Settings::get('enabletracking')) { return $result;
$tabs[getlocal("report.bypage.title")] = ($active != 2 }
? (MIBEW_WEB_ROOT . "/operator/statistics.php" . get_statistics_query('bypage'))
: "");
}
return $tabs; /**
* Loads statistics about pages for the time between $start and $end timestamps.
*
* @param int $start Timestamp for beginning of the interval of interest.
* @param int $end Timestamp for ending of the interval of interest.
* @return array Set of statistics records
*/
function get_by_page_statistics($start, $end)
{
$db = Database::getInstance();
$result = $db->query(
("SELECT SUM(visits) as visittimes, "
. "address, "
. "SUM(chats) as chattimes, "
. "SUM(sentinvitations) AS sentinvitations, "
. "SUM(acceptedinvitations) AS acceptedinvitations, "
. "SUM(rejectedinvitations) AS rejectedinvitations, "
. "SUM(ignoredinvitations) AS ignoredinvitations "
. "FROM {visitedpagestatistics} "
. "WHERE date >= :start "
. "AND date < :end "
. "GROUP BY address"),
array(':start' => $start, ':end' => $end),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
return $result;
} }
/** /**

View File

@ -1,200 +0,0 @@
<?php
/*
* Copyright 2005-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Import namespaces and classes of the core
use Mibew\Database;
use Mibew\Settings;
use Mibew\Style\PageStyle;
// Initialize libraries
require_once(dirname(dirname(__FILE__)) . '/libs/init.php');
$operator = check_login();
force_password($operator);
setlocale(LC_TIME, getstring("time.locale"));
$page = array();
$page['operator'] = get_operator_name($operator);
$page['availableDays'] = range(1, 31);
$page['availableMonth'] = get_month_selection(time() - 400 * 24 * 60 * 60, time() + 50 * 24 * 60 * 60);
$page['showresults'] = false;
$statistics_type = verify_param("type", "/^(bydate|byagent|bypage)$/", "bydate");
$page['type'] = $statistics_type;
$page['showbydate'] = ($statistics_type == 'bydate');
$page['showbyagent'] = ($statistics_type == 'byagent');
$page['showbypage'] = ($statistics_type == 'bypage');
$page['pageDescription'] = getlocal2(
"statistics.description.full",
array(
date_to_text(Settings::get('_last_cron_run')),
cron_get_uri(Settings::get('cron_key')),
)
);
$page['show_invitations_info'] = (bool) Settings::get('enabletracking');
$page['errors'] = array();
if (isset($_GET['startday'])) {
$start_day = verify_param("startday", "/^\d+$/");
$start_month = verify_param("startmonth", "/^\d{2}.\d{2}$/");
$end_day = verify_param("endday", "/^\d+$/");
$end_month = verify_param("endmonth", "/^\d{2}.\d{2}$/");
$start = get_form_date($start_day, $start_month);
$end = get_form_date($end_day, $end_month) + 24 * 60 * 60;
} else {
$curr = getdate(time());
if ($curr['mday'] < 7) {
// previous month
if ($curr['mon'] == 1) {
$month = 12;
$year = $curr['year'] - 1;
} else {
$month = $curr['mon'] - 1;
$year = $curr['year'];
}
$start = mktime(0, 0, 0, $month, 1, $year);
$end = mktime(0, 0, 0, $month, date("t", $start), $year) + 24 * 60 * 60;
} else {
$start = mktime(0, 0, 0, $curr['mon'], 1, $curr['year']);
$end = time() + 24 * 60 * 60;
}
}
$page = array_merge(
$page,
set_form_date($start, "start"),
set_form_date($end - 24 * 60 * 60, "end")
);
if ($start > $end) {
$page['errors'][] = getlocal("statistics.wrong.dates");
}
$active_tab = 0;
$db = Database::getInstance();
if ($statistics_type == 'bydate') {
$page['reportByDate'] = $db->query(
("SELECT DATE(FROM_UNIXTIME(date)) AS date, "
. "threads, "
. "missedthreads, "
. "sentinvitations, "
. "acceptedinvitations, "
. "rejectedinvitations, "
. "ignoredinvitations, "
. "operatormessages AS agents, "
. "usermessages AS users, "
. "averagewaitingtime AS avgwaitingtime, "
. "averagechattime AS avgchattime "
. "FROM {chatthreadstatistics} s "
. "WHERE s.date >= :start "
. "AND s.date < :end "
. "GROUP BY DATE(FROM_UNIXTIME(date)) "
. "ORDER BY s.date DESC"),
array(
':start' => $start,
':end' => $end,
),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$page['reportByDateTotal'] = $db->query(
("SELECT DATE(FROM_UNIXTIME(date)) AS date, "
. "SUM(threads) AS threads, "
. "SUM(missedthreads) AS missedthreads, "
. "SUM(sentinvitations) AS sentinvitations, "
. "SUM(acceptedinvitations) AS acceptedinvitations, "
. "SUM(rejectedinvitations) AS rejectedinvitations, "
. "SUM(ignoredinvitations) AS ignoredinvitations, "
. "SUM(operatormessages) AS agents, "
. "SUM(usermessages) AS users, "
. "ROUND(SUM(averagewaitingtime * s.threads) / SUM(s.threads),1) AS avgwaitingtime, "
. "ROUND(SUM(averagechattime * s.threads) / SUM(s.threads),1) AS avgchattime "
. "FROM {chatthreadstatistics} s "
. "WHERE s.date >= :start "
. "AND s.date < :end"),
array(
':start' => $start,
':end' => $end,
),
array('return_rows' => Database::RETURN_ONE_ROW)
);
$active_tab = 0;
} elseif ($statistics_type == 'byagent') {
$page['reportByAgent'] = $db->query(
("SELECT o.vclocalename AS name, "
. "SUM(s.threads) AS threads, "
. "SUM(s.messages) AS msgs, "
. "ROUND( "
. "SUM(s.averagelength * s.messages) / SUM(s.messages), "
. "1) AS avglen, "
. "SUM(sentinvitations) AS sentinvitations, "
. "SUM(acceptedinvitations) AS acceptedinvitations, "
. "SUM(rejectedinvitations) AS rejectedinvitations, "
. "SUM(ignoredinvitations) AS ignoredinvitations "
. "FROM {chatoperatorstatistics} s, {chatoperator} o "
. "WHERE s.operatorid = o.operatorid "
. "AND s.date >= :start "
. "AND s.date < :end "
. "GROUP BY s.operatorid"),
array(
':start' => $start,
':end' => $end,
),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
// We need to pass operator name through "to_page" function because we
// cannot do it in a template.
// TODO: Remove this block when "to_page" function will be removed.
foreach ($page['reportByAgent'] as &$row) {
$row['name'] = $row['name'];
}
unset($row);
$active_tab = 1;
} elseif ($statistics_type == 'bypage') {
$page['reportByPage'] = $db->query(
("SELECT SUM(visits) as visittimes, "
. "address, "
. "SUM(chats) as chattimes, "
. "SUM(sentinvitations) AS sentinvitations, "
. "SUM(acceptedinvitations) AS acceptedinvitations, "
. "SUM(rejectedinvitations) AS rejectedinvitations, "
. "SUM(ignoredinvitations) AS ignoredinvitations "
. "FROM {visitedpagestatistics} "
. "WHERE date >= :start "
. "AND date < :end "
. "GROUP BY address"),
array(':start' => $start, ':end' => $end),
array('return_rows' => Database::RETURN_ALL_ROWS)
);
$active_tab = 2;
}
$page['showresults'] = count($page['errors']) == 0;
$page['title'] = getlocal("statistics.title");
$page['menuid'] = "statistics";
$page = array_merge($page, prepare_menu($operator));
$page['tabs'] = setup_statistics_tabs($active_tab);
$page_style = new PageStyle(PageStyle::getCurrentStyle());
$page_style->render('statistics', $page);

View File

@ -16,7 +16,7 @@
<li{{#ifEqual menuid "users"}} class="active"{{/ifEqual}}><a href="{{mibewRoot}}/operator/users">{{l10n "topMenu.users"}}</a> <span class="small">(<a class="inner" href="{{mibewRoot}}/operator/users?nomenu">{{l10n "topMenu.users.nomenu"}}</a>)</span></li> <li{{#ifEqual menuid "users"}} class="active"{{/ifEqual}}><a href="{{mibewRoot}}/operator/users">{{l10n "topMenu.users"}}</a> <span class="small">(<a class="inner" href="{{mibewRoot}}/operator/users?nomenu">{{l10n "topMenu.users.nomenu"}}</a>)</span></li>
<li{{#ifEqual menuid "history"}} class="active"{{/ifEqual}}><a href="{{mibewRoot}}/operator/history">{{l10n "page_analysis.search.title"}}</a></li> <li{{#ifEqual menuid "history"}} class="active"{{/ifEqual}}><a href="{{mibewRoot}}/operator/history">{{l10n "page_analysis.search.title"}}</a></li>
{{#if showstat}} {{#if showstat}}
<li{{#ifEqual menuid "statistics"}} class="active"{{/ifEqual}}><a href="{{mibewRoot}}/operator/statistics.php">{{l10n "statistics.title"}}</a></li> <li{{#ifEqual menuid "statistics"}} class="active"{{/ifEqual}}><a href="{{mibewRoot}}/operator/statistics">{{l10n "statistics.title"}}</a></li>
{{/if}} {{/if}}
{{#if showban}} {{#if showban}}
<li{{#ifEqual menuid "blocked"}} class="active"{{/ifEqual}}><a href="{{mibewRoot}}/operator/blocked.php">{{l10n "menu.blocked"}}</a></li> <li{{#ifEqual menuid "blocked"}} class="active"{{/ifEqual}}><a href="{{mibewRoot}}/operator/blocked.php">{{l10n "menu.blocked"}}</a></li>

View File

@ -50,7 +50,7 @@
<div class="dashitem"> <div class="dashitem">
<div class="dashitem-content"> <div class="dashitem-content">
<img src="{{stylePath}}/images/dash/stat.gif" alt=""/> <img src="{{stylePath}}/images/dash/stat.gif" alt=""/>
<a href="{{mibewRoot}}/operator/statistics.php"> <a href="{{mibewRoot}}/operator/statistics">
{{l10n "statistics.title"}} {{l10n "statistics.title"}}
</a> </a>
{{l10n "statistics.description"}} {{l10n "statistics.description"}}

View File

@ -9,7 +9,7 @@
{{> _errors}} {{> _errors}}
<form name="statisticsForm" method="get" action="{{mibewRoot}}/operator/statistics.php"> <form name="statisticsForm" method="get" action="{{mibewRoot}}/operator/statistics">
<input type="hidden" name="type" value="{{type}}" /> <input type="hidden" name="type" value="{{type}}" />
{{> _tabs}} {{> _tabs}}