adding a FOURTH Debian Package : alternc-awstats

This commit is contained in:
Axel ROGER 2012-08-30 12:50:19 +00:00
parent 1af9bcd89b
commit c1e59f6e9a
27 changed files with 2536 additions and 0 deletions

24
.gitattributes vendored
View File

@ -13,6 +13,25 @@ aide/index.sgml -text
aide/sommaire.sgml -text
aide/stats.sgml -text
aide/test.sgml -text
awstats/Makefile -text
awstats/alternc-awstats -text
awstats/awstats.cache.php -text
awstats/awstats.sql -text
awstats/awstats.template.conf -text
awstats/awstats_alternc.png -text
awstats/bureau/admin/aws_add.php -text
awstats/bureau/admin/aws_del.php -text
awstats/bureau/admin/aws_doadd.php -text
awstats/bureau/admin/aws_doedit.php -text
awstats/bureau/admin/aws_edit.php -text
awstats/bureau/admin/aws_list.php -text
awstats/bureau/admin/aws_pass.php -text
awstats/bureau/admin/aws_useradd.php -text
awstats/bureau/admin/aws_userdel.php -text
awstats/bureau/admin/aws_users.php -text
awstats/bureau/admin/menu_aws.php -text
awstats/bureau/class/m_aws.php -text
awstats/logresolvemerge.pl -text
bureau/admin/about.php -text
bureau/admin/adm_add.php -text
bureau/admin/adm_authip_whitelist.php -text
@ -372,6 +391,11 @@ bureau/locales/pt_BR/LC_MESSAGES/messages.po -text
debian/.svnignore -text
debian/NEWS -text
debian/README.Debian -text
debian/alternc-awstats.dirs -text
debian/alternc-awstats.lintian-override -text
debian/alternc-awstats.postinst -text
debian/alternc-awstats.postrm -text
debian/alternc-awstats.preinst -text
debian/alternc-slave.config -text
debian/alternc-slave.dirs -text
debian/alternc-slave.install -text

28
awstats/Makefile Executable file
View File

@ -0,0 +1,28 @@
# ----------------------------------------------------------------------
# LICENSE
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# To read the license please visit http://www.gnu.org/copyleft/gpl.html
# ----------------------------------------------------------------------
# Purpose of file: Install the files of alternc-awstats packages
# ----------------------------------------------------------------------
install:
install -m 0644 -g root -o root alterncawstats.conf $(DESTDIR)/etc/alternc/
install -m 0755 -g root -o root logresolvemerge.pl $(DESTDIR)/usr/lib/alternc/
install -m 0644 -g www-data -o www-data awstats_alternc.png $(DESTDIR)/usr/share/awstats/icon/other/
install -m 0755 -g www-data -o www-data alternc-awstats $(DESTDIR)/usr/lib/alternc/
install -m 0755 -g www-data -o www-data awstats.cache.php $(DESTDIR)/usr/lib/alternc/
install -m 0644 awstats.sql $(DESTDIR)/usr/share/alternc/
install -m 0644 -g www-data -o www-data awstats.template.conf $(DESTDIR)/etc/alternc/templates/awstats/
install -m 0644 -g www-data -o www-data awstats.alternc.generic.conf $(DESTDIR)/etc/alternc/
#install -m 0444 lintian-override $(DESTDIR)/usr/share/lintian/overrides/alternc-awstats

62
awstats/alternc-awstats Executable file
View File

@ -0,0 +1,62 @@
#!/bin/bash
# Appelé seul, lance les stats AWStats du jour.
# Appelé avec "all" lance les stats avec tous les fichiers .gz situés dans /var/log/apache
# Appelé avec un nom de domaine en paramètre, rescanne tous les fichiers .gz pour ce domaine uniquement.
# Include some usefull functions
. /usr/lib/alternc/functions.sh
# Regenerate the awstat etc cache files :
if [ -x ./awstats.cache.php ]
then
./awstats.cache.php
fi
# FIXME : set this var in local.sh
LOG_DIR="/var/alternc/logs"
CACHEDIR="/var/cache/awstats" # Dans la sarge par defaut les données awstats sont stockées dans /var/lib/awstats ...
mkdir -p $CACHEDIR
function searchdomain {
U_ID=$(mysql_query "SELECT uid FROM aws WHERE hostname='$1'" | grep -v "^uid")
U_LOGIN=$(mysql_query "SELECT login FROM membres WHERE uid='$U_ID'" |grep -v "^login")
DOM_DIR="$LOG_DIR/$U_ID-$U_LOGIN"
echo $(find -P "$DOM_DIR" -mindepth 1 -maxdepth 2 -type f -iname "*.log" -print0 | xargs -0)
}
function dostatgz {
read DOM
while [ "$DOM" ]
do
LOGAPACHE=$(searchdomain $DOM)
echo "processing $DOM (for access files in $LOGAPACHE )"
/usr/lib/cgi-bin/awstats.pl -config=$DOM -update -LogFile="/usr/lib/alternc/logresolvemerge.pl $LOGAPACHE* |"
read DOM
done
}
function dostat {
read DOM
while [ "$DOM" ]
do
echo "processing $DOM"
LOGAPACHE=$(searchdomain $DOM)
/usr/lib/cgi-bin/awstats.pl -config=$DOM -LogFile="/usr/lib/alternc/logresolvemerge.pl $LOGAPACHE | "
read DOM
done
}
if [ -z "$1" ]
then
mysql_query "SELECT hostname FROM aws" |grep -v "^hostname" | dostat
else
if [ "$1" = "all" ]
then
mysql_query "SELECT hostname FROM aws" |grep -v "^hostname" | dostatgz
else
echo "$1" | dostatgz
fi
fi

14
awstats/awstats.cache.php Executable file
View File

@ -0,0 +1,14 @@
#!/usr/bin/php -q
<?php
include("/var/alternc/bureau/class/config_nochk.php");
$db->query("SELECT id,hostname FROM aws;");
while ($db->next_record()) {
$d[]=$db->Record;
}
foreach ($d as $r) {
$aws->_createconf($r[0],1);
}
?>

28
awstats/awstats.sql Normal file
View File

@ -0,0 +1,28 @@
# --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `aws` (
`id` int(10) unsigned NOT NULL auto_increment,
`uid` int(10) unsigned NOT NULL default '0',
`hostname` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`)
) TYPE=MyISAM COMMENT='Statistiques web par Awstats';
# --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `aws_users` (
`uid` int(10) unsigned NOT NULL,
`login` varchar(128) NOT NULL,
`pass` varchar(38) NOT NULL,
PRIMARY KEY (`login`),
INDEX (`uid`)
) COMMENT = 'Comptes pouvant accéder aux stats awstats.';
# --------------------------------------------------------
CREATE TABLE IF NOT EXISTS `aws_access` (
`id` int(10) unsigned NOT NULL,
`uid` int(10) unsigned NOT NULL,
`login` varchar(128) NOT NULL,
INDEX (`id`)
) COMMENT = 'Qui peut accéder aux stats awstats ';
ALTER TABLE `aws` ADD `public` INT(1) unsigned NOT NULL DEFAULT '1';
ALTER TABLE `aws` ADD `hostaliases` TEXT ;

View File

@ -0,0 +1,9 @@
Include "/etc/alternc/awstats.alternc.generic.conf"
Include "/etc/awstats/awstats.conf.local"
Include "/etc/alternc/awstats.log.alternc.conf"
SiteDomain="%%HOSTNAME%%"
HostAliases="%%HOSTALIASES%%"
DirData="/var/cache/awstats/%%HOSTNAME%%"
AllowAccessFromWebToFollowingAuthenticatedUsers="admin %%USERS%%"
AllowAccessFromWebToAuthenticatedUsersOnly=%%PUBLIC%%
AllowFullYearView=3

BIN
awstats/awstats_alternc.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

View File

@ -0,0 +1,107 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Purpose of file: Create a new awstat statistic set.
----------------------------------------------------------------------
*/
require_once("../class/config.php");
$fields = array (
"id" => array ("request", "integer", 0),
);
getFields($fields);
if (!$id && !$quota->cancreate("aws")) {
$error=_("You cannot add any new statistics, your quota is over.");
}
include_once("head.php");
?>
<h3><?php if (!$id) { __("New Statistics"); } else { __("Edit Statistics"); } ?></h3>
<hr id="topbar"/>
<br />
<?php
if (isset($error) && $error) {
echo "<p class=\"error\">$error</p></body></html>";
}
?>
<form method="post" action="<?php if (!$id) echo "aws_doadd.php"; else echo "aws_doedit.php"; ?>" id="main" name="main">
<table class="tedit">
<tr><th><input type="hidden" name="id" value="<?php echo $id ?>" />
<label for="hostname"><?php __("Domain name"); ?></label></th><td>
<?php if (!$id) { ?>
<select class="inl" name="hostname" id="hostname"><?php $aws->select_host_list($hostname); ?></select>
<?php } else { ?>
<code><?php echo $hostname; ?></code>
<?php } ?>
</td></tr>
<tr><th><?php __("Hostaliases"); ?></th><td>
<?php // TODO : put them on 2 columns (at least)
$hl=$aws->host_list();
$hatab=$aws->get_hostaliases($id);
foreach ($hl as $ho) {
echo "<input type=\"checkbox\" name=\"hostaliases[]\" id=\"ha_$ho\" value=\"$ho\"";
if (in_array($ho,explode(" ",$hatab[0]))) echo " checked=\"checked\"";
echo " /><label for=\"ha_$ho\">$ho</label><br />\n";
}
?>
</td></tr>
<tr><th><?php __("Allowed Users"); ?></th><td>
<?php
// List the users (and check allowed ones) :
$r=$aws->list_allowed_login($id);
if (is_array($r)) {
?>
<?php
foreach($r as $v) {
echo "<input type=\"checkbox\" name=\"awsusers[]\" class=\"int\" id=\"u_".htmlentities($v["login"])."\" value=\"".htmlentities($v["login"])."\" ";
if ($v["selected"]) echo " checked=\"checked\"";
echo "><label for=\"u_".htmlentities($v["login"])."\">".$v["login"]."</label><br />\n";
}
?>
<?php
} else {
__("No users currently defined, you must create login with the 'Manage allowed users' accounts' menu.");
}
?></td></tr>
<tr><th><?php __("View public"); ?></th><td>
<select class="inl" name="public" id="public">
<?php
// Public ?
$pub=$aws->get_view_public($id);
if($pub == 0) {
echo "<option selected=\"selected\" value=\"0\">"._("Yes")."</option><option value=\"1\">"._("No")."</option>";
} else {
echo "<option selected=\"selected\" value=\"1\">"._("No")."</option><option value=\"0\">"._("Yes")."</option>";
}
?>
</select>
</td></tr>
<tr class="trbtn"><td colspan="2">
<input type="submit" class="inb" name="submit" value="<?php if (!$id) __("Create those statistics"); else __("Edit those statistics"); ?>" />
<input type="button" class="inb" name="cancel" value="<?php __("Cancel"); ?>" onclick="document.location='aws_list.php'"/>
</td></tr>
</table>
</form>
<?php include_once("foot.php"); ?>

View File

@ -0,0 +1,51 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Purpose of file: Delete requested awstats statistics.
----------------------------------------------------------------------
*/
require_once("../class/config.php");
$error="";
// On parcours les POST_VARS et on repere les del_.
reset($_POST);
$found=false;
while (list($key,$val)=each($_POST)) {
if (substr($key,0,4)=="del_") {
// Effacement du jeu de stats $val
$r=$aws->delete_stats($val);
$found=true;
if (!$r) {
$error.=$err->errstr()."<br />";
} else {
$error.=sprintf(_("The statistics %s has been successfully deleted"),$r)."<br />";
}
}
}
if (!$found) {
$error.=_("Please check the statistics set you want to delete");
}
include("aws_list.php");
exit();
?>

View File

@ -0,0 +1,45 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Purpose of file:
----------------------------------------------------------------------
*/
require_once("../class/config.php");
$fields = array (
"hostname" => array ("post", "string", ""),
"awsusers" => array ("post", "array", ""),
"hostaliases" => array ("post", "array", ""),
"public" => array ("post", "integer", "")
);
getFields($fields);
$r=$aws->add_stats($hostname,$awsusers,$hostaliases,$public);
if (!$r) {
$error=$err->errstr();
include("aws_add.php");
exit();
} else {
$error=_("The statistics has been successfully created");
include("aws_list.php");
exit();
}
?>

View File

@ -0,0 +1,53 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Purpose of file: Edit a statistic set
----------------------------------------------------------------------
*/
require_once("../class/config.php");
$fields = array (
"id" => array ("request", "integer", 0),
"awsusers" => array ("post", "array", ""),
"hostaliases" => array ("post", "array", ""),
"public" => array ("post", "integer", "")
);
getFields($fields);
if (!$id) {
$error=_("No Statistics selected!");
} else {
$ha ="";
foreach($hostaliases as $ho)
$ha .= "$ho ";
$r=$aws->put_stats_details($id,$awsusers,$ha,$public);
if (!$r) {
$error=$err->errstr();
include("aws_edit.php");
exit();
} else {
$error=_("The Statistics has been successfully changed");
include("aws_list.php");
exit();
}
}
?>

View File

@ -0,0 +1,50 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Purpose of file: Edit a statistic set
----------------------------------------------------------------------
*/
require_once("../class/config.php");
$fields = array (
"id" => array ("request", "integer", 0),
);
getFields($fields);
if (!$id) {
$error=_("No Statistics selected!");
} else {
$r=$aws->get_stats_details($id);
if (!$r) {
$error=$err->errstr();
}
}
$id=$r["id"];
$hostname=$r["hostname"];
$awsusers=$r["users"];
$hostaliases=$r["hostaliases"];
$public=$r["public"];
include("aws_add.php");
exit();
?>

View File

@ -0,0 +1,83 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Purpose of file: List awstats statistics and manage them.
----------------------------------------------------------------------
*/
require_once("../class/config.php");
include_once("head.php");
$nosta=false;
if (!$r=$aws->get_list()) {
$error=$err->errstr();
$nosta=true;
}
?>
<h3><?php __("Statistics List"); ?></h3>
<hr id="topbar"/>
<br />
<p>
<span class="ina"><a href="aws_users.php"><?php __("Manage allowed users' accounts"); ?></a></span><br /><br />
<?php
if ($quota->cancreate("aws")) { ?>
<span class="ina"><a href="aws_add.php"><?php __("Create new Statistics"); ?></a></span><br />
<?php }
?>
</p>
<?php
if (isset($error) && $error) {
echo "<p class=\"error\">$error</p>";
}
if (!$nosta) {
?>
<form method="post" action="aws_del.php">
<table cellspacing="0" cellpadding="4">
<tr><th colspan="2"><?php __("Action"); ?></th><th><?php __("Domain name"); ?></th><th><?php __("Allowed Users"); ?></th><th><?php __("View the statistics"); ?></th></tr>
<?php
reset($r);
$col=1;
while (list($key,$val)=each($r))
{
$col=3-$col;
?>
<tr class="lst<?php echo $col; ?>">
<td><input type="checkbox" class="inc" id="del_<?php echo $val["id"]; ?>" name="del_<?php echo $val["id"]; ?>" value="<?php echo $val["id"]; ?>" /></td>
<td><div class="ina"><a href="aws_edit.php?id=<?php echo $val["id"] ?>"><img src="images/edit.png" alt="<?php __("Edit"); ?>" title="<?php __("Edit"); ?>" /><?php __("Edit"); ?></a></div></td>
<td><label for="del_<?php echo $val["id"]; ?>"><?php echo $val["hostname"] ?></label></td>
<td><?php echo $val["users"] ?></td>
<td><div class="ina"><img src="images/stat.png" alt="<?php __("View the statistics"); ?>" /><a href="/cgi-bin/awstats.pl?config=<?php echo $val["hostname"]; ?>"><?php __("View the statistics"); ?></a></div></td>
</tr>
<?php
}
?>
<tr><td colspan="5"><input type="submit" class="inb" name="submit" value="<?php __("Delete the checked Statistics"); ?>" /></td></tr>
</table>
</form>
<?php
}
?>
<?php include_once("foot.php"); ?>

View File

@ -0,0 +1,79 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Purpose of file: Change a user's password.
----------------------------------------------------------------------
*/
require_once("../class/config.php");
$fields = array (
"login" => array ("request", "string", ""),
"pass" => array ("request", "string", ""),
);
getFields($fields);
if (!$aws->login_exists($login)) {
$error=$err->errstr();
include("aws_users.php");
exit();
}
if ($pass) {
if (!$aws->change_pass($login,$pass)) {
$error=$err->errstr();
} else {
include("aws_users.php");
exit();
}
}
include_once("head.php");
?>
<h3><?php __("Change a user's password"); ?></h3>
<?php
if (isset($error) && $error) {
?>
<p class="error"><?php echo $error ?></p>
<?php } ?>
<form method="post" action="aws_pass.php" name="main" id="main">
<table class="tedit">
<tr><th>
<?php __("Username"); ?></th><td>
<code><?php echo $login; ?></code> <input type="hidden" name="login" value="<?php echo $login; ?>" />
</td></tr>
<tr><th><label for="pass"><?php __("New Password"); ?></label></th><td><input type="password" class="int" name="pass" id="pass" value="<?php echo $pass; ?>" size="20" maxlength="64" /></td></tr>
<tr class="trbtn"><td colspan="2">
<input type="submit" class="inb" name="submit" value="<?php __("Change this user's password"); ?>" />
<input type="button" class="inb" name="cancel" value="<?php __("Cancel"); ?>" onclick="document.location='aws_users.php'"/>
</td></tr>
</table>
</form>
<script type="text/javascript">
document.forms['main'].pass.focus();
document.forms['main'].setAttribute('autocomplete', 'off');
</script>
<?php include_once("foot.php"); ?>

View File

@ -0,0 +1,44 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Purpose of file: Create a new awstat account
----------------------------------------------------------------------
*/
require_once("../class/config.php");
$fields = array (
"prefixe" => array ("request", "string", ""),
"login" => array ("request", "string", ""),
"pass" => array ("request", "string", ""),
);
getFields($fields);
$r=$aws->add_login($prefixe.(($login)?"_":"").$login,$pass);
if (!$r) {
$error=$err->errstr();
} else {
$error=_("The Awstat account has been successfully created");
}
include("aws_users.php");
exit();
?>

View File

@ -0,0 +1,45 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Purpose of file: Delete awstat accounts
----------------------------------------------------------------------
*/
require_once("../class/config.php");
$error="";
// On parcours les POST_VARS et on repere les del_.
reset($_POST);
while (list($key,$val)=each($_POST)) {
if (substr($key,0,4)=="del_") {
// Effacement du compte ftp $val
$r=$aws->del_login($val);
if (!$r) {
$error.=$err->errstr()."<br />";
} else {
$error.=sprintf(_("The awstat account %s has been successfully deleted"),$val)."<br />";
}
}
}
include("aws_users.php");
exit();
?>

View File

@ -0,0 +1,100 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Purpose of file: List awstats accounts of the user.
----------------------------------------------------------------------
*/
require_once("../class/config.php");
include_once("head.php");
$nologin=false;
if (!$r=$aws->list_login()) {
$nologin=true;
$error=$err->errstr();
}
?>
<h3><?php __("Awstats allowed user list"); ?></h3>
<hr id="topbar"/>
<br />
<?php
if ($quota->cancreate("aws")) { ?>
<p><span class="ina"><a href="aws_add.php"><?php __("Create new Statistics"); ?></a></span></p>
<?php } ?>
<form method="post" action="aws_useradd.php" name="main">
<table class="tedit">
<tr><th>
<label for="login"><?php __("Username"); ?></label></th><td>
<select class="inl" name="prefixe"><?php $aws->select_prefix_list($prefixe); ?></select>&nbsp;<b>_</b>&nbsp;<input type="text" class="int" name="login" id="login" value="" size="20" maxlength="64" />
</td></tr>
<tr><th><label for="pass"><?php __("Password"); ?></label></th><td><input type="password" class="int" name="pass" id="pass" value="" size="20" maxlength="64" /></td></tr>
<tr class="trbtn"><td colspan="2">
<input type="submit" class="inb" name="submit" value="<?php __("Create this new awstat account"); ?>" />
<input type="button" class="inb" name="cancel" value="<?php __("Cancel"); ?>" onclick="document.location='aws_list.php'"/>
</td></tr>
</table>
</form>
<br />
<?php
if (isset($error) && $error) {
?>
<p class="error"><?php echo $error ?></p>
<?php }
if (!$nologin) {
?>
<form method="post" action="aws_userdel.php" name="main2" id="main2">
<table class="tlist">
<tr><th colspan="2"><?php __("Action"); ?></th><th><?php __("Username"); ?></th></tr>
<?php
$col=1;
foreach ($r as $val) {
$col=3-$col;
?>
<tr class="lst<?php echo $col; ?>">
<td align="center"><input type="checkbox" class="inc" id="del_<?php echo $val; ?>" name="del_<?php echo $val; ?>" value="<?php echo $val; ?>" /></td>
<td><span class="ina"><a href="aws_pass.php?login=<?php echo $val ?>"><?php __("Change password"); ?></a></span></td>
<td><label for="del_<?php echo $val; ?>"><?php echo $val ?></label></td>
</tr>
<?php
}
?>
<tr><td colspan="5"><input type="submit" name="submit" class="inb" value="<?php __("Delete checked accounts"); ?>" /></td></tr>
</table>
</form>
<?php
}
?>
<script type="text/javascript">
document.forms['main'].login.focus();
document.forms['main'].setAttribute('autocomplete', 'off');
</script>
<?php include_once("foot.php"); ?>

View File

@ -0,0 +1,40 @@
<?php
/*
$Id: menu_aws.php 2560 2009-09-08 05:31:48Z nahuel $
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2002 by the AlternC Development Team.
http://alternc.org/
----------------------------------------------------------------------
Based on:
Valentin Lacambre's web hosting softwares: http://altern.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Original Author of file:
Purpose of file:
----------------------------------------------------------------------
*/
/* ############# STATS ############# */
$q = $quota->getquota("aws");
$r = $quota->getquota("dom");
if (isset($q["t"]) && isset($r["u"]) && $q["t"] > 0 && $r["u"] > 0) {
?>
<div class="menu-box">
<div class="menu-title"><img src="images/stat.png" alt="<?php __("Web Statistics"); ?>" />&nbsp;<a href="aws_list.php"><?php __("Web Statistics"); ?></a> (<?= $q["u"]; ?>/<?= $q["t"]; ?>)</div>
</div>
<?php } ?>

View File

@ -0,0 +1,720 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Purpose of file: Gestion des statistiques web par Awstats
----------------------------------------------------------------------
*/
/**
* This class manage awstats statistic sets.
*
* Copyleft {@link http://alternc.org/ AlternC Team}
*
* @copyright AlternC-Team 2004-09-01 http://alternc.org/
*
*/
class m_aws {
/** Where are the awstats configuration files :
* @access private
*/
var $CONFDIR="/etc/awstats";
var $HTAFILE="/etc/alternc/awstats.htpasswd";
var $CACHEDIR="/var/cache/awstats";
/** Where is the template for conf files :
* @access private
*/
var $TEMPLATEFILE="/etc/alternc/templates/awstats/awstats.template.conf";
/* ----------------------------------------------------------------- */
/**
* Constructor
*/
function m_aws() {
}
/* ----------------------------------------------------------------- */
/**
* Password kind used in this class (hook for admin class)
*/
function alternc_password_policy() {
return array("aws"=>"Awstats Web Statistics");
}
/* ----------------------------------------------------------------- */
/**
* Name of the module function
*/
function alternc_module_description() {
return array("aws"=>_("The stats module allows any user to ask for statistics about his web site. Statistics are web pages generated daily based on the visits of the day before. Awstats is the soft used to produce those stats. The statistics are then protected by a login and a password."));
}
/* ----------------------------------------------------------------- */
/**
* Returns an array with all the statistics of a member.
*
* @return array Returns an indexed array of associative arrays
* like that :
* $r[0-n]["id"] = Id of the stat set
* $r[0-n]["hostname"]= domain
* $r[0-n]["users"]= list of allowed users separated with ' '
*/
function get_list() {
global $db,$err,$cuid;
$err->log("aws","get_list");
$r=array();
$db->query("SELECT id, hostname FROM aws WHERE uid='$cuid' ORDER BY hostname;");
if ($db->num_rows()) {
while ($db->next_record()) {
$r[]=array(
"id"=>$db->f("id"),
"hostname"=>$db->f("hostname"),
);
}
$t=array();
foreach ($r as $v) {
$db->query("SELECT login FROM aws_access WHERE id='".$v["id"]."';");
$u="";
while ($db->next_record()) {
$u.=$db->f("login")." ";
}
$t[]=array("id"=>$v["id"],"hostname"=>$v["hostname"],"users"=>$u);
}
return $t;
} else {
$err->raise("aws",1); // No statistics currently defined
return false;
}
}
/* ----------------------------------------------------------------- */
/**
* Return an array with the details for 1 statistic set
*
* @param integer $id ID of the set we want.
* @return array Returns an associative array as follow :
* $r["id"] = Id
* $r["hostname"]= domain
* $r["users"] = List of allowed users, separated by ' '
*/
function get_stats_details($id) {
global $db,$err,$cuid;
$err->log("aws","get_stats_details",$id);
$r=array();
$db->query("SELECT id, hostname, hostaliases, public FROM aws WHERE uid='$cuid' AND id='$id';");
if ($db->num_rows()) {
$db->next_record();
$id=$db->f("id");
$hostname=$db->f("hostname");
$hostaliases=$db->f("hostaliases");
$public=$db->f("public");
$db->query("SELECT login FROM aws_access WHERE id='$id';");
$u="";
while ($db->next_record()) {
$u.=$db->f("login")." ";
}
return array(
"id"=>$id,
"hostname"=>$hostname,
"users"=>$u,
"hostaliases"=>$hostaliases,
"public"=>$public
);
} else {
$err->raise("aws",2); // This statistic does not exist
return false;
}
}
/* ----------------------------------------------------------------- */
/** Return the list of domains / subdomains allowed for this member
*
* @return array an array of allowed domains / subdomains.
*/
function host_list() {
global $db,$err,$cuid;
$r=array();
$db->query("SELECT domaine,sub FROM sub_domaines WHERE compte='$cuid' ORDER BY domaine,sub;");
while ($db->next_record()) {
if ($db->f("sub")) {
$r[]=$db->f("sub").".".$db->f("domaine");
} else {
$r[]=$db->f("domaine");
}
}
return $r;
}
/* ----------------------------------------------------------------- */
/** Returns the list of prefixes that can be used on current account
* @return array an arry with the list of domains + the login of the account
*/
function prefix_list() {
global $db,$mem,$cuid;
$r=array();
$r[]=$mem->user["login"];
$db->query("SELECT domaine FROM domaines WHERE compte='$cuid' ORDER BY domaine;");
while ($db->next_record()) {
$r[]=$db->f("domaine");
}
return $r;
}
/* ----------------------------------------------------------------- */
/** Echoes <option> tags of all the domains hosted on the account + the login of the account
* They can be used as a root for the login that may have access to web statistics
* hosted on an account
* $current will be the selected value.
* @param string $current The default selected value
* @return boolean TRUE.
*/
function select_prefix_list($current) {
$r=$this->prefix_list();
reset($r);
while (list($key,$val)=each($r)) {
if ($current==$val) $c=" selected=\"selected\""; else $c="";
echo "<option$c>$val</option>";
}
return true;
}
/* ----------------------------------------------------------------- */
/**
* Draw options for a select html code with the list of allowed domains
* for this member.
*/
function select_host_list($current) {
$r=$this->host_list();
reset($r);
while (list($key,$val)=each($r)) {
if ($current==$val) $c=" selected=\"selected\""; else $c="";
echo "<option$c>$val</option>";
}
return true;
}
/* ----------------------------------------------------------------- */
/**
* Return the hostaliases list with an id.
*/
function get_hostaliases($id) {
global $db,$err,$cuid;
$r=array();
if ($id == NULL)
return $r;
$db->query("SELECT hostaliases FROM aws WHERE uid='$cuid' and id='$id' ORDER by hostaliases;");
while ($db->next_record()) {
$r[]=$db->f("hostaliases");
}
return $r;
}
/* ----------------------------------------------------------------- */
/**
* Edit a statistic set (change allowed user list)
* @param integer $id the stat number we change
* @param array $users the list of allowed users
*/
function put_stats_details($id,$users,$hostaliases,$public) {
global $err,$db,$cuid;
if ($c=$this->get_stats_details($id)) {
$this->delete_allowed_login($id, 1);
if (is_array($users)) {
foreach($users as $v) {
$this->allow_login($v,$id,1);
}
}
$db->query("UPDATE aws SET hostaliases='$hostaliases', public='$public' where id='$id';");
$this->_createconf($id);
$this->_createhtpasswd();
return true;
} else return false;
}
/* ----------------------------------------------------------------- */
/**
* Delete a statistic set.
* @param integer $id The statistic set ID
* @return string the domain name of the deleted statistic set, or FALSE if an error occurred
*/
function delete_stats($id) {
global $db,$err,$cuid;
$err->log("aws","delete_stats",$id);
$db->query("SELECT hostname FROM aws WHERE id='$id' and uid='$cuid';");
if (!$db->num_rows()) {
$err->raise("aws",2); // This statistic does not exist
return false;
}
$db->next_record();
$hostname=$db->f("hostname");
$this->delete_allowed_login($id,1);
$this->_delconf($hostname);
$db->query("DELETE FROM aws WHERE id='$id'");
system("rm ".$this->CACHEDIR."/$hostname/ -rf");
return $name;
}
/* ----------------------------------------------------------------- */
/**
* Create a new statistic set
* @param string $hostname The domain name
* @param $uers array the array of users that will be allowed
* @param $hostaliases array an array of host aliases
* @param $public boolean Shall this statistic set be public ?
* @return boolean TRUE if the set has been created
*/
function add_stats($hostname,$users="", $hostaliases,$public) {
global $db,$err,$quota,$mem,$cuid;
$err->log("aws","add_stats",$hostname);
$r=$this->host_list();
if (!in_array($hostname,$r) || $hostname=="") {
$err->raise("aws",3); // This hostname does not exist
return false;
}
// Parse the hostaliases array (it should contains valid domains)
if (is_array($hostaliases)) {
foreach($hostaliases as $ho) {
if (!in_array($hostname,$r) || $hostname=="") {
$err->raise("aws",3); // This hostname does not exist
return false;
}
$ha .= "$ho ";
}
}
if ($quota->cancreate("aws")) {
$db->query("INSERT INTO aws (hostname,uid,hostaliases,public) VALUES ('$hostname','$cuid','$ha','$public')");
$id=$db->lastid();
if (is_array($users)) {
foreach($users as $v) {
$this->allow_login($v,$id, 1);
}
}
$this->_createconf($id);
$this->_createhtpasswd();
mkdir($this->CACHEDIR."/".$hostname,0777);
return true;
} else {
$err->raise("aws",4); // Your stat quota is over...
return false;
}
}
/* ----------------------------------------------------------------- */
function list_login() {
global $db,$err,$cuid;
$err->log("aws","list_login");
$db->query("SELECT login FROM aws_users WHERE uid='$cuid';");
$res=array();
if (!$db->next_record()) {
$err->raise("aws",13); // No user currently defined
return false;
}
do {
$res[]=$db->f("login");
} while ($db->next_record());
return $res;
}
/* ----------------------------------------------------------------- */
function list_allowed_login($id) {
global $db,$err,$cuid;
$err->log("aws","list_allowed_login");
$db->query("SELECT u.login,a.id FROM aws_users u LEFT JOIN aws_access a ON a.id='$id' AND a.login=u.login WHERE u.uid='$cuid';");
$res=array();
if (!$db->next_record()) {
return false;
}
do {
$res[]=array("login"=>$db->f("login"),"selected"=>($db->f("id")));
} while ($db->next_record());
return $res;
}
/* ----------------------------------------------------------------- */
function get_view_public($id) {
global $db,$err,$cuid;
$db->query("SELECT public FROM aws WHERE id='$id' and uid='$cuid';");
if ($db->num_rows()) {
$db->next_record();
$pub=$db->f("public");
} else {
$pub=1;
}
return $pub;
}
/* ----------------------------------------------------------------- */
/* Check that a login exists ($exists=1) or doesn't exist ($exists=0) */
function login_exists($login,$exists=1) {
global $db,$err,$cuid;
$err->log("aws","list_login");
$db->query("SELECT login FROM aws_users WHERE uid='$cuid' AND login='$login';");
if (!$db->next_record()) {
return ($exists==0);
} else {
return ($exists==1);
}
}
/* ----------------------------------------------------------------- */
function del_login($login) {
global $db,$err,$cuid;
$err->log("aws","del_login");
if (!$this->login_exists($login,1)) {
$err->raise("aws",5); // Login does not exists
return false;
}
$db->query("DELETE FROM aws_users WHERE uid='$cuid' AND login='$login';");
$db->query("DELETE FROM aws_access WHERE uid='$cuid' AND login='$login';");
$this->_createhtpasswd();
return true;
}
/* ----------------------------------------------------------------- */
function add_login($login,$pass) {
global $db,$err,$cuid;
$err->log("aws","add_login");
if (!($login=$this->_check($login))) {
$err->raise("aws",6); // Login incorrect
return false;
}
if (!($this->login_exists($login,0))) {
$err->raise("aws",7); // Login does not exist
return false;
}
$pass=crypt($pass);
$db->query("INSERT INTO aws_users (uid,login,pass) VALUES ('$cuid','$login','$pass');");
$this->_createhtpasswd();
return true;
}
/* ----------------------------------------------------------------- */
function change_pass($login,$pass) {
global $db,$err,$cuid;
$err->log("aws","change_pass");
if (!($login=$this->_check($login))) {
$err->raise("aws",6); // Login incorrect
return false;
}
if (!($this->login_exists($login))) {
$err->raise("aws",5); // Login does not exists
return false;
}
$pass=crypt($pass);
$db->query("UPDATE aws_users SET pass='$pass' WHERE login='$login';");
$this->_createhtpasswd();
return true;
}
/* ----------------------------------------------------------------- */
function allow_login($login,$id,$noconf=0) { // allow user $login to access stats $id.
global $db,$err,$cuid;
$err->log("aws","allow_login");
if (!($login=$this->_check($login))) {
$err->raise("aws",6); // Login incorrect
return false;
}
if (!$this->login_exists($login)) {
$err->raise("aws",5); // Login does not exists
return false;
}
$db->query("SELECT id FROM aws WHERE id='$id' AND uid='$cuid'");
if (!$db->next_record()) {
$err->raise("aws",2); // The requested statistic does not exist.
return false;
}
$db->query("SELECT login FROM aws_access WHERE id='$id' AND login='$login'");
if ($db->next_record()) {
$err->raise("aws",8); // This login is already allowed for this statistics.
return false;
}
$db->query("INSERT INTO aws_access (uid,id,login) VALUES ('$cuid','$id','$login');");
if (!$noconf) {
$this->_createconf($id);
$this->_createhtpasswd();
}
return true;
}
/* ----------------------------------------------------------------- */
function delete_allowed_login($id,$noconf=0) {
global $db,$err,$cuid;
$err->log("aws","delete_allowed_login");
$db->query("SELECT id FROM aws WHERE id='$id' AND uid='$cuid'");
if (!$db->next_record()) {
$err->raise("aws",2); // The requested statistic does not exist.
return false;
}
$db->query("DELETE FROM aws_access WHERE id='$id';");
if (!$noconf) {
$this->_createconf($id);
$this->_createhtpasswd();
}
return true;
}
/* ----------------------------------------------------------------- */
function deny_login($login,$id,$noconf=0) { // deny user $login to access stats $id.
global $db,$err,$cuid;
$err->log("aws","deny_login");
if (!($login=$this->_check($login))) {
$err->raise("aws",6); // Login incorrect
return false;
}
if (!$this->login_exists($login,0)) {
$err->raise("aws",5); // Login does not exists
return false;
}
$db->query("SELECT id FROM aws WHERE id='$id' AND uid='$cuid'");
if (!$db->next_record()) {
$err->raise("aws",2); // The requested statistic does not exist.
return false;
}
$db->query("SELECT login FROM aws_access WHERE id='$id' AND login='$login'");
if (!$db->next_record()) {
$err->raise("aws",9); // This login is already denied for this statistics.
return false;
}
$db->query("DELETE FROM aws_access WHERE id='$id' AND login='$login';");
if (!$noconf) {
$this->_createconf($id);
$this->_createhtpasswd();
}
return true;
}
/* ----------------------------------------------------------------- */
function alternc_del_member() {
global $db,$err,$cuid;
$err->log("aws","del_member");
$db->query("SELECT * FROM aws WHERE uid='$cuid';");
$t=array();
while ($db->next_record()) {
$t[]=$db->f("hostname");
}
$db->query("DELETE FROM aws WHERE uid='$cuid';");
foreach ($t as $i) {
$this->_delconf($i);
}
$this->_createhtpasswd();
$db->query("DELETE FROM aws_access WHERE uid='$cuid'");
$db->query("DELETE FROM aws_users WHERE uid='$cuid';");
return true;
}
/* ----------------------------------------------------------------- */
/**
* This function is called on each class when a domain name is uninstalled
* @param string $dom the domain to uninstall
*/
function alternc_del_domain($dom) {
global $db,$err,$cuid;
$err->log("aws","alternc_del_domain",$dom);
$db=new DB_System();
$db->query("SELECT id,hostname FROM aws WHERE uid='$cuid' AND (hostname='$dom' OR hostname like '%.$dom')");
$t=array();
while ($db->next_record()) {
$t[]=array($db->f("hostname"),$db->f("id"));
}
foreach ($t as $i) {
$db->query("DELETE FROM aws WHERE uid='$cuid' AND hostname='".$i[0]."';");
$db->query("DELETE FROM aws_access WHERE uid='$cuid' AND id='".$i[1]."';");
$this->_delconf($i[0]);
}
$this->_createhtpasswd();
return true;
}
/* ----------------------------------------------------------------- */
/**
* This function is called when we are asked to compute the used quota
* for a service
* @param integer $id The userid whose quota should be computed.
*/
function hook_quota_get() {
global $db,$err,$cuid;
$err->log("aws","get_quota");
$db->query("SELECT COUNT(*) AS cnt FROM aws WHERE uid='$cuid'");
$q=Array("name"=>"aws", "description"=>_("Awstats"), "used"=>0);
if ($db->next_record()) {
$q['used']=$db->f("cnt");
}
return $q;
}
/* ----------------------------------------------------------------- */
function _check($login) {
global $err,$mem;
$login=trim($login);
$login=strtolower($login);
if ($c=strpos($login,"_")) {
$prefix=substr($login,0,$c);
$postfix=substr($login,$c+1);
} else {
$prefix=$login;
$postfix="";
}
$r=$this->prefix_list();
if (!in_array($prefix,$r)) {
$err->raise("aws",10); // prefix not allowed.
return false;
}
if (!preg_match('/^[0-9a-z_-]*$/', $postfix)){
$err->raise("aws",11); // Forbidden caracters in the postfix.
return false;
}
return $login;
}
/* ----------------------------------------------------------------- */
/** Delete the awstats configuration file for a statistic set.
* @access private
*/
function _delconf($hostname) {
global $err;
if (!preg_match('/^[._a-z0-9-]*$/', $hostname)){
$err->raise("aws",12); // Hostname is incorrect
return false;
}
@unlink($this->CONFDIR."/awstats.".$hostname.".conf");
}
/* ----------------------------------------------------------------- */
/** Create a configuration file for a statistic set.
* if nochk==1, does not check the owner of the stat set (for admin only)
* @access private
*/
function _createconf($id,$nochk=0) {
global $db,$err,$cuid;
$s=implode("",file($this->TEMPLATEFILE));
if ($nochk) {
$db->query("SELECT * FROM aws WHERE id='$id';");
} else {
$db->query("SELECT * FROM aws WHERE id='$id' AND uid='$cuid';");
}
if (!$db->num_rows()) {
$err->raise("aws",2); // This statistic does not exist
return false;
}
$db->next_record();
$hostname=$db->f("hostname");
$hostaliases=$db->f("hostaliases");
$public=$db->f("public");
$db->query("SELECT login FROM aws_access WHERE id='$id';");
$users="";
while ($db->next_record()) {
$users.=$db->f("login")." ";
}
$s=str_replace("%%HOSTNAME%%",$hostname,$s);
$s=str_replace("%%PUBLIC%%",$public,$s);
$s=str_replace("%%HOSTALIASES%%",$hostaliases,$s);
$s=str_replace("%%USERS%%",$users,$s);
$f=fopen($this->CONFDIR."/awstats.".$hostname.".conf","wb");
fputs($f,$s,strlen($s));
fclose($f);
}
/* ----------------------------------------------------------------- */
function _createhtpasswd() {
global $db;
$f=fopen($this->HTAFILE,"wb");
if ($f) {
$db->query("SELECT login,pass FROM aws_users;");
while ($db->next_record()) {
fputs($f,$db->f("login").":".$db->f("pass")."\n");
}
fclose($f);
}
}
/* ----------------------------------------------------------------- */
/**
* Exports all the aws related information for an account.
* @access private
* EXPERIMENTAL 'sid' function ;)
*/
function alternc_export() {
global $db,$err,$cuid;
$err->log("aws","export");
$str="<aws>\n";
$db->query("SELECT login,pass FROM aws_users WHERE uid='$cuid';");
while ($db->next_record()) {
$str.=" <user><login>".$db->Record["login"]."</login><pass hash=\"des\">".$db->Record["pass"]."</pass></user>\n";
}
$r=array();
$db->query("SELECT id, hostname FROM aws WHERE uid='$cuid' ORDER BY hostname;");
while ($db->next_record()) {
$r[$db->Record["id"]]=$db->Record["hostname"];
}
foreach($r as $id=>$host) {
$str.=" <domain>\n <name>".$host."</name>\n";
$db->query("SELECT login FROM aws_access WHERE id='$id';");
while ($db->next_record()) {
$str.=" <user>".$db->Record["login"]."</user>\n";
}
$str.=" </domain>\n";
}
$str.="</aws>\n";
return $str;
}
} /* CLASSE m_aws */
?>

715
awstats/logresolvemerge.pl Executable file
View File

@ -0,0 +1,715 @@
#!/usr/bin/perl
#-----------------------------------------------------------------------------
# Allows you to get one unique output log file, sorted on date,
# built from particular sources.
# This tool is part of AWStats log analyzer but can be use
# alone for any other log analyzer.
# See COPYING.TXT file about AWStats GNU General Public License.
#-----------------------------------------------------------------------------
# $Revision: 1.34 $ - $Author: eldy $ - $Date: 2005/12/04 21:10:46 $
use strict; no strict "refs";
#use diagnostics;
#-----------------------------------------------------------------------------
# Defines
#-----------------------------------------------------------------------------
# ENABLETHREAD --> COMMENT THIS BLOCK TO USE A THREADED VERSION
my $UseThread=0;
&Check_Thread_Use();
my $NbOfDNSLookupAsked = 0;
my %threadarray = ();
my %MyDNSTable = ();
my %TmpDNSLookup = ();
# ENABLETHREAD --> UNCOMMENT THIS BLOCK TO USE A THREADED VERSION
#my $UseThread=1;
#&Check_Thread_Use();
#my $NbOfDNSLookupAsked : shared = 0;
#my %threadarray : shared = ();
#my %MyDNSTable : shared = ();
#my %TmpDNSLookup : shared = ();
# ---------- Init variables --------
use vars qw/ $REVISION $VERSION /;
$REVISION='$Revision: 1.34 $'; $REVISION =~ /\s(.*)\s/; $REVISION=$1;
$VERSION="1.2 (build $REVISION)";
use vars qw/ $NBOFLINESFORBENCHMARK /;
$NBOFLINESFORBENCHMARK=8192;
use vars qw/
$DIR $PROG $Extension
$Debug $ShowSteps $AddFileNum $AddFileName
$MaxNbOfThread $DNSLookup $DNSCache $DirCgi $DirData $DNSLookupAlreadyDone
$NbOfLinesShowsteps $AFINET $QueueCursor
/;
$DIR='';
$PROG='';
$Extension='';
$Debug=0;
$ShowSteps=0;
$AddFileNum=0;
$AddFileName=0;
$MaxNbOfThread=0;
$DNSLookup=0;
$DNSCache='';
$DirCgi='';
$DirData='';
$DNSLookupAlreadyDone=0;
$NbOfLinesShowsteps=0;
$AFINET='';
# ---------- Init arrays --------
use vars qw/
@SkipDNSLookupFor
@ParamFile
/;
# ---------- Init hash arrays --------
use vars qw/
%LogFileToDo %linerecord %timerecord %corrupted
%QueueHostsToResolve %QueueRecords
/;
%LogFileToDo = %linerecord = %timerecord = %corrupted = ();
%QueueHostsToResolve = %QueueRecords = ();
# DRA2: the order of timerecords are kept here, each index in the array is the filerecordnumber, which
# DRA2: is used as the key for the other hashes
use vars qw/
@timerecordorder
/;
@timerecordorder = ();
# ---------- External Program variables ----------
# For gzip compression
my $zcat = 'zcat';
my $zcat_file = '\.gz$';
# For bz2 compression
my $bzcat = 'bzcat';
my $bzcat_file = '\.bz2$';
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
#------------------------------------------------------------------------------
# Function: Write an error message and exit
# Parameters: $message
# Input: None
# Output: None
# Return: None
#------------------------------------------------------------------------------
sub error {
print STDERR "Error: $_[0].\n";
exit 1;
}
#------------------------------------------------------------------------------
# Function: Write a debug message
# Parameters: $message
# Input: $Debug
# Output: None
# Return: None
#------------------------------------------------------------------------------
sub debug {
my $level = $_[1] || 1;
if ($Debug >= $level) {
my $debugstring = $_[0];
print "DEBUG $level - ".localtime(time())." : $debugstring\n";
}
}
#------------------------------------------------------------------------------
# Function: Write a warning message
# Parameters: $message
# Input: $Debug
# Output: None
# Return: None
#------------------------------------------------------------------------------
sub warning {
my $messagestring=shift;
if ($Debug) { debug("$messagestring",1); }
print STDERR "$messagestring\n";
}
#-----------------------------------------------------------------------------
# Function: Return 1 if string contains only ascii chars
# Input: String
# Return: 0 or 1
#-----------------------------------------------------------------------------
sub IsAscii {
my $string=shift;
if ($Debug) { debug("IsAscii($string)",5); }
if ($string =~ /^[\w\+\-\/\\\.%,;:=\"\'&?!\s]+$/) {
if ($Debug) { debug(" Yes",5); }
return 1; # Only alphanum chars (and _) or + - / \ . % , ; : = " ' & ? space \t
}
if ($Debug) { debug(" No",5); }
return 0;
}
#-----------------------------------------------------------------------------
# DRA Function: Return 1 if DNS lookup should be skipped
# Input: String
# Return: 0 or 1
#-----------------------------------------------------------------------------
sub SkipDNSLookup {
foreach my $match (@SkipDNSLookupFor) { if ($_[0] =~ /$match/i) { return 1; } }
0; # Not in @SkipDNSLookupFor
}
#-----------------------------------------------------------------------------
# Function: Function that wait for DNS lookup (can be threaded)
# Input: String
# Return: 0 or 1
#-----------------------------------------------------------------------------
sub MakeDNSLookup {
my $ipaddress=shift;
$NbOfDNSLookupAsked++;
use Socket; $AFINET=AF_INET;
my $tid=0;
$tid=$MaxNbOfThread?eval("threads->self->tid()"):0;
if ($Debug) { debug(" ***** Thread id $tid: MakeDNSlookup started (for $ipaddress)",4); }
my $lookupresult=gethostbyaddr(pack("C4",split(/\./,$ipaddress)),$AFINET); # This is very slow, may took 20 seconds
if (! $lookupresult || $lookupresult =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ || ! IsAscii($lookupresult)) {
$TmpDNSLookup{$ipaddress}='*';
}
else {
$TmpDNSLookup{$ipaddress}=$lookupresult;
}
if ($Debug) { debug(" ***** Thread id $tid: MakeDNSlookup done ($ipaddress resolved into $TmpDNSLookup{$ipaddress})",4); }
delete $threadarray{$ipaddress};
return;
}
#-----------------------------------------------------------------------------
# Function: WriteRecordsReadyInQueue
# Input: -
# Return: 0
#-----------------------------------------------------------------------------
sub WriteRecordsReadyInQueue {
my $logfilechosen=shift;
if ($Debug) { debug("Check head of queue to write records ready to flush (QueueCursor=$QueueCursor, QueueSize=".(scalar keys %QueueRecords).")",4); }
while ( $QueueHostsToResolve{$QueueCursor} && ( ($QueueHostsToResolve{$QueueCursor} eq '*') || ($MyDNSTable{$QueueHostsToResolve{$QueueCursor}}) || ($TmpDNSLookup{$QueueHostsToResolve{$QueueCursor}}) ) ) {
# $QueueCursor point to a ready record
if ($QueueHostsToResolve{$QueueCursor} eq '*') {
if ($Debug) { debug(" First elem in queue is ready. No change on it. We pull it.",4); }
}
else {
if ($MyDNSTable{$QueueHostsToResolve{$QueueCursor}}) {
if ($MyDNSTable{$QueueHostsToResolve{$QueueCursor}} ne '*') {
$QueueRecords{$QueueCursor}=~s/$QueueHostsToResolve{$QueueCursor}/$MyDNSTable{$QueueHostsToResolve{$QueueCursor}}/;
if ($Debug) { debug(" First elem in queue has been resolved (found in MyDNSTable $MyDNSTable{$QueueHostsToResolve{$QueueCursor}}). We pull it.",4); }
}
}
elsif ($TmpDNSLookup{$QueueHostsToResolve{$QueueCursor}}) {
if ($TmpDNSLookup{$QueueHostsToResolve{$QueueCursor}} ne '*') {
$QueueRecords{$QueueCursor}=~s/$QueueHostsToResolve{$QueueCursor}/$TmpDNSLookup{$QueueHostsToResolve{$QueueCursor}}/;
if ($Debug) { debug(" First elem in queue has been resolved (found in TmpDNSLookup $TmpDNSLookup{$QueueHostsToResolve{$QueueCursor}}). We pull it.",4); }
}
}
}
# Record is ready, we output it.
if ($AddFileNum) { print "$logfilechosen "; }
if ($AddFileName) { print "$LogFileToDo{$logfilechosen} "; }
print "$QueueRecords{$QueueCursor}\n";
delete $QueueRecords{$QueueCursor};
delete $QueueHostsToResolve{$QueueCursor};
$QueueCursor++;
}
return 0;
}
#-----------------------------------------------------------------------------
# Function: Check if thread are enabled or not
# Input: -
# Return: -
#-----------------------------------------------------------------------------
sub Check_Thread_Use {
if ($] >= 5.008) { for (0..@ARGV-1) { if ($ARGV[$_] =~ /^-dnslookup[:=](\d{1,2})/i) {
if ($UseThread) {
if (!eval ('require "threads.pm";')) { &error("Failed to load perl module 'threads' required for multi-threaded DNS lookup".($@?": $@":"")); }
if (!eval ('require "threads/shared.pm";')) { &error("Failed to load perl module 'threads::shared' required for multi-threaded DNS lookup".($@?": $@":"")); }
}
else { &error("Multi-thread is disabled in default version of this script.\nYou must manually edit the file '$0' to comment/uncomment all\nlines marked with 'ENABLETHREAD' string to enable multi-threading"); }
} }
}
}
#-----------------------------------------------------------------------------
# MAIN
#-----------------------------------------------------------------------------
($DIR=$0) =~ s/([^\/\\]*)$//; ($PROG=$1) =~ s/\.([^\.]*)$//; $Extension=$1;
# Get parameters (Note: $MaxNbOfThread is already known
my $cpt=1;
for (0..@ARGV-1) {
if ($ARGV[$_] =~ /^-/) {
if ($ARGV[$_] =~ /debug=(\d)/i) { $Debug=$1; }
elsif ($ARGV[$_] =~ /dnscache=/i) { $DNSLookup||=2; $DNSCache=$ARGV[$_]; $DNSCache =~ s/-dnscache=//; }
elsif ($ARGV[$_] =~ /dnslookup[:=](\d{1,2})/i) { $DNSLookup||=1; $MaxNbOfThread=$1; }
elsif ($ARGV[$_] =~ /dnslookup/i) { $DNSLookup||=1; }
elsif ($ARGV[$_] =~ /showsteps/i) { $ShowSteps=1; }
elsif ($ARGV[$_] =~ /addfilenum/i) { $AddFileNum=1; }
elsif ($ARGV[$_] =~ /addfilename/i) { $AddFileName=1; }
else { print "Unknown argument $ARGV[$_] ignored\n"; }
}
else {
push @ParamFile, $ARGV[$_];
$cpt++;
}
}
if ($Debug) { $|=1; }
if ($Debug) {
debug(ucfirst($PROG)." - $VERSION - Perl $^X $]",1);
debug("DNSLookup=$DNSLookup");
debug("DNSCache=$DNSCache");
debug("MaxNbOfThread=$MaxNbOfThread");
}
# Disallow MaxNbOfThread and Perl < 5.8
if ($] < 5.008 && $MaxNbOfThread) {
error("Multi-threaded DNS lookup is only supported with Perl 5.8 or higher (not $]). Use -dnslookup option instead");
}
# Warning, there is a memory hole in ActiveState perl version (in delete functions)
if ($^X =~ /activestate/i || $^X =~ /activeperl/i) {
# TODO Add a warning
}
if (scalar @ParamFile == 0) {
print "----- $PROG $VERSION (c) Laurent Destailleur -----\n";
print "$PROG allows you to get one unique output log file, sorted on date,\n";
print "built from particular sources:\n";
print " - It can read several input log files,\n";
print " - It can read .gz/.bz2 log files,\n";
print " - It can also makes a fast reverse DNS lookup to replace\n";
print " all IP addresses into host names in resulting log file.\n";
print "$PROG comes with ABSOLUTELY NO WARRANTY. It's a free software\n";
print "distributed with a GNU General Public License (See COPYING.txt file).\n";
print "$PROG is part of AWStats but can be used alone as a log merger\n";
print "or resolver before using any other log analyzer.\n";
print "\n";
print "Usage:\n";
print " $PROG.$Extension [options] file\n";
print " $PROG.$Extension [options] file1 ... filen\n";
print " $PROG.$Extension [options] *.*\n";
print " perl $PROG.$Extension [options] *.* > newfile\n";
print "Options:\n";
print " -dnslookup make a reverse DNS lookup on IP adresses\n";
print " -dnslookup=n same with a n parallel threads instead of serial requests\n";
print " -dnscache=file make DNS lookup from cache file first before network lookup\n";
print " -showsteps print on stderr benchmark information every $NBOFLINESFORBENCHMARK lines\n";
print " -addfilenum if used with several files, file number can be added in first\n";
print " -addfilename if used with several files, file name can be added in first\n";
print " field of output file. This can be used to add a cluster id\n";
print " when log files come from several load balanced computers.\n";
print "\n";
print "This runs $PROG in command line to open one or several\n";
print "server log files to merge them (sorted on date) and/or to make a reverse\n";
print "DNS lookup (if asked). The result log file is sent on standard output.\n";
print "Note: $PROG is not a 'sort' tool to sort one file. It's a\n";
print "software able to output sorted log records (with a reverse DNS lookup\n";
print "included or not) even if log records are dispatched in several files.\n";
print "Each of thoose files must be already independently sorted itself\n";
print "(but that is the case in all web server log files). So you can use it\n";
print "for load balanced log files or to group several old log files.\n";
print "\n";
print "Don't forget that the main goal of logresolvemerge is to send log records to\n";
print "a log analyzer in a sorted order without merging files on disk (NO NEED\n";
print "OF DISK SPACE AT ALL) and without loading files into memory (NO NEED\n";
print "OF MORE MEMORY). Choose of output records is done on the fly.\n";
print "\n";
print "So logresolvemerge is particularly usefull when you want to output several\n";
print "and/or large log files in a fast process, with no use of disk or\n";
print "more memory, and in a chronological order through a pipe (to be used by a log\n";
print "analyzer).\n";
print "\n";
print "Note: If input records are not 'exactly' sorted but 'nearly' sorted (this\n";
print "occurs with heavy servers), this is not a problem, the output will also\n";
print "be 'nearly' sorted but a few log analyzers (like AWStats) knowns how to deal\n";
print "with such logs.\n";
print "\n";
print "WARNING: If log files are old MAC text files (lines ended with CR char), you\n";
print "can't run this tool on Win or Unix platforms.\n";
print "\n";
print "WARNING: Because of important memory holes in ActiveState Perl version, use\n";
print "another Perl interpreter if you need to process large lof files.\n";
print "\n";
print "Now supports/detects:\n";
print " Automatic detection of log format\n";
print " Files can be .gz/.bz2 files if zcat/bzcat tools are available in PATH.\n";
print " Multithreaded reverse DNS lookup (several parallel requests) with Perl 5.8+.\n";
print "New versions and FAQ at http://awstats.sourceforge.net\n";
exit 0;
}
# Get current time
my $nowtime=time;
my ($nowsec,$nowmin,$nowhour,$nowday,$nowmonth,$nowyear) = localtime($nowtime);
if ($nowyear < 100) { $nowyear+=2000; } else { $nowyear+=1900; }
my $nowsmallyear=$nowyear;$nowsmallyear =~ s/^..//;
if (++$nowmonth < 10) { $nowmonth = "0$nowmonth"; }
if ($nowday < 10) { $nowday = "0$nowday"; }
if ($nowhour < 10) { $nowhour = "0$nowhour"; }
if ($nowmin < 10) { $nowmin = "0$nowmin"; }
if ($nowsec < 10) { $nowsec = "0$nowsec"; }
# Get tomorrow time (will be used to discard some record with corrupted date (future date))
my ($tomorrowsec,$tomorrowmin,$tomorrowhour,$tomorrowday,$tomorrowmonth,$tomorrowyear) = localtime($nowtime+86400);
if ($tomorrowyear < 100) { $tomorrowyear+=2000; } else { $tomorrowyear+=1900; }
my $tomorrowsmallyear=$tomorrowyear;$tomorrowsmallyear =~ s/^..//;
if (++$tomorrowmonth < 10) { $tomorrowmonth = "0$tomorrowmonth"; }
if ($tomorrowday < 10) { $tomorrowday = "0$tomorrowday"; }
if ($tomorrowhour < 10) { $tomorrowhour = "0$tomorrowhour"; }
if ($tomorrowmin < 10) { $tomorrowmin = "0$tomorrowmin"; }
if ($tomorrowsec < 10) { $tomorrowsec = "0$tomorrowsec"; }
my $timetomorrow=$tomorrowyear.$tomorrowmonth.$tomorrowday.$tomorrowhour.$tomorrowmin.$tomorrowsec;
# Init other parameters
$NBOFLINESFORBENCHMARK--;
if ($ENV{"GATEWAY_INTERFACE"}) { $DirCgi=''; }
if ($DirCgi && !($DirCgi =~ /\/$/) && !($DirCgi =~ /\\$/)) { $DirCgi .= '/'; }
if (! $DirData || $DirData eq '.') { $DirData=$DIR; } # If not defined or choosed to "." value then DirData is current dir
if (! $DirData) { $DirData='.'; } # If current dir not defined then we put it to "."
$DirData =~ s/\/$//;
#my %monthlib = ( "01","$Message[60]","02","$Message[61]","03","$Message[62]","04","$Message[63]","05","$Message[64]","06","$Message[65]","07","$Message[66]","08","$Message[67]","09","$Message[68]","10","$Message[69]","11","$Message[70]","12","$Message[71]" );
# monthnum must be in english because it's used to translate log date in apache log files which are always in english
my %monthnum = ( "Jan","01","jan","01","Feb","02","feb","02","Mar","03","mar","03","Apr","04","apr","04","May","05","may","05","Jun","06","jun","06","Jul","07","jul","07","Aug","08","aug","08","Sep","09","sep","09","Oct","10","oct","10","Nov","11","nov","11","Dec","12","dec","12" );
if ($DNSCache) {
if ($Debug) { debug("Load DNS Cache file $DNSCache",2); }
open(CACHE, "<$DNSCache") or error("Can't open cache file $DNSCache");
while (<CACHE>) {
my ($time, $ip, $name) = split;
if ($ip && $name) {
$name="$ip" if $name eq '*';
$MyDNSTable{$ip}=$name;
}
}
close CACHE;
}
#-----------------------------------------------------------------------------
# PROCESSING CURRENT LOG(s)
#-----------------------------------------------------------------------------
my $NbOfLinesRead=0;
my $NbOfLinesParsed=0;
my $logfilechosen=0;
my $starttime=time();
# Define the LogFileToDo list
$cpt=1;
foreach my $key (0..(@ParamFile-1)) {
if ($ParamFile[$key] !~ /\*/ && $ParamFile[$key] !~ /\?/) {
if ($Debug) { debug("DBG1 Log file $ParamFile[$key] is added to LogFileToDo with number $cpt."); }
# Check for supported compression
if ($ParamFile[$key] =~ /$zcat_file/) {
if ($Debug) { debug("GZIP compression detected for Log file $ParamFile[$key]."); }
# Modify the name to include the zcat command
$ParamFile[$key] = $zcat . ' ' . $ParamFile[$key] . ' |';
}
elsif ($ParamFile[$key] =~ /$bzcat_file/) {
if ($Debug) { debug("BZ2 compression detected for Log file $ParamFile[$key]."); }
# Modify the name to include the bzcat command
$ParamFile[$key] = $bzcat . ' ' . $ParamFile[$key] . ' |';
}
$LogFileToDo{$cpt}=@ParamFile[$key];
$cpt++;
}
else {
my $DirFile=$ParamFile[$key]; $DirFile =~ s/([^\/\\]*)$//;
$ParamFile[$key] = $1;
if ($DirFile eq '') { $DirFile = '.'; }
$ParamFile[$key] =~ s/\./\\\./g;
$ParamFile[$key] =~ s/\*/\.\*/g;
$ParamFile[$key] =~ s/\?/\./g;
if ($Debug) { debug("Search for file \"$ParamFile[$key]\" into \"$DirFile\""); }
opendir(DIR,"$DirFile");
my @filearray = sort readdir DIR;
close DIR;
foreach my $i (0..$#filearray) {
if ("$filearray[$i]" =~ /^$ParamFile[$key]$/ && "$filearray[$i]" ne "." && "$filearray[$i]" ne "..") {
if ($Debug) { debug("DBG2 Log file $filearray[$i] is added to LogFileToDo with number $cpt."); }
# Check for supported compression
if ($filearray[$i] =~ /$zcat_file/) {
if ($Debug) { debug("GZIP compression detected for Log file $filearray[$i]."); }
# Modify the name to include the zcat command
$LogFileToDo{$cpt}=$zcat . ' ' . "$DirFile/$filearray[$i]" . ' |';
}
elsif ($filearray[$i] =~ /$bzcat_file/) {
if ($Debug) { debug("BZ2 compression detected for Log file $filearray[$i]."); }
# Modify the name to include the bzcat command
$LogFileToDo{$cpt}=$bzcat . ' ' . "$DirFile/$filearray[$i]" . ' |';
}
else {
$LogFileToDo{$cpt}="$DirFile/$filearray[$i]";
}
$cpt++;
}
}
}
}
# If no files to process
if (scalar keys %LogFileToDo == 0) {
error("No input log file found");
}
# Open all log files
if ($Debug) { debug("Start of processing ".(scalar keys %LogFileToDo)." log file(s), $MaxNbOfThread threads max"); }
foreach my $logfilenb (keys %LogFileToDo) {
if ($Debug) { debug("Open log file number $logfilenb: \"$LogFileToDo{$logfilenb}\""); }
open("LOG$logfilenb","$LogFileToDo{$logfilenb}") || error("Couldn't open log file \"$LogFileToDo{$logfilenb}\" : $!");
binmode "LOG$logfilenb"; # To avoid pb of corrupted text log files with binary chars.
}
$QueueCursor=1;
while (1 == 1)
{
# BEGIN Read new record
# For each log file if logfilechosen is 0
# If not, we go directly to log file instead of iterating over all keys for a match
#----------------------------------------------------------------------------------
my @readlist;
if($logfilechosen == 0) {
@readlist = keys %LogFileToDo;
} else {
@readlist = ($logfilechosen);
}
foreach my $logfilenb (@readlist)
{
if ($Debug) { debug("Search next record in file number $logfilenb",3); }
# Read chosen log file until we found a record with good date or reaching end of file
while (1 == 1) {
my $LOG="LOG$logfilenb";
$_=<$LOG>; # Read new line
if (! $_) { # No more records in log file number $logfilenb
if ($Debug) { debug(" No more records in file number $logfilenb",2); }
delete $LogFileToDo{$logfilenb};
last;
}
$NbOfLinesRead++;
chomp $_; s/\r$//;
if (/^#/) { next; } # Ignore comment lines (ISS writes such comments)
if (/^!!/) { next; } # Ignore comment lines (Webstar writes such comments)
if (/^$/) { next; } # Ignore blank lines (With ISS: happens sometimes, with Apache: possible when editing log file)
$linerecord{$logfilenb}=$_;
# Check filters
#----------------------------------------------------------------------
# Split DD/Month/YYYY:HH:MM:SS or YYYY-MM-DD HH:MM:SS or MM/DD/YY\tHH:MM:SS
my $year=0; my $month=0; my $day=0; my $hour=0; my $minute=0; my $second=0;
if ($_ =~ /(\d\d\d\d)-(\d\d)-(\d\d)\s(\d\d):(\d\d):(\d\d)/) { $year=$1; $month=$2; $day=$3; $hour=$4; $minute=$5; $second=$6; }
elsif ($_ =~ /\[(\d\d)[\/:\s](\w+)[\/:\s](\d\d\d\d)[\/:\s](\d\d)[\/:\s](\d\d)[\/:\s](\d\d) /) { $year=$3; $month=$2; $day=$1; $hour=$4; $minute=$5; $second=$6; }
elsif ($_ =~ /\[\w+ (\w+) (\d\d) (\d\d)[\/:\s](\d\d)[\/:\s](\d\d) (\d\d\d\d)\]/) { $year=$6; $month=$1; $day=$2; $hour=$3; $minute=$4; $second=$5; }
if ($monthnum{$month}) { $month=$monthnum{$month}; } # Change lib month in num month if necessary
# Create $timerecord like YYYYMMDDHHMMSS
$timerecord{$logfilenb}=int("$year$month$day$hour$minute$second");
if ($timerecord{$logfilenb}<10000000000000) {
if ($Debug) { debug(" This record is corrupted (no date found)",3); }
$corrupted{$logfilenb}++;
next;
}
if ($Debug) { debug(" This is next record for file $logfilenb : timerecord=$timerecord{$logfilenb}",3); }
# Sort and insert into timerecordorder, oldest at end/back of array
# At the beginning, timerecordorder is empty. Then beceause the first pass is
# a loop on each file to read each first line, the timerecordorder size is
# number of input files.
# After, each new loop, read only one new line, so timerecordorder size increase
# by one but decrease just after by the pop command later.
my $inserted=0;
for(my $c=$#timerecordorder; $c>=0 ; $c--) {
if($timerecord{$logfilenb} <= $timerecord{$timerecordorder[$c]})
{
# Is older or equal than index at $c, add after
$timerecordorder[$c + 1]=$logfilenb;
$inserted = 1;
last;
} else {
$timerecordorder[$c + 1]=$timerecordorder[$c];
}
}
if(! $inserted) {
$timerecordorder[0] = $logfilenb;
}
last;
}
}
# END Read new lines for each log file. After this, following var are filled
# $timerecord{$logfilenb}
# @timerecordorder array
# We choose which record of which log file to process
if ($Debug) { debug("Choose which record of which log file to process",3); }
$logfilechosen=pop(@timerecordorder);
if(!defined($logfilechosen)) { last; } # No more record to process
# Record is chosen
if ($Debug) { debug(" We choosed to qualify record of file number $logfilechosen",3); }
if ($Debug) { debug(" Record is $linerecord{$logfilechosen}",3); }
# Record is approved. We found a new line to parse in file number $logfilechosen
#-------------------------------------------------------------------------------
$NbOfLinesParsed++;
if ($ShowSteps) {
if ((++$NbOfLinesShowsteps & $NBOFLINESFORBENCHMARK) == 0) {
my $delay=(time()-$starttime)||1;
print STDERR "$NbOfLinesParsed lines processed (".(1000*$delay)." ms, ".int($NbOfLinesShowsteps/$delay)." lines/seconds)\n";
}
}
# Do DNS lookup
#--------------------
my $Host='';
my $ip=0;
if ($DNSLookup) { # DNS lookup is 1 or 2
if ($linerecord{$logfilechosen} =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/) { $ip=4; $Host=$1; } # IPv4
elsif ($linerecord{$logfilechosen} =~ /([0-9A-F]*:)/i) { $ip=6; $Host=$1; } # IPv6
if ($ip) {
# Check in static DNS cache file
if ($MyDNSTable{$Host}) {
if ($Debug) { debug(" DNS lookup asked for $Host and found in static DNS cache file: $MyDNSTable{$Host}",4); }
}
elsif ($DNSLookup==1) {
# Check in session cache (dynamic DNS cache file + session DNS cache)
if (! $threadarray{$Host} && ! $TmpDNSLookup{$Host}) {
if (@SkipDNSLookupFor && &SkipDNSLookup($Host)) {
$TmpDNSLookup{$Host}='*';
if ($Debug) { debug(" No need of reverse DNS lookup for $Host, skipped at user request.",4); }
}
else {
if ($ip == 4) {
# Create or not a new thread
if ($MaxNbOfThread) {
if (! $threadarray{$Host}) { # No thread already launched for $Host
while ((scalar keys %threadarray) >= $MaxNbOfThread) {
if ($Debug) { debug(" $MaxNbOfThread thread running reached, so we wait",4); }
sleep 1;
}
$threadarray{$Host}=1; # Semaphore to tell thread for $Host is active
# my $t = new Thread \&MakeDNSLookup, $Host;
my $t = threads->create(sub { MakeDNSLookup($Host) });
if (! $t) { error("Failed to create new thread"); }
if ($Debug) { debug(" Reverse DNS lookup for $Host queued in thread ".$t->tid,4); }
$t->detach(); # We don't need to keep return code
}
else {
if ($Debug) { debug(" Reverse DNS lookup for $Host already queued in a thread"); }
}
# Here, this is the only way, $TmpDNSLookup{$Host} can be not defined
} else {
&MakeDNSLookup($Host);
if ($Debug) { debug(" Reverse DNS lookup for $Host done: $TmpDNSLookup{$Host}",4); }
}
}
elsif ($ip == 6) {
$TmpDNSLookup{$Host}='*';
if ($Debug) { debug(" Reverse DNS lookup for $Host not available for IPv6",4); }
}
}
} else {
if ($Debug) { debug(" Reverse DNS lookup already queued or done for $Host: $TmpDNSLookup{$Host}",4); }
}
}
else {
if ($Debug) { debug(" DNS lookup by static DNS cache file asked for $Host but not found.",4); }
}
}
else {
if ($Debug) { debug(" DNS lookup asked for $Host but this is not an IP address.",4); }
$DNSLookupAlreadyDone=$LogFileToDo{$logfilechosen};
}
}
else {
if ($linerecord{$logfilechosen} =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/) { $ip=4; $Host=$1; } # IPv4
elsif ($linerecord{$logfilechosen} =~ /([0-9A-F]*:)/i) { $ip=6; $Host=$1; } # IPv6
if ($Debug) { debug(" No DNS lookup asked.",4); }
}
# Put record in record queue
if ($Debug) { debug("Add record $NbOfLinesParsed in record queue (with host to resolve = ".($Host?$Host:'*').")",4); }
$QueueRecords{$NbOfLinesParsed}=$linerecord{$logfilechosen};
# Put record in host queue
# If there is a host to resolve, we add line to queue with value of host to resolve
# $Host is '' (no ip found) or is ip
if ($DNSLookup==0) {
$QueueHostsToResolve{$NbOfLinesParsed}='*';
}
if ($DNSLookup==1) {
$QueueHostsToResolve{$NbOfLinesParsed}=$Host?$Host:'*';
}
if ($DNSLookup==2) {
$QueueHostsToResolve{$NbOfLinesParsed}=$MyDNSTable{$Host}?$Host:'*';
}
# Print all records in head of queue that are ready
&WriteRecordsReadyInQueue($logfilechosen);
} # End of processing new record. Loop on next one.
if ($Debug) { debug("End of processing log file(s)"); }
# Close all log files
foreach my $logfilenb (keys %LogFileToDo) {
if ($Debug) { debug("Close log file number $logfilenb"); }
close("LOG$logfilenb") || error("Command for pipe '$LogFileToDo{$logfilenb}' failed");
}
while ( $QueueHostsToResolve{$QueueCursor} && $QueueHostsToResolve{$QueueCursor} ne '*' && ! $MyDNSTable{$QueueHostsToResolve{$QueueCursor}} && ! $TmpDNSLookup{$QueueHostsToResolve{$QueueCursor}} ) {
sleep 1;
# Print all records in head of queue that are ready
&WriteRecordsReadyInQueue($logfilechosen);
}
# Waiting queue is empty
if ($MaxNbOfThread) {
foreach my $t (threads->list()) {
if ($Debug) { debug("Join thread $t"); }
$t->join();
}
}
# DNSLookup warning
if ($DNSLookup==1 && $DNSLookupAlreadyDone) {
warning("Warning: $PROG has detected that some host names were already resolved in your logfile $DNSLookupAlreadyDone.\nIf DNS lookup was already made by the logger (web server) in ALL your log files, you should not use -dnslookup option to increase $PROG speed.");
}
if ($Debug) {
debug("Total nb of read lines: $NbOfLinesRead");
debug("Total nb of parsed lines: $NbOfLinesParsed");
debug("Total nb of DNS lookup asked: $NbOfDNSLookupAsked");
}
#if ($DNSCache) {
# open(CACHE, ">$DNSCache") or die;
# foreach (keys %TmpDNSLookup) {
# $TmpDNSLookup{$_}="*" if $TmpDNSLookup{$_} eq "ip";
# print CACHE "0\t$_\t$TmpDNSLookup{$_}\n";
# }
# close CACHE;
#}
0; # Do not remove this line

14
debian/alternc-awstats.dirs vendored Normal file
View File

@ -0,0 +1,14 @@
etc/apache
etc/awstats
etc/alternc/templates/awstats
var/cache/awstats
var/alternc/bureau/class
var/alternc/bureau/admin
var/alternc/bureau/locales/fr_FR/LC_MESSAGES
var/alternc/bureau/locales/en_US/LC_MESSAGES
var/alternc/bureau/locales/es_ES/LC_MESSAGES
usr/lib/alternc
usr/share/alternc
usr/share/doc/alternc-awstats
usr/share/lintian/overrides
usr/share/awstats/icon/other/

View File

@ -0,0 +1,5 @@
alternc-awstats: non-standard-dir-in-var var/alternc/
alternc-awstats: file-in-unusual-dir
alternc-awstats: no-debconf-config
alternc-awstats: postinst-does-not-load-confmodule

124
debian/alternc-awstats.postinst vendored Executable file
View File

@ -0,0 +1,124 @@
#!/bin/sh -e
# Uses debconf
. /usr/share/debconf/confmodule
MENUFILE="/etc/alternc/menulist.txt"
LOGAPACHE="/etc/alternc/awstats.log.alternc.conf"
APACHEROTATE="/etc/logrotate.d/apache2"
logrotate_apache() {
cp -a -f $APACHEROTATE $APACHEROTATE.tmp
sed -e 's/create 640 root adm/create 640 root www-data/' < $APACHEROTATE > $APACHEROTATE.tmp
mv -f $APACHEROTATE.tmp $APACHEROTATE
}
case "$1" in
configure)
# Then, configure the quota for "aws"
db_get alternc-awstats/default_quota_value || true
/usr/lib/alternc/quota_init aws $RET
db_stop
echo "Installing mysql table"
mysql --defaults-file=/etc/alternc/my.cnf \
</usr/share/alternc/awstats.sql || true
# Refresh apache configuration
# configure /etc/alternc/templates/apache/httpd.conf
# configure /etc/alternc/templates/apache-ssl/httpd.conf
# FIXME : ALTERNC DEPENDS ON APACHE2, SO APACHE IS NO LONGER SUPPORTED
# REMOVE THE FOLLOWING COMMENTED LINE TO CLEAN THIS FILE
#if [ -x /usr/sbin/apache ]; then
# if [ ! -h /etc/apache/conf.d/alterncawstats.conf ]; then
# ln -sf /etc/alternc/alterncawstats.conf \
# /etc/apache/conf.d/alterncawstats.conf
# fi
# # build awstats.log.alternc.conf if it does not exist
# if [ ! -f $LOGAPACHE ]; then
# cat > $LOGAPACHE <<EOF
#LogFile directive isn't important here :
#Awstats is launched with the good "LogFile" directive when called
#LogFile="/var/log/apache/access.log"
#LogFormat="%host %other %logname %time1 %methodurl %code %bytesd %refererquot %uaquot %other %virtualname"
#EOF
# chown alterncpanel:www-data $LOGAPACHE
# chmod 640 $LOGAPACHE
# fi
#fi
if [ -x /usr/sbin/apache2 ]; then
if [ ! -h /etc/apache2/conf.d/alterncawstats.conf ]; then
ln -sf /etc/alternc/alterncawstats.conf \
/etc/apache2/conf.d/alterncawstats.conf
fi
# build awstats.log.alternc.conf if it does not exist
if [ ! -f $LOGAPACHE ]; then
cat > $LOGAPACHE <<EOF
#LogFile directive isn't important here :
#Awstats is launched with the good "LogFile" directive when called
LogFile="/var/log/apache2/access.log"
LogFormat="%host %other %logname %time1 %methodurl %code %bytesd %refererquot %uaquot %other %virtualname"
EOF
chown alterncpanel:www-data $LOGAPACHE
chmod 640 $LOGAPACHE
fi
fi
if [ -x /usr/sbin/apache-ssl ]; then
if [ ! -h /etc/apache-ssl/conf.d/alterncawstats.conf ]; then
ln -sf /etc/alternc/alterncawstats.conf \
/etc/apache-ssl/conf.d/alterncawstats.conf
fi
fi
if [ ! -h /var/alternc/cgi-bin/awstats.pl ]; then
ln -sf /usr/lib/cgi-bin/awstats.pl \
/var/alternc/cgi-bin/awstats.pl
fi
alternc.install
logrotate_apache
# Add htpasswd :
touch /etc/alternc/awstats.htpasswd
chown alterncpanel /etc/alternc/awstats.htpasswd /etc/awstats
chmod 640 /etc/alternc/awstats.htpasswd
chmod 755 /etc/awstats
mkdir -p /var/cache/awstats
chown alterncpanel:www-data /var/cache/awstats
# ADD menu item :
if ! grep -q "^menu_aws.php$" "$MENUFILE"; then
rm -f $MENUFILE.alternc_awstats
sed -e "s/menu_sta2.php/&\\
menu_aws.php/" <$MENUFILE >$MENUFILE.alternc_awstats
mv -f $MENUFILE.alternc_awstats $MENUFILE
fi
echo "**********************************************"
echo "* ALTERNC-AWSTATS *"
echo "* Add an autorized user called 'admin' in *"
echo "* statistics section, so he will access *"
echo "* every stats of every users *"
echo "**********************************************"
;;
abort-upgrade|abort-remove|abort-deconfigure)
;;
*)
echo "postinst called with unknown argument \`$1'" >&2
exit 1
;;
esac
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#
# vim: et sw=4

44
debian/alternc-awstats.postrm vendored Executable file
View File

@ -0,0 +1,44 @@
#!/bin/sh -e
MENUFILE="/etc/alternc/menulist.txt"
case "$1" in
remove)
# Remove Awstats references from Apache configuration
# unconfigure /etc/alternc/templates/apache/httpd.conf
# unconfigure /etc/alternc/templates/apache-ssl/httpd.conf
alternc.install
if grep -qs "menu_aws.php" $MENUFILE; then
rm -f $MENUFILE.alternc_awstats
cat $MENUFILE | grep -v "menu_aws.php" >$MENUFILE.alternc_awstats
mv -f $MENUFILE.alternc_awstats $MENUFILE
fi
;;
purge)
#/usr/lib/alternc/quota_delete aws
if [ -e "$CONFIGFILE" -a -x "/usr/bin/mysql" ]; then
. "$CONFIGFILE"
mysql -f --defaults-file=/etc/alternc/my.cnf \
-e "DROP TABLE IF EXISTS aws,aws_users,aws_access;"
fi
#rm -rf /var/cache/awstats
#rm -f /etc/alternc/awstats.htpasswd
rm -f /etc/alternc/alterncawstats.conf \
/etc/apache-ssl/conf.d/alterncawstats.conf
# FIXME : ALTERNC DEPENDS ON APACHE2, APACHE IS NO LONGER REQUIRED
# REMOVE THE FOLLOWING LINE TO CLEAN THIS FILE
#if [ -x /usr/sbin/apache ]; then
# rm -f /etc/apache/conf.d/alterncawstats.conf
#fi
#if [ -x /usr/sbin/apache2 ]; then
rm -f /etc/apache2/conf.d/alterncawstats.conf
#fi
;;
esac
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#

19
debian/alternc-awstats.preinst vendored Executable file
View File

@ -0,0 +1,19 @@
#!/bin/sh -e
# Check that AlternC is properly installed/configured
if [ -f /etc/alternc/local.sh ]
then
exit 0
else
# Source debconf library.
. /usr/share/debconf/confmodule
db_version 2.0
db_title AlternC-Awstats
db_fset alternc-awstats/errorinstall seen false
db_input medium alternc-awstats/errorinstall
db_go
# il FAUT qu'AlternC soit proprement configuré pour installer awstats
exit 1
fi
#DEBHELPER#

17
debian/control vendored
View File

@ -133,3 +133,20 @@ Description-fr.UTF-8: Suite logicielle d'hébergement mutualisé pour Debian
automatique des profiles avec la bonne adresse et la bonne langue.
.
Pour plus d'informations, consultez http://www.alternc.com/
Package: alternc-awstats
Priority: optional
Section: admin
Architecture: all
Pre-depends: debconf
Depends: alternc (>=1.1), awstats (>=6.1-1), php5-cli
Suggests: apachemerge
Description: Awstats statistics module for AlternC
AlternC is a mutualized hosting software manager for Linux.
It allows you to manage your websites, domains, ftp, emails, aliases,
web statistics, mailing-lists, jabber accounts, etc.
.
This package is an optional module that adds awstats statistics
managment to the virtual desktop.
.
More information on http://www.alternc.com/.

16
debian/rules vendored
View File

@ -99,6 +99,22 @@ install: build
# alternc-squirrelmail:
(cd squirrelmail && $(MAKE) install DESTDIR=$(CURDIR)/debian/alternc-squirrelmail)
# alternc-awstats:
(cd awstats && $(MAKE) install DESTDIR=$(CURDIR)/debian/alternc-awstats)
cd ..
# Copy the desk files
cp -r awstats/bureau debian/alternc-awstats/var/alternc/
# Fix permisions
chown -R root:www-data debian/alternc-awstats/var/alternc/bureau
chmod -R 644 debian/alternc-awstats/var/alternc/bureau
chmod -R a+X debian/alternc-awstats/var/alternc/bureau
touch debian/alternc-awstats/var/cache/awstats/.placeholder
chown www-data:www-data debian/alternc-awstats/var/cache/awstats
chmod 755 debian/alternc-awstats/var/cache/awstats
mkdir -p debian/alternc-awstats/var/cache/awstats
# This single target is used to build all the packages, all at once, or
# one at a time. So keep in mind: any options passed to commands here will
# affect _all_ packages. Anything you want to only affect one package