REFACTORING: code formatting of the panel + braces on if/while/for + fixe some missing or too many Globals in functions

This commit is contained in:
Benjamin Sonntag 2015-09-25 17:42:00 +02:00
parent 3e42567048
commit d3ab589e56
19 changed files with 6838 additions and 6706 deletions

View File

@ -4,90 +4,88 @@ require_once("../class/config.php");
if (!$admin->enabled) {
__("This page is restricted to authorized staff");
exit();
}
}
include_once("head.php");
?>
<h3><?php __("Manage defaults domains type"); ?></h3>
<hr id="topbar" />
<p><?php __("If you don't know what this page is about, don't touch anything, and read AlternC documentation about domain types"); ?></p>
<p><?php __("The Type column contains a type of available VirtualHost config on The server."); ?></p>
<p><?php __("The Setting column contains the variables to be expanded in the defaults configuration. Available values are: "); ?></p>
<ul>
include_once("head.php");
?>
<h3><?php __("Manage defaults domains type"); ?></h3>
<hr id="topbar" />
<p><?php __("If you don't know what this page is about, don't touch anything, and read AlternC documentation about domain types"); ?></p>
<p><?php __("The Type column contains a type of available VirtualHost config on The server."); ?></p>
<p><?php __("The Setting column contains the variables to be expanded in the defaults configuration. Available values are: "); ?></p>
<ul>
<li><?php __("%%DOMAIN%% : the Domain name"); ?></li>
<li><?php __("%%TARGETDOM%%: The destination domain"); ?></li>
<li><?php __("%%SUB%% : The subdomain name"); ?></li>
<li><?php __("%%DOMAINDIR%%: the domain directory on the file system"); ?></li>
</ul>
</ul>
<br />
<?php
if (isset($error) && $error) {
<br />
<?php
if (isset($error) && $error) {
echo "<p class=\"alert alert-danger\">$error</p>";
}
}
$fields = array (
"domup" => array ("post", "array", ""),
$fields = array(
"domup" => array("post", "array", ""),
);
getFields($fields);
if (!empty($domup)) {
if (!$dom->update_default_subdomains($domup) ) {
$error=_("There was an error during the record.");
if (!$dom->update_default_subdomains($domup)) {
$error = _("There was an error during the record.");
} else {
$error=_("Save done.");
$error = _("Save done.");
}
}
$tab=$dom->lst_default_subdomains();
$tab = $dom->lst_default_subdomains();
?>
<form method="post" action="adm_doms_def_type.php" name="main" id="main">
<table class="tlist">
<table class="tlist">
<tr><th>&nbsp;</th><th><?php __("Sub"); ?></th><th><?php __("Type"); ?></th><th><?php __("settings"); ?></th><th><?php __("Concerned"); ?></th><th><?php __("Activation"); ?></th></tr>
<?php
for($i=0;$i<count($tab)+1;$i++) {?>
<?php for ($i = 0; $i < count($tab) + 1; $i++) { ?>
<tr class="lst">
<td>
<?php
@$val=$tab[$i];
if (isset($tab[$i])){
echo "<input type='hidden' name='domup[$i][id]' value='".$val['id']."' />";
<?php
@$val = $tab[$i];
if (isset($tab[$i])) {
echo "<input type='hidden' name='domup[$i][id]' value='" . $val['id'] . "' />";
}
?>
<div class="ina delete"><a href='dom_defdel.php?id=<?php echo $val['id']; ?>' type=''><?php __("Delete"); ?></a></div>
?>
<div class="ina delete"><a href="dom_defdel.php?id=<?php echo $val['id']; ?>"><?php __("Delete"); ?></a></div>
</td>
<td><input type='text' size="16" name='domup[<?php echo $i; ?>][sub]' value="<?php echo $val['sub']; ?>"/></td>
<?php $type=array("VHOST","URL","WEBMAIL","");
if(in_array($val['domain_type'],$type)){?>
<?php
$type = array("VHOST", "URL", "WEBMAIL", "");
if (in_array($val['domain_type'], $type)) {
?>
<td><select name='domup[<?php echo $i; ?>][domain_type]'>
<option value='VHOST' <?php if($val['domain_type']=='VHOST') echo "selected=\"selected\""; ?> >VHOST</option>
<option value='URL' <?php if($val['domain_type']=='URL') echo "selected=\"selected\""; ?> >URL</option>
<option value='WEBMAIL' <?php if($val['domain_type']=='WEBMAIL') echo "selected=\"selected\""; ?> >WEBMAIL</option>
<option value='VHOST' <?php if ($val['domain_type'] == 'VHOST') echo "selected=\"selected\""; ?> >VHOST</option>
<option value='URL' <?php if ($val['domain_type'] == 'URL') echo "selected=\"selected\""; ?> >URL</option>
<option value='WEBMAIL' <?php if ($val['domain_type'] == 'WEBMAIL') echo "selected=\"selected\""; ?> >WEBMAIL</option>
</select>
<?php }else{?>
<td><input type ='text' width="100px" style="width:100px" name='domup[<?php echo $i; ?>][domain_type]' value='<?php echo $val['domain_type']?>' ></td>
<? }?>
</td>
<td><input type ='text' name='domup[<?php echo $i; ?>][domain_type_parameter]' value='<?php echo $val['domain_type_parameter']?>' /></td>
<?php } else { ?>
<td><input type="text" style="width:100px" name="domup[<?php echo $i; ?>][domain_type]" value="<?php echo $val['domain_type'] ?>" ></td>
<?php } ?>
<td><input type ='text' name='domup[<?php echo $i; ?>][domain_type_parameter]' value='<?php echo $val['domain_type_parameter'] ?>' /></td>
<td><select name='domup[<?php echo $i; ?>][concerned]'>
<option value='MAIN' <?php if($val['concerned']=='MAIN') echo "selected=\"selected\""; ?> >MAIN</option>
<option value='SLAVE' <?php if($val['concerned']=='SLAVE') echo "selected=\"selected\""; ?> >SLAVE</option>
<option value='BOTH' <?php if($val['concerned']=='BOTH') echo "selected=\"selected\""; ?> >BOTH</option>
<option value='MAIN' <?php if ($val['concerned'] == 'MAIN') echo "selected=\"selected\""; ?> >MAIN</option>
<option value='SLAVE' <?php if ($val['concerned'] == 'SLAVE') echo "selected=\"selected\""; ?> >SLAVE</option>
<option value='BOTH' <?php if ($val['concerned'] == 'BOTH') echo "selected=\"selected\""; ?> >BOTH</option>
</select>
</td>
<td><input type="checkbox" name="domup[<?php echo $i; ?>][enabled]" value="1" <?php if ($val['enabled']==1) echo "checked=\"checked\""; ?> /></td>
<td><input type="checkbox" name="domup[<?php echo $i; ?>][enabled]" value="1" <?php if ($val['enabled'] == 1) echo "checked=\"checked\""; ?> /></td>
</tr>
<?php
}
?>
<?php
}
?>
<tr>
<td colspan='6'><p><input type="submit" class="inb" name="submit" value="<?php __("Save"); ?>" /></p></td>
</tr>
</table>
</table>
</form>
<?php
include_once("foot.php"); ?>
<?php include_once("foot.php");

View File

@ -1,4 +1,5 @@
<?php
/**
$Id: m_authip.php
----------------------------------------------------------------------
@ -18,11 +19,12 @@
----------------------------------------------------------------------
Original Author of file: Fufroma
----------------------------------------------------------------------
*/
*/
/**
* Classe de gestion des IP authorisée
* Classe de gestion des IP authorisée
* @group alternc
**/
* */
class m_authip {
/**
@ -33,7 +35,9 @@ class m_authip {
*/
function list_ip_whitelist() {
global $mem;
if (!$mem->checkRight()) return false;
if (!$mem->checkRight()) {
return false;
}
return $this->list_ip(true);
}
@ -47,7 +51,7 @@ class m_authip {
'ico' => 'images/ip.png',
'link' => 'ip_main.php',
'pos' => 120,
) ;
);
return $obj;
}
@ -62,11 +66,11 @@ class m_authip {
* @param boolean $whitelist
* @return array Retourne un tableau indexé des ip de l'utilisateur
*/
function list_ip($whitelist=false) {
function list_ip($whitelist = false) {
global $db, $mem;
if ($whitelist && $mem->checkRight() ) {
$cuid=0;
if ($whitelist && $mem->checkRight()) {
$cuid = 0;
} else {
global $cuid;
}
@ -74,20 +78,17 @@ class m_authip {
$r = array();
$db->query("SELECT * FROM authorised_ip WHERE uid='$cuid' order by ip,subnet;");
while ($db->next_record()) {
$r[$db->f('id')]=$db->Record;
if ( (checkip($db->f('ip')) && $db->f('subnet') == 32) ||
(checkipv6($db->f('ip')) && $db->f('subnet') == 128) ) {
$r[$db->f('id')]['ip_human']=$db->f('ip');
$r[$db->f('id')] = $db->Record;
if ((checkip($db->f('ip')) && $db->f('subnet') == 32) ||
(checkipv6($db->f('ip')) && $db->f('subnet') == 128)) {
$r[$db->f('id')]['ip_human'] = $db->f('ip');
} else {
$r[$db->f('id')]['ip_human']=$db->f('ip')."/".$db->f('subnet');
$r[$db->f('id')]['ip_human'] = $db->f('ip') . "/" . $db->f('subnet');
}
}
return $r;
}
/**
* Supprime une IP des IP de l'utilisateur
* et supprime les droits attaché en cascade
@ -102,14 +103,14 @@ class m_authip {
*/
function ip_delete($id) {
global $db, $cuid;
$id=intval($id);
$id = intval($id);
$db->query("SELECT id FROM authorised_ip_affected where authorised_ip_id ='$id';");
while ($db->next_record()) {
$this->ip_affected_delete($db->f('id'));
}
if (! $db->query("delete from authorised_ip where id='$id' and ( uid='$cuid' or uid=0) limit 1;") ) {
echo "query failed: ".$db->Error;
if (!$db->query("delete from authorised_ip where id='$id' and ( uid='$cuid' or uid=0) limit 1;")) {
echo "query failed: " . $db->Error;
return false;
}
return true;
@ -126,13 +127,13 @@ class m_authip {
*/
function get_allowed($s) {
global $db, $cuid;
if (! $db->query("select ai.ip, ai.subnet, ai.infos, aia.parameters from authorised_ip ai, authorised_ip_affected aia where aia.protocol='$s' and aia.authorised_ip_id = ai.id and ai.uid='$cuid';") ) {
echo "query failed: ".$db->Error;
if (!$db->query("select ai.ip, ai.subnet, ai.infos, aia.parameters from authorised_ip ai, authorised_ip_affected aia where aia.protocol='$s' and aia.authorised_ip_id = ai.id and ai.uid='$cuid';")) {
echo "query failed: " . $db->Error;
return false;
}
$r=Array();
$r = Array();
while ($db->next_record()) {
$r[]=Array("ip"=>$db->f("ip"), "subnet"=>$db->f("subnet"), "infos"=>$db->f("infos"), "parameters"=>$db->f("parameters"));
$r[] = Array("ip" => $db->f("ip"), "subnet" => $db->f("subnet"), "infos" => $db->f("infos"), "parameters" => $db->f("parameters"));
}
return $r;
}
@ -145,12 +146,13 @@ class m_authip {
*/
function is_wl($ip) {
global $db;
if (! $db->query("select ai.ip, ai.subnet from authorised_ip ai where ai.uid='0';") ) {
echo "query failed: ".$db->Error;
if (!$db->query("select ai.ip, ai.subnet from authorised_ip ai where ai.uid='0';")) {
echo "query failed: " . $db->Error;
return false;
}
while ($db->next_record()) {
if ( $this->is_in_subnet($ip, $db->f('ip'), $db->f('subnet') ) ) return true;
if ($this->is_in_subnet($ip, $db->f('ip'), $db->f('subnet')))
return true;
}
return false;
}
@ -168,7 +170,9 @@ class m_authip {
$ip = inet_pton($ip);
$sub = pow(2, $sub);
if ( $o >= $ip && $o <= ($ip+$sub) ) return true;
if ($o >= $ip && $o <= ($ip + $sub)) {
return true;
}
return false;
}
@ -179,7 +183,9 @@ class m_authip {
*/
function ip_save_whitelist($id, $ipsub, $infos) {
global $mem;
if (!$mem->checkRight()) return false;
if (!$mem->checkRight()) {
return false;
}
return $this->ip_save($id, $ipsub, $infos, 0);
}
@ -198,56 +204,61 @@ class m_authip {
* @return boolean Retourne FALSE si erreur, sinon TRUE
*
*/
function ip_save($id, $ipsub, $infos, $uid=null) {
function ip_save($id, $ipsub, $infos, $uid = null) {
global $db, $mem;
// If we ask for uid=0, we have to check to be super-user
// else, juste use global cuid;
if ($uid === 0 && $mem->checkRight() ) {
$cuid=0;
if ($uid === 0 && $mem->checkRight()) {
$cuid = 0;
} else {
global $cuid;
}
$id=intval($id);
$infos=mysql_real_escape_string($infos);
$id = intval($id);
$infos = mysql_real_escape_string($infos);
// Extract subnet from ipsub
$tmp=explode('/',$ipsub);
$ip=$tmp[0];
$tmp = explode('/', $ipsub);
$ip = $tmp[0];
// Error if $ip not an IP
if ( ! checkip($ip) && ! checkipv6($ip) ) {
if (!checkip($ip) && !checkipv6($ip)) {
echo "Failed : not an IP address";
return false;
}
// Check the subnet, if not defined, give a /32 or a /128
if (isset($tmp[1])) {
$subnet=intval($tmp[1]);
$subnet = intval($tmp[1]);
} else {
if ( checkip($ip) ) $subnet=32;
else $subnet=128;
if (checkip($ip)) {
$subnet = 32;
} else {
$subnet = 128;
}
}
// An IPv4 can't have subnet > 32
if (checkip($ip) && $subnet > 32 ) $subnet=32;
if (checkip($ip) && $subnet > 32) {
$subnet = 32;
}
if ($id) { // Update
$list_affected = $this->list_affected($id);
foreach($list_affected as $k => $v) {
$this->call_hooks("authip_on_delete", $k );
foreach ($list_affected as $k => $v) {
$this->call_hooks("authip_on_delete", $k);
}
if (! $db->query("update authorised_ip set ip='$ip', subnet='$subnet', infos='$infos' where id='$id' and uid='$cuid' ;") ) {
echo "query failed: ".$db->Error;
if (!$db->query("update authorised_ip set ip='$ip', subnet='$subnet', infos='$infos' where id='$id' and uid='$cuid' ;")) {
echo "query failed: " . $db->Error;
return false;
}
foreach($list_affected as $k => $v) {
$this->call_hooks("authip_on_create", $k );
foreach ($list_affected as $k => $v) {
$this->call_hooks("authip_on_create", $k);
}
} else { // Insert
if (! $db->query("insert into authorised_ip (uid, ip, subnet, infos) values ('$cuid', '$ip', '$subnet', '$infos' );") ) {
echo "query failed: ".$db->Error;
if (!$db->query("insert into authorised_ip (uid, ip, subnet, infos) values ('$cuid', '$ip', '$subnet', '$infos' );")) {
echo "query failed: " . $db->Error;
return false;
}
}
@ -262,7 +273,7 @@ class m_authip {
* @return boolean Retourne TRUE
*/
function alternc_del_member() {
global $cuid,$db;
global $cuid, $db;
$db->query("SELECT id FROM authorised_ip WHERE uid ='$cuid';");
while ($db->next_record()) {
$this->ip_delete($db->f('id'));
@ -270,7 +281,6 @@ class m_authip {
return true;
}
/**
* Analyse les classes et récupéres les informations
* des classes voulant de la restriction IP
@ -284,7 +294,7 @@ class m_authip {
// Je rajoute la class DANS l'objet parce que
// ca m'interesse
foreach ($authclass as $k => $v) {
$authclass[$k]['class']=$k;
$authclass[$k]['class'] = $k;
}
return $authclass;
@ -302,26 +312,26 @@ class m_authip {
* @param int $id $id présent si c'est une édition
* @return boolean Retourne FALSE si erreur, sinon TRUE
*/
function ip_affected_save($authorised_ip_id, $protocol, $parameters, $id=null) {
function ip_affected_save($authorised_ip_id, $protocol, $parameters, $id = null) {
global $db;
$authorised_ip_id=intval($authorised_ip_id);
$protocol=mysql_real_escape_string($protocol);
$parameters=mysql_real_escape_string($parameters);
$authorised_ip_id = intval($authorised_ip_id);
$protocol = mysql_real_escape_string($protocol);
$parameters = mysql_real_escape_string($parameters);
if ($id) {
$id=intval($id);
$this->call_hooks("authip_on_delete", $id );
if (! $db->query("update authorised_ip_affected set authorised_ip_id='$authorised_ip_id', protocol='$protocol', parameters='$parameters' where id ='$id' limit 1;") ) {
echo "query failed: ".$db->Error;
$id = intval($id);
$this->call_hooks("authip_on_delete", $id);
if (!$db->query("update authorised_ip_affected set authorised_ip_id='$authorised_ip_id', protocol='$protocol', parameters='$parameters' where id ='$id' limit 1;")) {
echo "query failed: " . $db->Error;
return false;
}
$this->call_hooks("authip_on_create", $id );
$this->call_hooks("authip_on_create", $id);
} else {
if (! $db->query("insert into authorised_ip_affected (authorised_ip_id, protocol, parameters) values ('$authorised_ip_id', '$protocol', '$parameters');") ) {
echo "query failed: ".$db->Error;
if (!$db->query("insert into authorised_ip_affected (authorised_ip_id, protocol, parameters) values ('$authorised_ip_id', '$protocol', '$parameters');")) {
echo "query failed: " . $db->Error;
return false;
}
$this->call_hooks("authip_on_create", mysql_insert_id() );
$this->call_hooks("authip_on_create", mysql_insert_id());
}
return true;
}
@ -337,19 +347,18 @@ class m_authip {
*/
function ip_affected_delete($id) {
global $db;
$id=intval($id);
$id = intval($id);
// Call hooks
$this->call_hooks("authip_on_delete", $id );
$this->call_hooks("authip_on_delete", $id);
if (! $db->query("delete from authorised_ip_affected where id='$id' limit 1;") ) {
echo "query failed: ".$db->Error;
if (!$db->query("delete from authorised_ip_affected where id='$id' limit 1;")) {
echo "query failed: " . $db->Error;
return false;
}
return true;
}
/**
* Appel les hooks demandé avec en parametres les
* affectationt ip<=>ressource dont l'id est en parametre
@ -361,11 +370,11 @@ class m_authip {
* @return boolean Retourne TRUE
*/
function call_hooks($function, $affectation_id) {
global $hooks,$err;
global $hooks, $err;
// On récure l'objet dont on parle
$d = $this->list_affected();
if (! isset($d[$affectation_id] )) {
if (!isset($d[$affectation_id])) {
$err->raise('authip', _("Object not available"));
return false;
}
@ -374,14 +383,14 @@ class m_authip {
// On en déduis la classe qui le concerne
$e = $this->get_auth_class();
if (! isset($e[$affectation['protocol']])) {
if (!isset($e[$affectation['protocol']])) {
$err->raise('authip', sprintf(_("Can't identified class for the protocole %s"), $affectation['protocol']));
return false;
}
$c = $e[$affectation['protocol']]['class'];
// On appelle le hooks de cette classe
$hooks->invoke($function, Array($affectation), Array($c) );
$hooks->invoke($function, Array($affectation), Array($c));
return true;
}
@ -394,21 +403,21 @@ class m_authip {
* @param int $ip_id
* @return array Retourne un tableau de valeurs
*/
function list_affected($ip_id=null) {
function list_affected($ip_id = null) {
global $db, $cuid;
$r = array();
if ( is_null($ip_id) ) {
if (is_null($ip_id)) {
$db->query("select aia.* from authorised_ip_affected aia, authorised_ip ai where ai.uid='$cuid' and aia.authorised_ip_id = ai.id order by protocol, parameters;");
} else {
$db->query("select aia.* from authorised_ip_affected aia, authorised_ip ai where ai.uid='$cuid' and aia.authorised_ip_id = '".intval($ip_id)."' order by protocol, parameters;");
$db->query("select aia.* from authorised_ip_affected aia, authorised_ip ai where ai.uid='$cuid' and aia.authorised_ip_id = '" . intval($ip_id) . "' order by protocol, parameters;");
}
while ($db->next_record()) {
$r[$db->f('id')]=$db->Record;
$r[$db->f('id')] = $db->Record;
}
return $r;
}
}; /* Classe m_authip */
}
?>
/* Classe m_authip */

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,5 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
@ -21,50 +22,52 @@
----------------------------------------------------------------------
Purpose of file: Manage hook system.
----------------------------------------------------------------------
*/
*/
/**
* This class manage web-cron tasks
*/
class m_cron {
const MAX_SOCKETS=8;
const DEFAULT_CAFILE="/etc/ssl/certs/ca-certificates.crt";
const MAX_SOCKETS = 8;
const DEFAULT_CAFILE = "/etc/ssl/certs/ca-certificates.crt";
/* --------------------------------------------------------------------------- */
/*---------------------------------------------------------------------------*/
/** Constructor
*/
function m_cron() {
}
function schedule() {
return Array(
Array('unit'=>1440, 'name'=>_("Daily")),
Array('unit'=>60, 'name'=>_("Hour")),
Array('unit'=>30, 'name'=>_("Half Hour")),
Array('unit' => 1440, 'name' => _("Daily")),
Array('unit' => 60, 'name' => _("Hour")),
Array('unit' => 30, 'name' => _("Half Hour")),
);
}
/* --------------------------------------------------------------------------- */
/*---------------------------------------------------------------------------*/
/** List the crontab for the current user.
* @return array an hash for each crontab.
*/
function lst_cron() {
global $cuid,$db,$err;
$err->log("cron","lst_cron");
global $cuid, $db, $err;
$err->log("cron", "lst_cron");
$db->query("SELECT * FROM cron WHERE uid = $cuid ORDER BY url;");
$r=Array();
$r = Array();
while ($db->next_record()) {
$tmp=Array();
$tmp['id']=$db->f('id');
$tmp['url']=urldecode($db->f('url'));
$tmp['user']=urldecode($db->f('user'));
$tmp['password']=urldecode($db->f('password'));
$tmp['schedule']=$db->f('schedule');
$tmp['email']=urldecode($db->f('email'));
$tmp['next_execution']=$db->f('next_execution');
$r[]=$tmp;
$tmp = Array();
$tmp['id'] = $db->f('id');
$tmp['url'] = urldecode($db->f('url'));
$tmp['user'] = urldecode($db->f('user'));
$tmp['password'] = urldecode($db->f('password'));
$tmp['schedule'] = $db->f('schedule');
$tmp['email'] = urldecode($db->f('email'));
$tmp['next_execution'] = $db->f('next_execution');
$r[] = $tmp;
}
return $r;
}
@ -75,84 +78,93 @@ class m_cron {
'ico' => 'images/schedule.png',
'link' => 'cron.php',
'pos' => 90,
) ;
);
return $obj;
}
/*---------------------------------------------------------------------------*/
/* --------------------------------------------------------------------------- */
/** update the crontab
* @param $arr array the crontab information, including its ID
* @return boolean TRUE if the crontab has been edited
*/
function update($arr) {
$ok=true;
$ok = true;
foreach ($arr as $a) {
if (! isset($a['id'])) $a['id']=null;
if (empty($a['url']) && is_null($a['id'])) continue;
if (! $this->_update_one($a['url'], $a['user'], $a['password'], $a['email'], $a['schedule'], $a['id']) ) {
$ok=false;
if (!isset($a['id'])) {
$a['id'] = null;
}
if (empty($a['url']) && is_null($a['id'])) {
continue;
}
if (!$this->_update_one($a['url'], $a['user'], $a['password'], $a['email'], $a['schedule'], $a['id'])) {
$ok = false;
}
}
return $ok;
}
/* --------------------------------------------------------------------------- */
/*---------------------------------------------------------------------------*/
/** delete a crontab
* @param $id the id of the crontab to delete
* @return boolean TRUE if the crontab has been deleted
*/
function delete_one($id) {
global $db,$err,$cuid;
$err->log("cron","delete_one");
return $db->query("DELETE FROM cron WHERE id=".intval($id)." AND uid=$cuid LIMIT 1;");
global $db, $err, $cuid;
$err->log("cron", "delete_one");
return $db->query("DELETE FROM cron WHERE id=" . intval($id) . " AND uid=$cuid LIMIT 1;");
}
/* --------------------------------------------------------------------------- */
/*---------------------------------------------------------------------------*/
/** update a crontab,
* @return boolean TRUE if the crontab has been edited
*/
private function _update_one($url, $user, $password, $email, $schedule, $id=null) {
global $db,$err,$quota,$cuid;
$err->log("cron","update_one");
private function _update_one($url, $user, $password, $email, $schedule, $id = null) {
global $db, $err, $quota, $cuid;
$err->log("cron", "update_one");
if (empty($url) && !is_null($id)) {
return $this->delete_one($id);
}
if(filter_var($url,FILTER_VALIDATE_URL)===false){
$err->raise("cron",_("URL not valid"));
if (filter_var($url, FILTER_VALIDATE_URL) === false) {
$err->raise("cron", _("URL not valid"));
return false;
}
$url=urlencode($url);
$user=urlencode($user);
if (empty($user)) $password='';
$password=urlencode($password);
$url = urlencode($url);
$user = urlencode($user);
if (empty($user)) {
$password = '';
}
$password = urlencode($password);
//@todo remove checkmail cf functions.php
if (!empty($email) && ! checkmail($email) == 0 ){
$err->raise("cron",_("Email address is not valid"));
if (!empty($email) && !checkmail($email) == 0) {
$err->raise("cron", _("Email address is not valid"));
return false;
}
$email = urlencode($email);
if (!$this->valid_schedule($schedule)) {
return false;
}
$email=urlencode($email);
if (! $this->valid_schedule($schedule)) return false;
if (is_null($id)) { // if a new insert, quotacheck
$q = $quota->getquota("cron");
if ( $q["u"] >= $q["t"] ) {
$err->raise("cron",_("You quota of cron entries is over. You cannot create more cron entries"));
if ($q["u"] >= $q["t"]) {
$err->raise("cron", _("You quota of cron entries is over. You cannot create more cron entries"));
return false;
}
} else { // if not a new insert, check the $cuid
$db->query("SELECT uid FROM cron WHERE id = $id;");
if (! $db->next_record()) {
if (!$db->next_record()) {
return "false";
} // return false if pb
if ( $db->f('uid') != $cuid ) {
$err->raise("cron",_("Identity problem"));
if ($db->f('uid') != $cuid) {
$err->raise("cron", _("Identity problem"));
return false;
}
}
@ -160,37 +172,43 @@ class m_cron {
return $db->query("$query");
}
/* --------------------------------------------------------------------------- */
/*---------------------------------------------------------------------------*/
/** validate a crontab schedule
* @param $s array schedule paramters
* @return boolean TRUE if the schedule is valid
*/
function valid_schedule($s) {
$s2 = intval($s);
if ($s2 != $s) return false;
$r=false;
foreach ($this->schedule() as $cs ) {
if ($cs['unit'] == $s) return true;
if ($s2 != $s) {
return false;
}
$r = false;
foreach ($this->schedule() as $cs) {
if ($cs['unit'] == $s) {
return true;
}
}
return $r;
}
/*---------------------------------------------------------------------------*/
/* --------------------------------------------------------------------------- */
/** hook for quota computation
*/
function hook_quota_get() {
global $cuid,$db,$err;
$err->log("cron","alternc_get_quota");
$q=Array("name"=>"cron", "description"=>_("Scheduled tasks"), "used"=>0);
global $cuid, $db, $err;
$err->log("cron", "alternc_get_quota");
$q = Array("name" => "cron", "description" => _("Scheduled tasks"), "used" => 0);
$db->query("select count(*) as cnt from cron where uid = $cuid;");
if ($db->next_record()) {
$q['used']=$db->f('cnt');
$q['used'] = $db->f('cnt');
}
return $q;
}
/*---------------------------------------------------------------------------*/
/* --------------------------------------------------------------------------- */
/**
* Execute the required crontab of AlternC users
* this function EXIT at the end.
@ -198,27 +216,32 @@ class m_cron {
function execute_cron() {
global $db;
if (!isset($GLOBALS["DEBUG"])) $GLOBALS["DEBUG"]=false;
if (!isset($GLOBALS["DEBUG"])) {
$GLOBALS["DEBUG"] = false;
}
$db->query("SELECT id, url, email, schedule, user, password FROM cron WHERE next_execution <= NOW();");
$urllist=array();
$urllist = array();
while ($db->next_record()) {
$db->Record["url"]=urldecode($db->Record["url"]); $db->Record["user"]=urldecode($db->Record["user"]);
$db->Record["email"]=urldecode($db->Record["email"]); $db->Record["password"]=urldecode($db->Record["password"]);
$db->Record["url"] = urldecode($db->Record["url"]);
$db->Record["user"] = urldecode($db->Record["user"]);
$db->Record["email"] = urldecode($db->Record["email"]);
$db->Record["password"] = urldecode($db->Record["password"]);
// we support only http or https schemes:
if (substr($db->Record["url"],0,7)=="http://" || substr($db->Record["url"],0,8)=="https://") {
$u=array(
if (substr($db->Record["url"], 0, 7) == "http://" || substr($db->Record["url"], 0, 8) == "https://") {
$u = array(
"url" => $db->Record["url"],
"id" => $db->Record["id"], "email" =>$db->Record["email"],
"id" => $db->Record["id"], "email" => $db->Record["email"],
);
if ($db->Record["user"] && $db->Record["password"]) {
$u["login"]=$db->Record["user"];
$u["password"]=$db->Record["password"];
$u["login"] = $db->Record["user"];
$u["password"] = $db->Record["password"];
}
if ($GLOBALS["DEBUG"]) echo "Will run cron :\n".print_r($u,true)."\n";
$urllist[]=$u;
if ($GLOBALS["DEBUG"])
echo "Will run cron :\n" . print_r($u, true) . "\n";
$urllist[] = $u;
}
if (empty($urllist)) { // nothing to do :
@ -226,39 +249,39 @@ class m_cron {
}
// cron_callback($url, $content, $curlobj) will be called at the end of each http call.
$this->rolling_curl($urllist, array("m_cron","cron_callback"));
$this->rolling_curl($urllist, array("m_cron", "cron_callback"));
}
}
/* --------------------------------------------------------------------------- */
/*---------------------------------------------------------------------------*/
/**
* Callback function called by rolling_curl when a cron resulr has been received
* schedule it for next run and send the mail if needed
*/
function cron_callback($url,$content,$curl) {
global $db,$L_FQDN;
if (empty($url["id"])) return; // not normal...
$id=intval($url["id"]);
function cron_callback($url, $content, $curl) {
global $db, $L_FQDN;
if (empty($url["id"])) {
return; // not normal...
}
$id = intval($url["id"]);
if ($curl["http_code"]==200) {
$ok=true;
if ($curl["http_code"] == 200) {
$ok = true;
} else {
$ok=false;
$ok = false;
}
if (isset($url["email"]) && $url["email"] && $content) {
if (!mail($url["email"],"AlternC Cron #$id - Report ".date("r"),"Please find below the stdout content produced by your cron task.\n------------------------------------------------------------\n\n".$content,"From: postmaster@$L_FQDN")) {
echo "Error sending mail for cron #$id to address '".$url["email"]."'\n";
if (!mail($url["email"], "AlternC Cron #$id - Report " . date("r"), "Please find below the stdout content produced by your cron task.\n------------------------------------------------------------\n\n" . $content, "From: postmaster@$L_FQDN")) {
echo "Error sending mail for cron #$id to address '" . $url["email"] . "'\n";
}
}
// now schedule it for next run:
$db->query("UPDATE cron SET next_execution=FROM_UNIXTIME( UNIX_TIMESTAMP(NOW()) + schedule * 60) WHERE id=$id");
}
/* --------------------------------------------------------------------------- */
/*---------------------------------------------------------------------------*/
/**
* Launch parallel (using MAX_SOCKETS sockets maximum) retrieval
* of URL using CURL
@ -273,12 +296,12 @@ class m_cron {
*/
function rolling_curl($urls, $callback, $custom_options = null) {
// make sure the rolling window isn't greater than the # of urls
if (!isset($GLOBALS["DEBUG"])) $GLOBALS["DEBUG"]=false;
if (!isset($GLOBALS["DEBUG"]))
$GLOBALS["DEBUG"] = false;
$rolling_window = m_cron::MAX_SOCKETS;
$rolling_window = (count($urls) < $rolling_window) ? count($urls) : $rolling_window;
$master = curl_multi_init();
$curl_arr = array();
// add additional curl options here
$std_options = array(CURLOPT_RETURNTRANSFER => true,
@ -288,66 +311,82 @@ class m_cron {
CURLOPT_USERAGENT => "AlternC (Cron Daemon)",
CURLOPT_MAXREDIRS => 0);
if ($GLOBALS["DEBUG"]) $std_options[CURLOPT_VERBOSE]=true;
if ($GLOBALS["DEBUG"]) {
$std_options[CURLOPT_VERBOSE] = true;
}
$options = ($custom_options) ? ($std_options + $custom_options) : $std_options;
// start the first batch of requests
for ($i = 0; $i < $rolling_window; $i++) {
$ch = curl_init();
$options[CURLOPT_URL] = $urls[$i]["url"];
if ($GLOBALS["DEBUG"]) echo "URL: ".$urls[$i]["url"]."\n";
curl_setopt_array($ch,$options);
if ($GLOBALS["DEBUG"]) {
echo "URL: " . $urls[$i]["url"] . "\n";
}
curl_setopt_array($ch, $options);
// Handle custom cafile for some https url
if (strtolower(substr($options[CURLOPT_URL],0,5))=="https") {
curl_setopt($ch,CURLOPT_CAINFO,m_cron::DEFAULT_CAFILE);
if ($GLOBALS["DEBUG"]) echo "cainfo set to DEFAULT\n";
if (strtolower(substr($options[CURLOPT_URL], 0, 5)) == "https") {
curl_setopt($ch, CURLOPT_CAINFO, m_cron::DEFAULT_CAFILE);
if ($GLOBALS["DEBUG"]) {
echo "cainfo set to DEFAULT\n";
}
}
if (isset($urls[$i]["login"]) && isset($urls[$i]["password"])) { // set basic http authentication
curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_BASIC);
curl_setopt($ch,CURLOPT_USERPWD,$urls[$i]["login"].":".$urls[$i]["password"]);
if ($GLOBALS["DEBUG"]) echo "set basic auth\n";
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $urls[$i]["login"] . ":" . $urls[$i]["password"]);
if ($GLOBALS["DEBUG"]) {
echo "set basic auth\n";
}
}
curl_multi_add_handle($master, $ch);
}
do {
while(($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM);
if($execrun != CURLM_OK)
while (($execrun = curl_multi_exec($master, $running)) == CURLM_CALL_MULTI_PERFORM);
if ($execrun != CURLM_OK) {
break;
}
// a request was just completed -- find out which one
while($done = curl_multi_info_read($master)) {
while ($done = curl_multi_info_read($master)) {
$info = curl_getinfo($done['handle']);
// TODO : since ssl_verify_result is buggy, if we have [header_size] => 0 && [request_size] => 0 && [http_code] => 0, AND https, we can pretend the SSL certificate is buggy.
if ($GLOBALS["DEBUG"]) { echo "Info for ".$done['handle']." \n"; print_r($info); }
if ($GLOBALS["DEBUG"]) {
echo "Info for " . $done['handle'] . " \n";
print_r($info);
}
if ($info['http_code'] == 200) {
$output = curl_multi_getcontent($done['handle']);
} else {
// request failed. add error handling.
$output="";
$output = "";
}
// request terminated. process output using the callback function.
// Pass the url array to the callback, so we need to search it
foreach($urls as $url) {
if ($url["url"]==$info["url"]) {
call_user_func($callback,$url,$output,$info);
foreach ($urls as $url) {
if ($url["url"] == $info["url"]) {
call_user_func($callback, $url, $output, $info);
break;
}
}
// If there is more: start a new request
// (it's important to do this before removing the old one)
if ($i<count($urls)) {
if ($i < count($urls)) {
$ch = curl_init();
$options[CURLOPT_URL] = $urls[$i++]; // increment i
curl_setopt_array($ch,$options);
if (strtolower(substr($options[CURLOPT_URL],0,5))=="https") {
curl_setopt($ch,CURLOPT_CAINFO,m_cron::DEFAULT_CAFILE);
if ($GLOBALS["DEBUG"]) echo "cainfo set to DEFAULT\n";
curl_setopt_array($ch, $options);
if (strtolower(substr($options[CURLOPT_URL], 0, 5)) == "https") {
curl_setopt($ch, CURLOPT_CAINFO, m_cron::DEFAULT_CAFILE);
if ($GLOBALS["DEBUG"]) {
echo "cainfo set to DEFAULT\n";
}
}
if (isset($urls[$i]["login"]) && isset($urls[$i]["password"])) { // set basic http authentication
curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_BASIC);
curl_setopt($ch,CURLOPT_USERPWD,urlencode($urls[$i]["login"]).":".urlencode($urls[$i]["password"]));
if ($GLOBALS["DEBUG"]) echo "set basic auth\n";
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, urlencode($urls[$i]["login"]) . ":" . urlencode($urls[$i]["password"]));
if ($GLOBALS["DEBUG"]) {
echo "set basic auth\n";
}
}
curl_multi_add_handle($master, $ch);
}
@ -360,5 +399,6 @@ class m_cron {
return true;
}
}
} /* Class cron */
/* Class cron */

View File

@ -1,41 +1,28 @@
<?php
class m_crypto
{
function encrypt($sValue, $sSecretKey)
{
class m_crypto {
function encrypt($sValue, $sSecretKey) {
return rtrim(
base64_encode(
mcrypt_encrypt(
MCRYPT_RIJNDAEL_256,
$sSecretKey, $sValue,
MCRYPT_MODE_ECB,
mcrypt_create_iv(
MCRYPT_RIJNDAEL_256, $sSecretKey, $sValue, MCRYPT_MODE_ECB, mcrypt_create_iv(
mcrypt_get_iv_size(
MCRYPT_RIJNDAEL_256,
MCRYPT_MODE_ECB
),
MCRYPT_RAND
MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB
), MCRYPT_RAND
)
)
), "\0"
);
}
function decrypt($sValue, $sSecretKey)
{
function decrypt($sValue, $sSecretKey) {
return rtrim(
mcrypt_decrypt(
MCRYPT_RIJNDAEL_256,
$sSecretKey,
base64_decode($sValue),
MCRYPT_MODE_ECB,
mcrypt_create_iv(
MCRYPT_RIJNDAEL_256, $sSecretKey, base64_decode($sValue), MCRYPT_MODE_ECB, mcrypt_create_iv(
mcrypt_get_iv_size(
MCRYPT_RIJNDAEL_256,
MCRYPT_MODE_ECB
),
MCRYPT_RAND
MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB
), MCRYPT_RAND
)
), "\0"
);

View File

@ -1,4 +1,5 @@
<?php
/*
LICENSE
@ -17,41 +18,44 @@
Original Author of file: Camille Lafitte
Purpose of file: Manage hook system.
----------------------------------------------------------------------
*/
*/
/**
* This class manage debug.
*
* @copyright AlternC-Team 2002-2005 http://alternc.org/
*/
class m_debug_alternc {
var $infos="";
var $status=false;
var $nb_sql_query=0;
var $tps_sql_query=0;
var $generation_started=null;
/*---------------------------------------------------------------------------*/
var $infos = "";
var $status = false;
var $nb_sql_query = 0;
var $tps_sql_query = 0;
var $generation_started = null;
/* --------------------------------------------------------------------------- */
/** Constructor
*/
function m_debug_alternc() {
if ( isset($_COOKIE['alternc_debugme']) && $_COOKIE['alternc_debugme'] ) {
$this->status=true;
if (isset($_COOKIE['alternc_debugme']) && $_COOKIE['alternc_debugme']) {
$this->status = true;
ini_set('display_errors', '1');
}
$this->nb_sql_query=0;
$this->tps_sql_query=0;
$this->generation_started=microtime(true);
$this->nb_sql_query = 0;
$this->tps_sql_query = 0;
$this->generation_started = microtime(true);
}
function activate() {
setcookie('alternc_debugme','1', time()+3600); // expire in 1 hour
$this->status="";
setcookie('alternc_debugme', '1', time() + 3600); // expire in 1 hour
$this->status = "";
return true;
}
function desactivate() {
setcookie('alternc_debugme','0');
$this->status=false;
setcookie('alternc_debugme', '0');
$this->status = false;
return true;
}
@ -62,8 +66,12 @@ class m_debug_alternc {
function dump() {
global $cuid;
if ( $cuid!=2000 ) return false;
if ( ! $this->status ) return false;
if ($cuid != 2000) {
return false;
}
if (!$this->status) {
return false;
}
$generation_time = (microtime(true) - $this->generation_started) * 1000;
@ -71,7 +79,7 @@ class m_debug_alternc {
echo "<pre>";
echo "+++ BEGIN Debug Mode+++\n";
echo "Total generation time : $generation_time ms\n";
print_r("\n--- Total SQL Query : ".$this->nb_sql_query." req / ".$this->tps_sql_query." ms ---\n");
print_r("\n--- Total SQL Query : " . $this->nb_sql_query . " req / " . $this->tps_sql_query . " ms ---\n");
print_r($this->infos);
echo "\n\n--- GET ---\n";
print_r($_GET);
@ -89,6 +97,6 @@ class m_debug_alternc {
return true;
}
} /* Class debug_alternc */
}
?>
/* Class debug_alternc */

View File

@ -105,16 +105,16 @@ class m_dom {
* @param string $fqdn
*/
public static function get_sub_domain_id_and_member_by_name($fqdn) {
global $db, $err, $cuid;
global $db, $err;
$err->log("dom", "get_sub_domain_by_name");
$fqdn = mysql_real_escape_string($fqdn);
$db->query("select sd.* from sub_domaines sd where if(length(sd.sub)>0,concat_ws('.',sd.sub,sd.domaine),sd.domaine) = '$fqdn';");
if (!$db->next_record())
if (!$db->next_record()) {
return false;
}
return array('sub_id' => intval($db->f('id')), 'member_id' => intval($db->f('compte')));
}
function hook_menu() {
global $quota;
$obj = array(
@ -126,8 +126,7 @@ class m_dom {
);
if ($quota->cancreate("dom")) {
$obj['links'][] =
array(
$obj['links'][] = array(
'ico' => 'images/new.png',
'txt' => _("Add a domain"),
'url' => "dom_add.php",
@ -135,8 +134,7 @@ class m_dom {
}
foreach ($this->enum_domains() as $d) {
$obj['links'][] =
array(
$obj['links'][] = array(
'txt' => htmlentities($d),
'url' => "dom_edit.php?domain=" . urlencode($d),
);
@ -186,7 +184,7 @@ class m_dom {
* @param integer $type
*/
function domains_type_target_values($type = null) {
global $db, $err, $cuid;
global $db, $err;
$err->log("dom", "domains_type_target_values");
if (is_null($type)) {
$db->query("desc domaines_type;");
@ -202,8 +200,9 @@ class m_dom {
return $r;
} else {
$db->query("select target from domaines_type where name='$type';");
if (!$db->next_record())
if (!$db->next_record()) {
return false;
}
return $db->f('target');
}
}
@ -220,8 +219,9 @@ class m_dom {
$val = array();
foreach (explode("\n", $zone) as $z) {
$z = trim($z);
if (empty($z))
if (empty($z)) {
continue;
}
$val[] = $this->import_manual_dns_entry($z, $domain, $detect_redirect, $save);
}
return $val;
@ -231,11 +231,12 @@ class m_dom {
* @param string $zone
*/
function import_manual_dns_entry($zone, $domain, $detect_redirect = true, $save = false) {
global $cuid, $err;
global $err;
$err->log("dom", "import_manual_dns_entry");
$zone = trim($zone);
if (empty($zone))
if (empty($zone)) {
return false;
}
$domain = trim($domain);
if (empty($domain)) {
@ -409,7 +410,6 @@ class m_dom {
}
private function import_manual_dns_entry_doit($entry) {
global $err;
$entry['did_it'] = 0;
if ($entry['status'] == 'err') {
return $entry;
@ -417,14 +417,14 @@ class m_dom {
$val = $entry['entry_new'];
if (empty($val['type']))
if (empty($val['type'])) {
return false;
}
switch ($val['type']) {
case "set_ttl":
$entry['did_it'] = $this->set_ttl($this->get_domain_byname($val['domain']), $val['value']);
return $entry;
break;
}
// If it is an unknown domains type
@ -435,8 +435,9 @@ class m_dom {
}
// If the subdomain is @, we want an empty subdomain
if ($val['sub'] == '@')
if ($val['sub'] == '@') {
$val['sub'] = '';
}
$this->lock();
$entry['did_it'] = $this->set_sub_domain($val['domain'], $val['sub'], $val['type'], $val['value']);
@ -492,7 +493,6 @@ class m_dom {
if ($result === false) {
throw new Exception("Could not read data from {$url}");
return false;
}
if (strstr($http_response_header[0], '301') || strstr($http_response_header[0], '302')) {
// This is a redirection
@ -528,7 +528,7 @@ class m_dom {
}
function domains_type_get($name) {
global $db, $err, $cuid;
global $db;
$name = mysql_real_escape_string($name);
$db->query("select * from domaines_type where name='$name' ;");
$db->next_record();
@ -536,14 +536,14 @@ class m_dom {
}
function domains_type_del($name) {
global $db, $err, $cuid;
global $db;
$name = mysql_real_escape_string($name);
$db->query("delete domaines_type where name='$name';");
return true;
}
function domains_type_update($name, $description, $target, $entry, $compatibility, $enable, $only_dns, $need_dns, $advanced, $create_tmpdir, $create_targetdir) {
global $err, $cuid, $db;
global $err, $db;
// The name MUST contain only letter and digits, it's an identifier after all ...
if (!preg_match("#^[a-z0-9]+$#", $name)) {
$err->raise("dom", _("The name MUST contain only letter and digits"));
@ -565,12 +565,13 @@ class m_dom {
}
function sub_domain_change_status($sub_id, $status) {
global $db, $err, $cuid;
global $db, $err;
$err->log("dom", "sub_domain_change_status");
$sub_id = intval($sub_id);
$status = strtoupper($status);
if (!in_array($status, array('ENABLE', 'DISABLE')))
if (!in_array($status, array('ENABLE', 'DISABLE'))) {
return false;
}
$jh = $this->get_sub_domain_all($sub_id);
if ($status == 'ENABLE') { // check compatibility with existing sub_domains
@ -618,9 +619,7 @@ class m_dom {
$dom = strtolower($dom);
$db->query("UPDATE sub_domaines SET web_action='UPDATE' WHERE domaine='$dom';");
$this->set_dns_action($dom, 'UPDATE');
# TODO : some work with domain sensitive classes
return true;
}
@ -638,7 +637,7 @@ class m_dom {
* @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
*/
function del_domain($dom) {
global $db, $err, $classes, $cuid, $hooks;
global $db, $err, $hooks;
$err->log("dom", "del_domain", $dom);
$dom = strtolower($dom);
@ -689,7 +688,7 @@ class m_dom {
$ @return boolean Retourne FALSE si une erreur s'est produite, TRUE sinon.
*/
function add_domain($domain, $dns, $noerase = false, $force = false, $isslave = false, $slavedom = "") {
global $db, $err, $quota, $classes, $L_MX, $L_FQDN, $tld, $cuid, $bro, $hooks;
global $db, $err, $quota, $L_FQDN, $tld, $cuid, $hooks;
$err->log("dom", "add_domain", $domain);
// Locked ?
@ -740,14 +739,15 @@ class m_dom {
return false;
}
if ($dns)
if ($dns) {
$dns = "1";
else
} else {
$dns = "0";
}
// mode 5 : force DNS to NO.
if ($tld[$v] == 5)
if ($tld[$v] == 5) {
$dns = 0;
}
// It must be a real domain (no subdomain)
if (!$dns) {
$v = checkhostallow_nodns($domain);
@ -762,14 +762,16 @@ class m_dom {
$err->raise("dom", _("Your domain quota is over, you cannot create more domain names"));
return false;
}
if ($noerase)
if ($noerase) {
$noerase = "1";
else
} else {
$noerase = "0";
if ($dns)
}
if ($dns) {
$gesmx = "1";
else
} else {
$gesmx = "0"; // do not host mx by default if not hosting the DNS
}
$db->query("INSERT INTO domaines (compte,domaine,gesdns,gesmx,noerase,dns_action) VALUES ('$cuid','$domain','$dns','$gesmx','$noerase','UPDATE');");
if (!($id = $db->lastid())) {
$err->raise("dom", _("An unexpected error occured when creating the domain"));
@ -798,8 +800,9 @@ class m_dom {
}
// New Hooks:
$hooks->invoke("hook_dom_add_domain", array($id));
if ($gesmx)
if ($gesmx) {
$hooks->invoke("hook_dom_add_mx_domain", array($id));
}
if ($isslave) {
$hooks->invoke("hook_dom_add_slave_domain", array($id, $slavedom));
}
@ -834,13 +837,11 @@ class m_dom {
* @param string $domain
*/
function domdefaultdir($domain) {
global $bro, $cuid;
$dest_root = $bro->get_userid_root($cuid);
# return $dest_root."/www/".$this->domshort($domain);
return "/www/" . $this->domshort($domain);
}
function dump_axfr($domain, $ns = 'localhost') {
$axfr = array();
exec('/usr/bin/dig AXFR "' . escapeshellcmd($domain) . '" @"' . escapeshellcmd($ns) . '"', $axfr);
return $axfr;
}
@ -869,12 +870,14 @@ class m_dom {
$err->log("dom", "update_default_subdomains");
$ok = true;
foreach ($arr as $a) {
if (!isset($a['id']))
if (!isset($a['id'])) {
$a['id'] = null;
}
if (!empty($a['sub']) || !empty($a['domain_type_parameter'])) {
if (!isset($a['enabled']))
if (!isset($a['enabled'])) {
$a['enabled'] = 0;
}
if (!$this->update_one_default($a['domain_type'], $a['sub'], $a['domain_type_parameter'], $a['concerned'], $a['enabled'], $a['id'])) {
$ok = false;
}
@ -887,10 +890,11 @@ class m_dom {
global $db, $err;
$err->log("dom", "update_one_default");
if ($id == null)
if ($id == null) {
$db->query("INSERT INTO default_subdomains values ('','" . addslashes($sub) . "','" . addslashes($domain_type) . "','" . addslashes($domain_type_parameter) . "','" . addslashes($concerned) . "','" . addslashes($enabled) . "');");
else
} else {
$db->query("UPDATE default_subdomains set sub='" . addslashes($sub) . "', domain_type='" . addslashes($domain_type) . "',domain_type_parameter='" . addslashes($domain_type_parameter) . "',concerned='" . addslashes($concerned) . "',enabled='" . addslashes($enabled) . "' where id=" . addslashes($id) . ";");
}
return true;
//update
}
@ -924,7 +928,7 @@ class m_dom {
*
*/
function whois($domain) {
global $db, $err;
global $err;
$err->log("dom", "whois", $domain);
// pour ajouter un nouveau TLD, utiliser le code ci-dessous.
// echo "whois : $domain<br />";
@ -978,16 +982,19 @@ class m_dom {
if (preg_match("#Name Server:#", $ligne)) {
$found = true;
$tmp = strtolower(str_replace(chr(10), "", str_replace(chr(13), "", str_replace(" ", "", str_replace("Name Server:", "", $ligne)))));
if ($tmp)
if ($tmp) {
$serveurList[] = $tmp;
}
}
break;
case "cx":
$ligne = str_replace(chr(10), "", str_replace(chr(13), "", str_replace(" ", "", $ligne)));
if ($ligne == "" && $state == 1)
if ($ligne == "" && $state == 1) {
$state = 2;
if ($state == 1)
}
if ($state == 1) {
$serveurList[] = strtolower($ligne);
}
if ($ligne == "Nameservers:" && $state == 0) {
$state = 1;
$found = true;
@ -996,10 +1003,12 @@ class m_dom {
case "eu":
case "be":
$ligne = preg_replace("/^ *([^ ]*) \(.*\)$/", "\\1", trim($ligne));
if ($found)
if ($found) {
$tmp = trim($ligne);
if ($tmp)
}
if ($tmp) {
$serveurList[] = $tmp;
}
if ($ligne == "Nameservers:") {
$state = 1;
$found = true;
@ -1011,26 +1020,29 @@ class m_dom {
// weird regexp (trailing garbage after name server), but I could not make it work otherwise
$tmp = strtolower(preg_replace('/Name Server: ([^ ]+)\..$/', "\\1", $ligne));
$tmp = preg_replace('/[^-_a-z0-9\.]/', '', $tmp);
if ($tmp)
if ($tmp) {
$serveurList[] = $tmp;
}
}
break;
case "it":
if (preg_match("#nserver:#", $ligne)) {
$found = true;
$tmp = strtolower(preg_replace("/nserver:\s*[^ ]*\s*([^\s]*)$/", "\\1", $ligne));
if ($tmp)
if ($tmp) {
$serveurList[] = $tmp;
}
}
break;
case "fr":
case "re":
if (preg_match("#nserver:#", $ligne)) {
$found = true;
$tmp = strtolower(preg_replace("#nserver:\s*([^\s]*)\s*.*$#", "\\1", $ligne));
if ($tmp)
if ($tmp) {
$serveurList[] = $tmp;
}
}
break;
case "ca":
case "ws";
@ -1082,6 +1094,8 @@ class m_dom {
function checkmx($domaine, $ref_domain = '') {
global $L_DEFAULT_MX, $L_DEFAULT_SECONDARY_MX;
$ref_mx = array();
$mxhosts = array();
if (!empty($ref_domain)) {
getmxrr($ref_domain, $ref_mx);
} else {
@ -1114,9 +1128,6 @@ class m_dom {
return 0;
}
//checkmx
/* ----------------------------------------------------------------- */
/**
@ -1245,7 +1256,7 @@ class m_dom {
* @param string $value
*/
function check_type_value($type, $value) {
global $db, $err, $cuid;
global $err;
// check the type we can have in domaines_type.target
switch ($this->domains_type_target_values($type)) {
@ -1273,7 +1284,6 @@ class m_dom {
return false;
}
return true;
break;
case 'IP':
if (checkip($value)) {
return true;
@ -1309,14 +1319,10 @@ class m_dom {
default:
$err->raise("dom", _("Invalid domain type selected, please check"));
return false;
break;
}
return false;
}
//check_type_value
/* ----------------------------------------------------------------- */
/**
@ -1328,13 +1334,14 @@ class m_dom {
* @return boolean tell you if the subdomain can be installed there
*/
function can_create_subdomain($dom, $sub, $type, $sub_domain_id = 'null') {
global $db, $err, $cuid;
global $db, $err;
$err->log("dom", "can_create_subdomain", $dom . "/" . $sub);
// Get the compatibility list for this domain type
$db->query("select upper(compatibility) as compatibility from domaines_type where upper(name)=upper('$type');");
if (!$db->next_record())
if (!$db->next_record()) {
return false;
}
$compatibility_lst = explode(",", $db->f('compatibility'));
// Get the list of type of subdomains already here who have the same name
@ -1342,9 +1349,10 @@ class m_dom {
#$db->query("select * from sub_domaines where sub='$sub' and domaine='$dom';");
while ($db->next_record()) {
// And if there is a domain with a incompatible type, return false
if (!in_array(strtoupper($db->f('type')), $compatibility_lst))
if (!in_array(strtoupper($db->f('type')), $compatibility_lst)) {
return false;
}
}
// All is right, go ! Create ur domain !
return true;
@ -1393,7 +1401,7 @@ class m_dom {
}
// On a épuré $dir des problémes eventuels ... On est en DESSOUS du dossier de l'utilisateur.
if ($t = checkfqdn($dom)) {
if (($t = checkfqdn($dom))) {
$err->raise("dom", _("The domain name is syntaxically incorrect"));
return false;
}
@ -1415,7 +1423,7 @@ class m_dom {
// Create TMP dir and TARGET dir if needed by the domains_type
$dest_root = $bro->get_userid_root($cuid);
$domshort = $this->domshort($dom, $sub);
//$domshort = $this->domshort($dom, $sub);
$db->query("select create_tmpdir, create_targetdir from domaines_type where name = '$type';");
$db->next_record();
if ($db->f('create_tmpdir')) {
@ -1444,9 +1452,6 @@ class m_dom {
return true;
}
// set_sub_domain
/* ----------------------------------------------------------------- */
/**
@ -1456,7 +1461,7 @@ class m_dom {
*
*/
function del_sub_domain($sub_domain_id) {
global $db, $err, $cuid;
global $db, $err;
$err->log("dom", "del_sub_domain", $sub_domain_id);
// Locked ?
if (!$this->islocked) {
@ -1473,8 +1478,6 @@ class m_dom {
return true;
}
// del_sub_domain
/**
* @param integer $dom_id
*/
@ -1505,7 +1508,7 @@ class m_dom {
*
*/
function edit_domain($dom, $dns, $gesmx, $force = false, $ttl = 86400) {
global $db, $err, $L_MX, $classes, $cuid, $hooks;
global $db, $err, $hooks;
$err->log("dom", "edit_domain", $dom . "/" . $dns . "/" . $gesmx);
// Locked ?
if (!$this->islocked && !$force) {
@ -1544,8 +1547,9 @@ class m_dom {
$err->raise("dom", _("The domain name %s does not exist"), $dom);
return false;
}
if ($dns != "1")
if ($dns != "1") {
$dns = "0";
}
// On vérifie que des modifications ont bien eu lieu :)
if ($r["dns"] == $dns && $r["mail"] == $gesmx && $r["zonettl"] == $ttl) {
$err->raise("dom", _("No change has been requested..."));
@ -1579,14 +1583,10 @@ class m_dom {
return true;
}
// edit_domain
/* * ************************* */
/* Slave dns ip managment */
/* * ************************* */
/* ----------------------------------------------------------------- */
/** Return the list of ip addresses and classes that are allowed access to domain list
@ -1616,8 +1616,9 @@ class m_dom {
return false;
}
$class = intval($class);
if ($class < 8 || $class > 32)
if ($class < 8 || $class > 32) {
$class = 32;
}
$db->query("SELECT * FROM slaveip WHERE ip='$ip' AND class='$class';");
if ($db->next_record()) {
$err->raise("err", _("The requested domain is forbidden in this server, please contact the administrator"));
@ -1652,7 +1653,7 @@ class m_dom {
/** Check for a slave account
*/
function check_slave_account($login, $pass) {
global $db, $err;
global $db;
$db->query("SELECT * FROM slaveaccount WHERE login='$login' AND pass='$pass';");
if ($db->next_record()) {
return true;
@ -1665,7 +1666,7 @@ class m_dom {
/** Out (echo) the complete hosted domain list :
*/
function echo_domain_list($integrity = false) {
global $db, $err;
global $db;
$db->query("SELECT domaine FROM domaines WHERE gesdns=1 ORDER BY domaine");
$tt = "";
while ($db->next_record()) {
@ -1684,7 +1685,7 @@ class m_dom {
/** Returns the complete hosted domain list :
*/
function get_domain_list($uid = -1) {
global $db, $err;
global $db;
$uid = intval($uid);
$res = array();
$sql = "";
@ -1703,7 +1704,7 @@ class m_dom {
* @return array
*/
function get_domain_all_summary() {
global $db, $err;
global $db;
$res = array();
$db->query("SELECT domaine, gesdns, gesmx, dns_action, zonettl FROM domaines ORDER BY domaine");
while ($db->next_record()) {
@ -1770,7 +1771,7 @@ class m_dom {
/** Count all domains, for all users
*/
function count_domains_all() {
global $db, $err, $cuid;
global $db;
$db->query("SELECT COUNT(*) AS count FROM domaines;");
if ($db->next_record()) {
return $db->f('count');
@ -1784,14 +1785,15 @@ class m_dom {
/** Return the list of allowed slave accounts
*/
function enum_slave_account() {
global $db, $err;
global $db;
$db->query("SELECT * FROM slaveaccount;");
$res = array();
while ($db->next_record()) {
$res[] = $db->Record;
}
if (!count($res))
if (!count($res)) {
return false;
}
return $res;
}
@ -1831,7 +1833,7 @@ class m_dom {
* @access private
*/
function lock() {
global $db, $err;
global $err;
$err->log("dom", "lock");
if ($this->islocked) {
$err->raise("dom", _("--- Program error --- Lock already obtained!"));
@ -1850,7 +1852,7 @@ class m_dom {
* @access private
*/
function unlock() {
global $db, $err;
global $err;
$err->log("dom", "unlock");
if (!$this->islocked) {
$err->raise("dom", _("--- Program error --- No lock on the domains!"));
@ -1914,10 +1916,10 @@ class m_dom {
* No parameters needed
* */
function alternc_export_conf() {
global $db, $err;
global $err;
$err->log("dom", "export");
$this->enum_domains();
$str="";
$str = "";
foreach ($this->domains as $d) {
$str.= " <domaines>\n";
$str.=" <nom>" . $d . "</nom>\n";
@ -1975,6 +1977,7 @@ class m_dom {
if ($only_apache) {
$params.=" and dt.only_dns is false ";
}
// BUG BUG BUG FIXME
// Suppression de comptes -> membres existe pas -> domaines a supprimer ne sont pas lister
$db->query("
@ -2017,8 +2020,9 @@ order by
global $dom;
$d = array();
foreach ($dom->domains_type_lst() as $k => $v) {
if ($v['only_dns'] == true)
if ($v['only_dns'] == true) {
continue;
}
if (!$j = file_get_contents(ALTERNC_APACHE2_GEN_TMPL_DIR . '/' . strtolower($k) . '.conf')) {
die("Error: missing file for $k");
}
@ -2030,9 +2034,9 @@ order by
// Launch old fashionned hooks as there was in AlternC 1.0
function generate_conf_oldhook($action, $lst_sub, $sub_obj = null) {
if (is_null($sub_obj))
if (is_null($sub_obj)) {
$sub_obj = $this->generation_parameters(null, false);
}
if (!isset($lst_sub[strtoupper($action)]) || empty($lst_sub[strtoupper($action)])) {
return false;
}
@ -2173,12 +2177,14 @@ order by
// by subdomain
$tmp = array();
foreach ($da['sub'] as $sub) {
if ($sub['web_action']!='OK') continue;
if ($sub['web_action'] != 'OK') {
continue;
}
if (!$sub['only_dns']) {
if (!isset($tmp[$sub['fqdn']])) {
$tmp[$sub['fqdn']] = 0;
}
$tmp[$sub['fqdn']]++;
$tmp[$sub['fqdn']] ++;
if ($tmp[$sub['fqdn']] >= 2) {
$errors[$sub['fqdn']] = sprintf(_("Problem on %s: there is more than 1 web configuration going to be generated for this sub-domain."), $sub['fqdn']);
}

View File

@ -1,4 +1,5 @@
<?php
/*
$Id: m_err.php,v 1.4 2004/05/19 14:23:06 benjamin Exp $
----------------------------------------------------------------------
@ -18,34 +19,35 @@
----------------------------------------------------------------------
Original Author of file: Benjamin Sonntag, Franck Missoum
----------------------------------------------------------------------
*/
*/
/**
* Classe de gestion des erreurs apparaissant lors d'appels API.
*
* <p>Cette classe gère les erreurs qui peuvent apparaitre lors d'appels
* à l'API d'AlternC. Ces erreurs sont stockées sous la forme de 2 nombres
* (Classe ID et Numéro d'erreur) ainsi qu'un texte facultatif associé.
* Des textes d'erreurs localisés sont aussi disponibles.</p>
* <p>Cette classe se charge aussi d'insérer les appels à l'API d'AlternC
* dans les logs du système dans /var/log/alternc/bureau.log
* </p>
* Copyleft {@link http://alternc.net/ AlternC Team}
*
* @copyright AlternC-Team 2002-11-01 http://alternc.net/
*/
* Classe de gestion des erreurs apparaissant lors d'appels API.
*
* <p>Cette classe gère les erreurs qui peuvent apparaitre lors d'appels
* à l'API d'AlternC. Ces erreurs sont stockées sous la forme de 2 nombres
* (Classe ID et Numéro d'erreur) ainsi qu'un texte facultatif associé.
* Des textes d'erreurs localisés sont aussi disponibles.</p>
* <p>Cette classe se charge aussi d'insérer les appels à l'API d'AlternC
* dans les logs du système dans /var/log/alternc/bureau.log
* </p>
* Copyleft {@link http://alternc.net/ AlternC Team}
*
* @copyright AlternC-Team 2002-11-01 http://alternc.net/
*/
class m_err {
/** Numero de classe d'erreur actuelle */
var $clsid=0;
var $clsid = 0;
/** Dernière erreur enregistrée par la classe */
var $error=0;
var $error = 0;
/** Paramètre chaine eventuellement associé à la dernière erreur */
var $param="";
var $param = "";
/** Emplacement du fichier de logs d'AlternC */
var $logfile="/var/log/alternc/bureau.log";
var $logfile = "/var/log/alternc/bureau.log";
/**
* Leve une erreur, signale celle-ci dans les logs et stocke le code erreur
@ -61,19 +63,19 @@ class m_err {
* @return boolean TRUE si l'erreur est connue, FALSE sinon.
*
*/
function raise($clsid,$error,$param="") {
/* Leve une exception. Si elle existe, sinon, stocke un message d'erreur sur erreur ...*/
if (_("err_".$clsid."_".$error)!="err_".$clsid."_".$error || is_string($error)) {
$this->clsid=$clsid;
$this->error=$error;
function raise($clsid, $error, $param = "") {
/* Leve une exception. Si elle existe, sinon, stocke un message d'erreur sur erreur ... */
if (_("err_" . $clsid . "_" . $error) != "err_" . $clsid . "_" . $error || is_string($error)) {
$this->clsid = $clsid;
$this->error = $error;
$args = func_get_args();
$this->param=array_slice($args, 2);
$this->param = array_slice($args, 2);
$this->logerr();
return true;
} else {
$this->clsid="err";
$this->error=1;
$this->param="Error # $error in Class $clsid, Value is $param. (sorry, no text for this error in your language at the moment)";
$this->clsid = "err";
$this->error = 1;
$this->param = "Error # $error in Class $clsid, Value is $param. (sorry, no text for this error in your language at the moment)";
$this->logerr();
return false;
}
@ -92,10 +94,10 @@ class m_err {
function errstr() {
if (is_string($this->error)) {
// new way of handling errors: message directly in the class
$str = $this->error."\n";
$str = $this->error . "\n";
} else {
// old way: message in the locales files (ugly)
$str = _("err_".$this->clsid."_".$this->error)."\n";
$str = _("err_" . $this->clsid . "_" . $this->error) . "\n";
}
$args = $this->param;
if (is_array($args)) {
@ -117,7 +119,7 @@ class m_err {
*/
function logerr() {
global $mem;
@file_put_contents($this->logfile, date("d/m/Y H:i:s")." - ERROR - ".$mem->user["login"]." - ".$this->errstr(), FILE_APPEND );
@file_put_contents($this->logfile, date("d/m/Y H:i:s") . " - ERROR - " . $mem->user["login"] . " - " . $this->errstr(), FILE_APPEND);
}
/**
@ -132,11 +134,11 @@ class m_err {
* @return boolean TRUE si le log a été ajouté, FALSE sinon
*
*/
function log($clsid,$function,$param="") {
global $mem,$cuid;
return @file_put_contents($this->logfile,date("d/m/Y H:i:s")." - " .get_remote_ip(). " - CALL - ".$mem->user["login"]." - $clsid - $function - $param\n", FILE_APPEND );
function log($clsid, $function, $param = "") {
global $mem;
return @file_put_contents($this->logfile, date("d/m/Y H:i:s") . " - " . get_remote_ip() . " - CALL - " . $mem->user["login"] . " - $clsid - $function - $param\n", FILE_APPEND);
}
}; /* Classe m_err */
}
?>
/* Classe m_err */

View File

@ -1,29 +1,35 @@
<?php
/*---------------------------------------------------------------------------*/
/** Constructor
Classe d'export de compte Alternc.
Cette classe ce contente d'invoquer les fonctions d'exportation de configuration et de données d'un compte,
presentes dans les classes concernées.
/* --------------------------------------------------------------------------- */
/** Constructor
Classe d'export de compte Alternc.
Cette classe ce contente d'invoquer les fonctions d'exportation de configuration et de données d'un compte,
presentes dans les classes concernées.
*/
Class m_export {
function m_export() {
}
function export_conf(){
function export_conf() {
global $hooks;
$config=$hooks->invoke('alternc_export_conf');
$config = $hooks->invoke('alternc_export_conf');
return $config;
}
/** le repertoire de base est passé en paramettre puis en construit une arborescence de la forme
<dir>/<user>/<timestamp/ qui contiendra les dossier de dump html et sql
*/
function export_data($dir){
/** le repertoire de base est passé en paramettre puis en construit une arborescence de la forme
<dir>/<user>/<timestamp/ qui contiendra les dossier de dump html et sql
*/
function export_data($dir) {
global $hooks, $mem;
$hooks->invoke('alternc_export_data', Array($dir));
}
}// export Class end
}
// export Class end

View File

@ -1,4 +1,5 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
@ -21,31 +22,32 @@
----------------------------------------------------------------------
Purpose of file: Manage FTP accounts
----------------------------------------------------------------------
*/
*/
/**
* Classe de gestion des comptes FTP de l'hébergé.
*/
* FTP account management class
*/
class m_ftp {
var $srv_name;
/* ----------------------------------------------------------------- */
/**
* Constructeur
*/
function m_ftp() {
global $L_FQDN;
$this->srv_name = variable_get('ftp_human_name', $L_FQDN,'Human name for FTP server', array('desc'=>'Name','type'=>'string'));
$this->srv_name = variable_get('ftp_human_name', $L_FQDN, 'Human name for FTP server', array('desc' => 'Name', 'type' => 'string'));
}
/* ----------------------------------------------------------------- */
/**
* Password kind used in this class (hook for admin class)
*/
function alternc_password_policy() {
return array("ftp"=>"FTP accounts");
return array("ftp" => "FTP accounts");
}
function hook_menu() {
@ -58,11 +60,10 @@ class m_ftp {
'link' => 'toggle',
'pos' => 60,
'links' => array(),
) ;
);
if ( $quota->cancreate("ftp") ) {
$obj['links'][] =
array (
if ($quota->cancreate("ftp")) {
$obj['links'][] = array(
'ico' => 'images/new.png',
'txt' => _("Create a new ftp account"),
'url' => "ftp_edit.php?create=1",
@ -70,9 +71,8 @@ class m_ftp {
);
}
if ( $q['u'] > 0 ) { // if there are some FTP accounts
$obj['links'][] =
array (
if ($q['u'] > 0) { // if there are some FTP accounts
$obj['links'][] = array(
'txt' => _("FTP accounts list"),
'url' => "ftp_list.php"
);
@ -85,122 +85,130 @@ class m_ftp {
// in authip for more informations
function authip_class() {
$c = Array();
$c['name']="FTP";
$c['protocol']="ftp";
$c['values']=Array();
$c['name'] = "FTP";
$c['protocol'] = "ftp";
$c['values'] = Array();
$tt = $this->get_list();
if (empty($tt) || !is_array($tt)) return $c;
foreach ($this->get_list() as $v ) {
$c['values'][$v['id']]=$v['login'];
if (empty($tt) || !is_array($tt)) {
return $c;
}
foreach ($this->get_list() as $v) {
$c['values'][$v['id']] = $v['login'];
}
return $c;
}
// Switch enabled status of an account
function switch_enabled($id,$status=null) {
function switch_enabled($id, $status = null) {
global $cuid, $db, $err;
if (! $jj = $this->get_ftp_details($id)) {
if (!$jj = $this->get_ftp_details($id)) {
$err->raise('ftp', _("This account do not exist or is not of this account"));
return false;
}
if ( $status == null ){
if ($jj[0]['enabled'] == true ) { $status=0;}
else { $status=1; }
if ($status == null) {
if ($jj[0]['enabled'] == true) {
$status = 0;
} else {
$status = 1;
}
}
// Be sure what is in $status, in case of it was a parameter
$status = ($status?'true':'false');
$status = ($status ? 'true' : 'false');
if ( ! $db->query("UPDATE ftpusers SET enabled = $status WHERE uid = '$cuid' AND id = '$id' ;") ) {
if (!$db->query("UPDATE ftpusers SET enabled = $status WHERE uid = '$cuid' AND id = '$id' ;")) {
$err->raise('ftp', _("Error during update"));
return false;
} else {
return true ;
return true;
}
}
/* ----------------------------------------------------------------- */
/** Retourne la liste des comptes FTP du compte hébergé
* Retourne la liste des comptes FTP sous forme de tableau indexé de
/** Retourne la liste des comptes FTP du compte h<EFBFBD>berg<EFBFBD>
* Retourne la liste des comptes FTP sous forme de tableau index<EFBFBD> de
* tableaus associatifs comme suit :
* $a["id"]= ID du compte ftp
* $a["login"]= Nom de login du compte
* $a["dir"]= Dossier relatif à la racine du compte de l'utilisateur
* $a["dir"]= Dossier relatif <EFBFBD> la racine du compte de l'utilisateur
* @return array Retourne le tableau des comptes
*/
function get_list() {
global $db,$err,$cuid, $bro;
$err->log("ftp","get_list");
$r=array();
global $db, $err, $cuid;
$err->log("ftp", "get_list");
$r = array();
$db->query("SELECT id, name, homedir, enabled FROM ftpusers WHERE uid='$cuid' ORDER BY name;");
if ($db->num_rows()) {
while ($db->next_record()) {
$r[]=array(
"id"=>$db->f("id"),
"login"=>$db->f("name"),
"enabled"=>$db->f("enabled"),
$r[] = array(
"id" => $db->f("id"),
"login" => $db->f("name"),
"enabled" => $db->f("enabled"),
//"dir"=>$match[1]
"dir"=>$db->f("homedir")
"dir" => $db->f("homedir")
);
}
return $r;
} else {
$err->raise("ftp",_("No FTP account found"));
$err->raise("ftp", _("No FTP account found"));
return array();
}
}
/* ----------------------------------------------------------------- */
/** Retourne les détails d'un compte FTP (voir get_list)
* Le tableau est celui du compte d'id spécifié
* @param integer $id Numéro du compte dont on souhaite obtenir les détails
/** Retourne les details d'un compte FTP (voir get_list)
* Le tableau est celui du compte d'id specifie
* @param integer $id Numero du compte dont on souhaite obtenir les d<EFBFBD>tails
* @return array Tableau associatif contenant les infos du comptes ftp
*/
function get_ftp_details($id) {
global $db,$err,$cuid;
$err->log("ftp","get_ftp_details",$id);
$r=array();
global $db, $err, $cuid;
$err->log("ftp", "get_ftp_details", $id);
$r = array();
$db->query("SELECT id, name, homedir, enabled FROM ftpusers WHERE uid='$cuid' AND id='$id';");
if ($db->num_rows()) {
$db->next_record();
$regexp="/^".preg_quote(getuserpath(),"/")."\/(.*)$/";
preg_match($regexp, $db->f("homedir"),$match);
$regexp = "/^" . preg_quote(getuserpath(), "/") . "\/(.*)$/";
$match = array();
preg_match($regexp, $db->f("homedir"), $match);
$lg=explode("_",$db->f("name"));
if ((!is_array($lg)) || (count($lg)!=2)) {
$lg[0]=$db->f("name");
$lg[1]="";
$lg = explode("_", $db->f("name"));
if ((!is_array($lg)) || (count($lg) != 2)) {
$lg[0] = $db->f("name");
$lg[1] = "";
}
$r[]=array(
"id"=>$db->f("id"),
"prefixe"=> $lg[0],
"login"=>$lg[1],
"dir"=>$match[1],
"enabled"=>$db->f("enabled")
$r[] = array(
"id" => $db->f("id"),
"prefixe" => $lg[0],
"login" => $lg[1],
"dir" => $match[1],
"enabled" => $db->f("enabled")
);
return $r;
} else {
$err->raise("ftp",_("This FTP account does not exist"));
$err->raise("ftp", _("This FTP account does not exist"));
return false;
}
}
/* ----------------------------------------------------------------- */
/** Retourne la liste des prefixes utilisables par le compte courant
* @return array tableau contenant la liste des prefixes (domaines + login)
* du compte actuel.
*/
function prefix_list() {
global $db,$mem,$cuid;
$r=array();
$r[]=$mem->user["login"];
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");
$r[] = $db->f("domaine");
}
return $r;
}
@ -215,16 +223,16 @@ class m_ftp {
// special chars and the max numbers of them allowed
// to be able to give a specific error
$vv = array('_'=>'1', ' '=>0);
foreach ($vv as $k=>$n) {
if (substr_count($l, $k) > $n ) { // if there is more than $n $k
$vv = array('_' => '1', ' ' => 0);
foreach ($vv as $k => $n) {
if (substr_count($l, $k) > $n) { // if there is more than $n $k
$err->raise('ftp', sprintf(_("FTP login is incorrect: too many '%s'"), $k));
return false;
}
}
// Explicitly look for only allowed chars
if ( ! preg_match("/^[A-Za-z0-9]+[A-Za-z0-9_\.\-]*$/", $l) ) {
if (!preg_match("/^[A-Za-z0-9]+[A-Za-z0-9_\.\-]*$/", $l)) {
$err->raise('ftp', _("FTP login is incorrect"));
return false;
}
@ -232,97 +240,107 @@ class m_ftp {
}
/* ----------------------------------------------------------------- */
/** Affiche (ECHO) la liste des prefixes disponibles sous forme de champs d'option
* Les champs sont affichés sous la forme <option>prefixe</option>...
* La valeur $current se voit affublée de la balise SELECTED.
* @param string $current Prefixe sélectionné par faut
* Les champs sont affich<EFBFBD>s sous la forme <option>prefixe</option>...
* La valeur $current se voit affubl<EFBFBD>e de la balise SELECTED.
* @param string $current Prefixe s<EFBFBD>lectionn<EFBFBD> par d<EFBFBD>faut
* @return boolean TRUE.
*/
function select_prefix_list($current) {
$r=$this->prefix_list();
$r = $this->prefix_list();
reset($r);
while (list($key,$val)=each($r)) {
if ($current==$val) $c=" selected=\"selected\""; else $c="";
while (list($key, $val) = each($r)) {
if ($current == $val) {
$c = " selected=\"selected\"";
} else {
$c = "";
}
echo "<option$c>$val</option>";
}
return true;
}
/* ----------------------------------------------------------------- */
/** Modifie les paramètres du comptes FTP $id.
* @param integer $id Numéro du compte dont on veut modifier les paramètres
/** Modifie les param<EFBFBD>tres du comptes FTP $id.
* @param integer $id Num<EFBFBD>ro du compte dont on veut modifier les param<EFBFBD>tres
* @param string $prefixe Prefixe du compte FTP
* @param string $login login ajouté au préfixe ($prefixe_$login)
* @param string $login login ajout<EFBFBD> au pr<EFBFBD>fixe ($prefixe_$login)
* @param string $pass mot de passe
* @param string $dir Répertoire racine du compte
* @return boolean TRUE si le compte a été modifié, FALSE si une erreur est survenue.
* @param string $dir R<EFBFBD>pertoire racine du compte
* @return boolean TRUE si le compte a <EFBFBD>t<EFBFBD> modifi<EFBFBD>, FALSE si une erreur est survenue.
*/
function put_ftp_details($id,$prefixe,$login,$pass,$dir) {
global $mem,$db,$err,$bro,$cuid,$admin;
$err->log("ftp","put_ftp_details",$id);
function put_ftp_details($id, $prefixe, $login, $pass, $dir) {
global $db, $err, $bro, $cuid, $admin;
$err->log("ftp", "put_ftp_details", $id);
$db->query("SELECT count(*) AS cnt FROM ftpusers WHERE id='$id' and uid='$cuid';");
$db->next_record();
if (!$db->f("cnt")) {
$err->raise("ftp",_("This FTP account does not exist"));
$err->raise("ftp", _("This FTP account does not exist"));
return false;
}
$dir=$bro->convertabsolute($dir);
if (substr($dir,0,1)=="/") {
$dir=substr($dir,1);
$dir = $bro->convertabsolute($dir);
if (substr($dir, 0, 1) == "/") {
$dir = substr($dir, 1);
}
$r=$this->prefix_list();
if (!in_array($prefixe,$r)) {
$err->raise("ftp",_("The chosen prefix is not allowed"));
$r = $this->prefix_list();
if (!in_array($prefixe, $r)) {
$err->raise("ftp", _("The chosen prefix is not allowed"));
return false;
}
$full_login=$prefixe;
if ($login) $full_login.="_".$login;
if (! $this->check_login($full_login) ) return false;
$full_login = $prefixe;
if ($login) {
$full_login.="_" . $login;
}
if (!$this->check_login($full_login)) {
return false;
}
$db->query("SELECT COUNT(*) AS cnt FROM ftpusers WHERE id!='$id' AND name='$full_login';");
$db->next_record();
if ($db->f("cnt")) {
$err->raise("ftp",_("This FTP account already exists"));
$err->raise("ftp", _("This FTP account already exists"));
return false;
}
$absolute=getuserpath()."/$dir";
$absolute = getuserpath() . "/$dir";
if (!file_exists($absolute)) {
system("/bin/mkdir -p $absolute");
}
if (!is_dir($absolute)) {
$err->raise("ftp",_("The directory cannot be created"));
$err->raise("ftp", _("The directory cannot be created"));
return false;
}
if (trim($pass)) {
// Check this password against the password policy using common API :
if (is_callable(array($admin,"checkPolicy"))) {
if (!$admin->checkPolicy("ftp",$full_login,$pass)) {
if (is_callable(array($admin, "checkPolicy"))) {
if (!$admin->checkPolicy("ftp", $full_login, $pass)) {
return false; // The error has been raised by checkPolicy()
}
}
$encrypted_password = _md5cr($pass,strrev(microtime(true)));
$db->query("UPDATE ftpusers SET name='".$full_login."', password='', encrypted_password='$encrypted_password', homedir='$absolute', uid='$cuid' WHERE id='$id';");
$encrypted_password = _md5cr($pass, strrev(microtime(true)));
$db->query("UPDATE ftpusers SET name='" . $full_login . "', password='', encrypted_password='$encrypted_password', homedir='$absolute', uid='$cuid' WHERE id='$id';");
} else {
$db->query("UPDATE ftpusers SET name='".$full_login."', homedir='$absolute', uid='$cuid' WHERE id='$id';");
$db->query("UPDATE ftpusers SET name='" . $full_login . "', homedir='$absolute', uid='$cuid' WHERE id='$id';");
}
return true;
}
/* ----------------------------------------------------------------- */
/** Efface le compte ftp spécifié.
* @param integer $id Numéro du compte FTP à supprimer.
* @return boolean TRUE si le compte a été effacé, FALSE sinon.
/** Efface le compte ftp specifie
* @param integer $id Numero du compte FTP a supprimer.
* @return boolean TRUE si le compte a ete efface, FALSE sinon.
*/
function delete_ftp($id) {
global $db,$err,$cuid;
$err->log("ftp","delete_ftp",$id);
global $db, $err, $cuid;
$err->log("ftp", "delete_ftp", $id);
$db->query("SELECT name FROM ftpusers WHERE id='$id' and uid='$cuid';");
$db->next_record();
$name=$db->f("name");
$name = $db->f("name");
if (!$name) {
$err->raise("ftp",_("This FTP account does not exist"));
$err->raise("ftp", _("This FTP account does not exist"));
return false;
}
$db->query("DELETE FROM ftpusers WHERE id='$id'");
@ -330,77 +348,85 @@ class m_ftp {
}
/* ----------------------------------------------------------------- */
/** Crée un nouveau compte FTP.
/** Cree un nouveau compte FTP.
* @param string $prefixe Prefixe au login
* @param string $login Login ftp (login=prefixe_login)
* @param string $pass Mot de passe FTP
* @param string $dir Répertoire racine du compte relatif à la racine du membre
* @return boolean TRUE si le compte a été créé, FALSE sinon.
* @param string $dir Repertoire racine du compte relatif à la racine du membre
* @return boolean TRUE si le compte a ete cree, FALSE sinon.
*
*/
function add_ftp($prefixe,$login,$pass,$dir) {
global $mem,$db,$err,$quota,$bro,$cuid,$admin;
$err->log("ftp","add_ftp",$prefixe."_".$login);
$dir=$bro->convertabsolute($dir);
if (substr($dir,0,1)=="/") {
$dir=substr($dir,1);
function add_ftp($prefixe, $login, $pass, $dir) {
global $db, $err, $quota, $bro, $cuid, $admin;
$err->log("ftp", "add_ftp", $prefixe . "_" . $login);
$dir = $bro->convertabsolute($dir);
if (substr($dir, 0, 1) == "/") {
$dir = substr($dir, 1);
}
$r=$this->prefix_list();
$r = $this->prefix_list();
if (empty($pass)) {
$err->raise("ftp",_("Password can't be empty"));
$err->raise("ftp", _("Password can't be empty"));
return false;
}
if (!in_array($prefixe,$r) || $prefixe=="") {
$err->raise("ftp",_("The chosen prefix is not allowed"));
if (!in_array($prefixe, $r) || $prefixe == "") {
$err->raise("ftp", _("The chosen prefix is not allowed"));
return false;
}
$full_login=$prefixe;
if ($login) $full_login.="_".$login;
if ( !$this->check_login($full_login) ) return false;
$db->query("SELECT count(*) AS cnt FROM ftpusers WHERE name='".$full_login."'");
$full_login = $prefixe;
if ($login) {
$full_login.="_" . $login;
}
if (!$this->check_login($full_login)) {
return false;
}
$db->query("SELECT count(*) AS cnt FROM ftpusers WHERE name='" . $full_login . "'");
$db->next_record();
if ($db->f("cnt")) {
$err->raise("ftp",_("This FTP account already exists"));
$err->raise("ftp", _("This FTP account already exists"));
return false;
}
$db->query("SELECT login FROM membres WHERE uid='$cuid';");
$db->next_record();
$absolute=getuserpath()."/$dir";
$absolute = getuserpath() . "/$dir";
if (!file_exists($absolute)) {
system("/bin/mkdir -p $absolute"); // FIXME replace with action
}
if (!is_dir($absolute)) {
$err->raise("ftp",_("The directory cannot be created"));
$err->raise("ftp", _("The directory cannot be created"));
return false;
}
// Check this password against the password policy using common API :
if (is_callable(array($admin,"checkPolicy"))) {
if (!$admin->checkPolicy("ftp",$full_login,$pass)) {
if (is_callable(array($admin, "checkPolicy"))) {
if (!$admin->checkPolicy("ftp", $full_login, $pass)) {
return false; // The error has been raised by checkPolicy()
}
}
if ($quota->cancreate("ftp")) {
$encrypted_password = _md5cr($pass,strrev(microtime(true)));
$db->query("INSERT INTO ftpusers (name,password, encrypted_password,homedir,uid) VALUES ('".$full_login."', '', '$encrypted_password', '$absolute', '$cuid')");
$encrypted_password = _md5cr($pass, strrev(microtime(true)));
$db->query("INSERT INTO ftpusers (name,password, encrypted_password,homedir,uid) VALUES ('" . $full_login . "', '', '$encrypted_password', '$absolute', '$cuid')");
return true;
} else {
$err->raise("ftp",_("Your FTP account quota is over. You cannot create more ftp accounts"));
$err->raise("ftp", _("Your FTP account quota is over. You cannot create more ftp accounts"));
return false;
}
}
/* ----------------------------------------------------------------- */
/** Retourne TRUE si $dir possède un compte FTP
* @param string $dir Dossier à tester, relatif à la racine du compte courant
* @return boolean retourne TRUE si $dir à un compte FTP, FALSE sinon.
/** Retourne TRUE si $dir possee un compte FTP
* @param string $dir Dossier a tester, relatif a la racine du compte courant
* @return boolean retourne TRUE si $dir a un compte FTP, FALSE sinon.
*/
function is_ftp($dir) {
global $mem,$db,$err;
$err->log("ftp","is_ftp",$dir);
if (substr($dir,0,1)=="/") $dir=substr($dir,1);
$db->query("SELECT id FROM ftpusers WHERE homedir='".getuserpath()."/$dir';");
global $db, $err;
$err->log("ftp", "is_ftp", $dir);
if (substr($dir, 0, 1) == "/") {
$dir = substr($dir, 1);
}
$db->query("SELECT id FROM ftpusers WHERE homedir='" . getuserpath() . "/$dir';");
if ($db->num_rows()) {
$db->next_record();
return $db->f("id");
@ -410,29 +436,32 @@ class m_ftp {
}
/* ----------------------------------------------------------------- */
/** Fonction appellée par domains quand un domaine est supprimé pour le membre
* @param string $dom Domaine à détruire.
/** Fonction appellee par domains quand un domaine est supprime pour le membre
* @param string $dom Domaine à detruire.
* @access private
*/
function alternc_del_domain($dom) {
global $db,$err,$cuid;
$err->log("ftp","alternc_del_domain",$dom);
global $db, $err, $cuid;
$err->log("ftp", "alternc_del_domain", $dom);
$db->query("DELETE FROM ftpusers WHERE uid='$cuid' AND ( name LIKE '$dom\_%' OR name LIKE '$dom') ");
return true;
}
/* ----------------------------------------------------------------- */
/** Fonction appellée par membres quand un membre est effacé.
/** Fonction appellee par membres quand un membre est efface
* @access private
*/
function alternc_del_member() {
global $db,$err,$cuid;
$err->log("ftp","alternc_del_member");
global $db, $err, $cuid;
$err->log("ftp", "alternc_del_member");
$db->query("DELETE FROM ftpusers WHERE uid='$cuid'");
return true;
}
/* ----------------------------------------------------------------- */
/**
* Returns the used quota for the $name service for the current user.
* @param $name string name of the quota
@ -440,39 +469,39 @@ class m_ftp {
* @access private
*/
function hook_quota_get() {
global $db,$err,$cuid;
$err->log("ftp","getquota");
$q=Array("name"=>"ftp", "description"=>_("FTP accounts"), "used"=>0);
global $db, $err, $cuid;
$err->log("ftp", "getquota");
$q = Array("name" => "ftp", "description" => _("FTP accounts"), "used" => 0);
$db->query("SELECT COUNT(*) AS cnt FROM ftpusers WHERE uid='$cuid'");
if ($db->next_record()) {
$q['used']=$db->f("cnt");
$q['used'] = $db->f("cnt");
}
return $q;
}
/* ----------------------------------------------------------------- */
/**
* Exporte toutes les informations ftp du compte AlternC
* @access private
* EXPERIMENTAL 'sid' function ;)
*/
function alternc_export_conf() {
global $db,$err;
$err->log("ftp","export");
$f=$this->get_list();
$str=" <ftp>";
foreach ($f as $d=>$v) {
$str.=" <login>".($v["login"])."</login>\n";
$str.=" <password>".($v["encrypted_password"])."</password>\n";
$str.=" <directory>".($v["dir"])."<directory>\n";
global $db, $err;
$err->log("ftp", "export");
$f = $this->get_list();
$str = " <ftp>";
foreach ($f as $d => $v) {
$str.=" <login>" . ($v["login"]) . "</login>\n";
$str.=" <password>" . ($v["encrypted_password"]) . "</password>\n";
$str.=" <directory>" . ($v["dir"]) . "<directory>\n";
}
$str.=" </ftp>\n";
return $str;
}
/* ----------------------------------------------------------------- */
/** hook function called by AlternC-upnp to know which open
* tcp or udp ports this class requires or suggests
* @return array a key => value list of port protocol name mandatory values
@ -484,5 +513,6 @@ class m_ftp {
);
}
} /* Class m_ftp */
}
/* Class m_ftp */

View File

@ -1,4 +1,5 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
@ -21,7 +22,7 @@
----------------------------------------------------------------------
Purpose of file: Manage hook system.
----------------------------------------------------------------------
*/
*/
/**
* This class manage hooks.
@ -29,15 +30,17 @@
* @copyright AlternC-Team 2002-2005 http://alternc.org/
*/
class m_hooks {
/* --------------------------------------------------------------------------- */
/*---------------------------------------------------------------------------*/
/** Constructor
* hooks([$mid]) Constructeur de la classe hooks, ne fait rien pour le moment
*/
function m_hooks() {
}
/*---------------------------------------------------------------------------*/
/* --------------------------------------------------------------------------- */
/**
* invoke() permet de lancer une fonction donné en parametre dans toute les classes
* connues de alternc, avec les parametres donnés.
@ -66,9 +69,9 @@ class m_hooks {
$val = array();
foreach ($classes as $c) {
global $$c;
if ( method_exists($$c, $hname) ) {
if (method_exists($$c, $hname)) {
//$val[$$c]=call_user_func_array(array($$c,$hname), $hparam);
$val[$c]=call_user_func_array(array($$c,$hname), $hparam);
$val[$c] = call_user_func_array(array($$c, $hname), $hparam);
}
}
@ -76,25 +79,26 @@ class m_hooks {
return $val;
}
/*---------------------------------------------------------------------------*/
/* --------------------------------------------------------------------------- */
/**
* invoke each executable script of the directory (or the specified script)
* @param string $scripts a script or a directory
* @param array $parameters parameters for the scripts
* @return boolean TRUE
*/
function invoke_scripts($scripts, $parameters=array()) {
function invoke_scripts($scripts, $parameters = array()) {
// First, build the list of script we want to launch
$to_launch=array();
$to_launch = array();
if (is_file($scripts)) {
if (is_executable($scripts)) {
$to_launch[]=$scripts;
$to_launch[] = $scripts;
}
} else if (is_dir($scripts)) {
foreach ( scandir($scripts) as $ccc ) {
foreach (scandir($scripts) as $ccc) {
if (is_file($ccc) && is_executable($ccc)) {
$to_launch[]=$ccc;
$to_launch[] = $ccc;
}
}
} else {
@ -107,13 +111,15 @@ class m_hooks {
$params = implode(" ", $parameters);
// Launch !
foreach($to_launch as $fi) {
system($fi." ".$params);
foreach ($to_launch as $fi) {
system($fi . " " . $params);
}
// TODO: return something more interesting than true
return true;
}
} /* Class hooks */
}
/* Class hooks */

View File

@ -1,4 +1,5 @@
<?php
/*
$Id: m_hta.php,v 1.5 2004/11/29 17:15:37 anonymous Exp $
----------------------------------------------------------------------
@ -26,26 +27,25 @@
Original Author of file:
Purpose of file:
----------------------------------------------------------------------
*/
*/
/**
* This class handle folder web restricted access through .htaccess/.htpassword
* files.
*
* Copyleft {@link http://alternc.net/ AlternC Team}
*
* @copyright AlternC-Team 2002-11-01 http://alternc.org/
*
*/
* This class handle folder web restricted access through .htaccess/.htpassword
* files.
*
* Copyleft {@link http://alternc.net/ AlternC Team}
*
* @copyright AlternC-Team 2002-11-01 http://alternc.org/
*
*/
class m_hta {
/**
* Constructor
*/
function m_webaccess() {
}
}
/**
* Password kind used in this class (hook for admin class)
@ -53,7 +53,7 @@ class m_hta {
* @return array
*/
function alternc_password_policy() {
return array("hta"=>"Protected folders passwords");
return array("hta" => "Protected folders passwords");
}
/**
@ -66,12 +66,11 @@ class m_hta {
'ico' => 'images/password.png',
'link' => 'hta_list.php',
'pos' => 50,
) ;
);
return $obj;
}
/**
* Create a protected folder (.htaccess et .htpasswd)
* @param string $dir Folder to protect (relative to user root)
@ -84,34 +83,34 @@ class m_hta {
* @return boolean
*/
function CreateDir($dir) {
global $mem,$bro,$err;
$err->log("hta","createdir",$dir);
$absolute = $bro->convertabsolute($dir,0);
global $bro, $err;
$err->log("hta", "createdir", $dir);
$absolute = $bro->convertabsolute($dir, 0);
if (!$absolute) {
$err->raise("hta",printf(_("The folder '%s' does not exist"),$dir));
$err->raise("hta", printf(_("The folder '%s' does not exist"), $dir));
return false;
}
if (!file_exists($absolute)) {
@mkdir($absolute,00777);
@mkdir($absolute, 00777);
}
if (!file_exists("$absolute/.htaccess")) {
if (!@touch("$absolute/.htaccess")) {
$err->raise("hta",_("File already exist"));
$err->raise("hta", _("File already exist"));
return false;
}
$file = @fopen("$absolute/.htaccess","r+");
$file = @fopen("$absolute/.htaccess", "r+");
if (!$file) {
$err->raise("hta",_("File already exist"));
$err->raise("hta", _("File already exist"));
return false;
}
fseek($file,0);
$param = "AuthUserFile \"$absolute/.htpasswd\"\nAuthName \""._("Restricted area")."\"\nAuthType Basic\nrequire valid-user\n";
fseek($file, 0);
$param = "AuthUserFile \"$absolute/.htpasswd\"\nAuthName \"" . _("Restricted area") . "\"\nAuthType Basic\nrequire valid-user\n";
fwrite($file, $param);
fclose($file);
}
if (!file_exists("$absolute/.htpasswd")) {
if (!touch("$absolute/.htpasswd")) {
$err->raise("hta",_("File already exist"));
$err->raise("hta", _("File already exist"));
return false;
}
return true;
@ -119,7 +118,6 @@ class m_hta {
return true;
}
/**
* Returns the list of all user folder currently protected by a .htpasswd file
*
@ -127,23 +125,24 @@ class m_hta {
* @global m_mem $mem
* @return array Array containing user folder list
*/
function ListDir(){
global$err,$mem;
$err->log("hta","listdir");
function ListDir() {
global$err, $mem;
$err->log("hta", "listdir");
$sortie = array();
$absolute = ALTERNC_HTML."/".substr($mem->user["login"],0,1)."/".$mem->user["login"];
exec("find ".escapeshellarg($absolute)." -name .htpasswd|sort",$sortie);
if(!count($sortie)){
$err->raise("hta",_("No protected folder"));
$absolute = ALTERNC_HTML . "/" . substr($mem->user["login"], 0, 1) . "/" . $mem->user["login"];
exec("find " . escapeshellarg($absolute) . " -name .htpasswd|sort", $sortie);
if (!count($sortie)) {
$err->raise("hta", _("No protected folder"));
return false;
}
$pattern = "/^".preg_quote(ALTERNC_HTML,"/")."\/.\/[^\/]*\/(.*)\/\.htpasswd/";
$pattern = "/^" . preg_quote(ALTERNC_HTML, "/") . "\/.\/[^\/]*\/(.*)\/\.htpasswd/";
$r = array();
for($i = 0;$i<count($sortie);$i++){
preg_match($pattern,$sortie[$i],$matches);
$tmpm = isset($matches[1])?'/'.$matches[1]:'';
$r[$i] = $tmpm."/";
for ($i = 0; $i < count($sortie); $i++) {
$matches = array();
preg_match($pattern, $sortie[$i], $matches);
$tmpm = isset($matches[1]) ? '/' . $matches[1] : '';
$r[$i] = $tmpm . "/";
}
return $r;
}
@ -156,18 +155,17 @@ class m_hta {
* @param string $dir Folder to check
* @return boolean If the folder is protected, or FALSE if it is not
*/
function is_protected($dir){
global $mem,$err;
$err->log("hta","is_protected",$dir);
$absolute = ALTERNC_HTML."/".substr($mem->user["login"],0,1)."/".$mem->user["login"]."/$dir";
if (file_exists("$absolute/.htpasswd")){
function is_protected($dir) {
global $mem, $err;
$err->log("hta", "is_protected", $dir);
$absolute = ALTERNC_HTML . "/" . substr($mem->user["login"], 0, 1) . "/" . $mem->user["login"] . "/$dir";
if (file_exists("$absolute/.htpasswd")) {
return true;
} else {
return false;
}
}
/**
* Returns the list of login for a protected folder.
*
@ -177,15 +175,16 @@ class m_hta {
* @return array An array containing the list of logins from the .htpasswd file, or FALSE
*/
function get_hta_detail($dir) {
global $mem,$err;
$err->log("hta","get_hta_detail");
$absolute = ALTERNC_HTML."/".substr($mem->user["login"],0,1)."/".$mem->user["login"]."/$dir";
global $mem, $err;
$err->log("hta", "get_hta_detail");
$absolute = ALTERNC_HTML . "/" . substr($mem->user["login"], 0, 1) . "/" . $mem->user["login"] . "/$dir";
if (file_exists("$absolute/.htaccess")) {
/* if (!_reading_htaccess($absolute)) {
return false;
}
*/ }
$file = @fopen("$absolute/.htpasswd","r");
*/
}
$file = @fopen("$absolute/.htpasswd", "r");
$i = 0;
$res = array();
if (!$file) {
@ -193,18 +192,17 @@ class m_hta {
}
// TODO: Tester la validité du .htpasswd
while (!feof($file)) {
$s = fgets($file,1024);
$t = explode(":",$s);
if ($t[0]!=$s) {
$s = fgets($file, 1024);
$t = explode(":", $s);
if ($t[0] != $s) {
$res[$i] = $t[0];
$i = $i+1;
$i = $i + 1;
}
}
fclose($file);
return $res;
}
/**
* Unprotect a folder
*
@ -215,17 +213,17 @@ class m_hta {
* @param boolean $skip For testing purpose mainly, skips the full user path search
* @return boolean TRUE if the folder has been unprotected, or FALSE if an error occurred
*/
function DelDir($dir,$skip = false) {
global $mem,$bro,$err;
$err->log("hta","deldir",$dir);
$dir = $bro->convertabsolute($dir,$skip);
function DelDir($dir, $skip = false) {
global $bro, $err;
$err->log("hta", "deldir", $dir);
$dir = $bro->convertabsolute($dir, $skip);
if (!$dir) {
$err->raise("hta",printf(("The folder '%s' does not exist"),$dir));
$err->raise("hta", printf(("The folder '%s' does not exist"), $dir));
return false;
}
$htaccess_file = "$dir/.htaccess";
if( !is_readable($htaccess_file)){
$err->raise("hta",printf(_("I cannot read the file '%s'"),$htaccess_file));
if (!is_readable($htaccess_file)) {
$err->raise("hta", printf(_("I cannot read the file '%s'"), $htaccess_file));
}
$fileLines = file($htaccess_file);
$patternList = array(
@ -235,39 +233,37 @@ class m_hta {
"require valid-user.*$"
);
$count_lines = 0;
foreach($fileLines as $key => $line){
foreach ($fileLines as $key => $line) {
foreach ($patternList as $pattern) {
if(preg_match("/".$pattern."/", $line)){
if (preg_match("/" . $pattern . "/", $line)) {
$count_lines++;
unset($fileLines[$key]);
}
}
}
// If no changes
if( ! $count_lines ){
$err->raise("hta",printf(_("Unexpected: No changes made to '%s'"),$htaccess_file));
if (!$count_lines) {
$err->raise("hta", printf(_("Unexpected: No changes made to '%s'"), $htaccess_file));
}
// If file is empty, remove it
if( !count($fileLines)){
if( ! unlink( $htaccess_file)){
$err->raise("hta",printf(_("I could not delete the file '%s'"),$htaccess_file));
if (!count($fileLines)) {
if (!unlink($htaccess_file)) {
$err->raise("hta", printf(_("I could not delete the file '%s'"), $htaccess_file));
}
}else{
file_put_contents($htaccess_file, implode("\n",$fileLines));
} else {
file_put_contents($htaccess_file, implode("\n", $fileLines));
}
$htpasswd_file = "$dir/.htpasswd";
if( ! is_writable($htpasswd_file)){
$err->raise("hta",printf(_("I cannot read the file '%s'"),$htpasswd_file));
}
else if ( ! unlink($htpasswd_file)) {
$err->raise("hta",printf(_("I cannot delete the file '%s/.htpasswd'"),$dir));
if (!is_writable($htpasswd_file)) {
$err->raise("hta", printf(_("I cannot read the file '%s'"), $htpasswd_file));
} else if (!unlink($htpasswd_file)) {
$err->raise("hta", printf(_("I cannot delete the file '%s/.htpasswd'"), $dir));
return false;
}
return true;
}
/**
* Add a user to a protected folder
*
@ -281,61 +277,58 @@ class m_hta {
* @param string $dir The folder we add it to (relative to user root).
* @return boolean TRUE if the user has been added, or FALSE if an error occurred
*/
function add_user($user,$password,$dir) {
function add_user($user, $password, $dir) {
global $err, $bro, $admin;
$err->log("hta","add_user",$user."/".$dir);
$err->log("hta", "add_user", $user . "/" . $dir);
if (empty($user)) {
$err->raise('hta',_("Please enter a user"));
$err->raise('hta', _("Please enter a user"));
return false;
}
if (empty($password)) {
$err->raise('hta',_("Please enter a password"));
$err->raise('hta', _("Please enter a password"));
return false;
}
$absolute = $bro->convertabsolute($dir,0);
$absolute = $bro->convertabsolute($dir, 0);
if (!file_exists($absolute)) {
$err->raise("hta",printf(("The folder '%s' does not exist"),$dir));
$err->raise("hta", printf(("The folder '%s' does not exist"), $dir));
return false;
}
// @todo delete cf!. functions.php checkloginemail definition
if (checkloginmail($user)){
if (checkloginmail($user)) {
// Check this password against the password policy using common API :
if (is_callable(array($admin,"checkPolicy"))) {
if (!$admin->checkPolicy("hta",$user,$password)) {
if (is_callable(array($admin, "checkPolicy"))) {
if (!$admin->checkPolicy("hta", $user, $password)) {
return false; // The error has been raised by checkPolicy()
}
}
$file = @fopen("$absolute/.htpasswd","a+");
$file = @fopen("$absolute/.htpasswd", "a+");
if (!$file) {
$err->raise("hta",_("File already exist"));
$err->raise("hta", _("File already exist"));
return false;
}
fseek($file,0);
fseek($file, 0);
while (!feof($file)) {
$s = fgets($file,1024);
$t = explode(":",$s);
if ($t[0]==$user) {
$err->raise("hta",_("The user '%s' already exist for this folder"),$user);
$s = fgets($file, 1024);
$t = explode(":", $s);
if ($t[0] == $user) {
$err->raise("hta", _("The user '%s' already exist for this folder"), $user);
return false;
}
}
fseek($file,SEEK_END);
if ( empty($t[1]) || substr($t[1],-1)!="\n") {
fwrite($file,"\n");
fseek($file, SEEK_END);
if (empty($t[1]) || substr($t[1], -1) != "\n") {
fwrite($file, "\n");
}
fwrite($file, "$user:"._md5cr($password)."\n");
fwrite($file, "$user:" . _md5cr($password) . "\n");
fclose($file);
return true;
} else {
$err->raise("hta",_("Please enter a valid username"));
$err->raise("hta", _("Please enter a valid username"));
return false;
}
}
/**
*/
/**
* Delete a user from a protected folder.
*
@ -345,28 +338,28 @@ class m_hta {
* @param string $dir The folder, relative to user root, where we want to delete users.
* @return boolean TRUE if users has been deleted, or FALSE if an error occurred.
*/
function del_user($lst,$dir) {
global $bro,$err;
$err->log("hta","del_user",$lst."/".$dir);
$absolute = $bro->convertabsolute($dir,0);
function del_user($lst, $dir) {
global $bro, $err;
$err->log("hta", "del_user", $lst . "/" . $dir);
$absolute = $bro->convertabsolute($dir, 0);
if (!file_exists($absolute)) {
$err->raise("hta",printf(_("The folder '%s' does not exist"),$dir));
$err->raise("hta", printf(_("The folder '%s' does not exist"), $dir));
return false;
}
touch("$absolute/.htpasswd.new");
$file = fopen("$absolute/.htpasswd","r");
$newf = fopen("$absolute/.htpasswd.new","a");
$file = fopen("$absolute/.htpasswd", "r");
$newf = fopen("$absolute/.htpasswd.new", "a");
if (!$file || !$newf) {
$err->raise("hta",_("File already exist"));
$err->raise("hta", _("File already exist"));
return false;
}
reset($lst);
fseek($file,0);
fseek($file, 0);
while (!feof($file)) {
$s = fgets($file,1024);
$t = explode(":",$s);
if (!in_array($t[0],$lst) && ($t[0]!="\n")) {
fseek($newf,0);
$s = fgets($file, 1024);
$t = explode(":", $s);
if (!in_array($t[0], $lst) && ($t[0] != "\n")) {
fseek($newf, 0);
fwrite($newf, "$s");
}
}
@ -377,55 +370,44 @@ class m_hta {
return true;
}
/**
* Change the password of a user in a protected folder
* @param string $user The users whose password should be changed
* @param string $newpass The new password of this user
* @param string $dir The folder, relative to user root, in which we will change a password
* @return boolean TRUE if the password has been changed, or FALSE if an error occurred
*/
/**
* Change the password of a user in a protected folder
*
* @global m_bro $bro
* @global m_err $err
* @global m_admin $admin
* @param string $user
* @param string $newpass
* @param string $dir
* @return boolean
*/
function change_pass($user,$newpass,$dir) {
global $bro,$err,$admin;
$err->log("hta","change_pass",$user."/".$dir);
$absolute = $bro->convertabsolute($dir,0);
function change_pass($user, $newpass, $dir) {
global $bro, $err, $admin;
$err->log("hta", "change_pass", $user . "/" . $dir);
$absolute = $bro->convertabsolute($dir, 0);
if (!file_exists($absolute)) {
$err->raise("hta",printf(_("The folder '%s' does not exist"),$dir));
$err->raise("hta", printf(_("The folder '%s' does not exist"), $dir));
return false;
}
// Check this password against the password policy using common API :
if (is_callable(array($admin,"checkPolicy"))) {
if (!$admin->checkPolicy("hta",$user,$newpass)) {
if (is_callable(array($admin, "checkPolicy"))) {
if (!$admin->checkPolicy("hta", $user, $newpass)) {
return false; // The error has been raised by checkPolicy()
}
}
touch("$absolute/.htpasswd.new");
$file = fopen("$absolute/.htpasswd","r");
$newf = fopen("$absolute/.htpasswd.new","a");
$file = fopen("$absolute/.htpasswd", "r");
$newf = fopen("$absolute/.htpasswd.new", "a");
if (!$file || !$newf) {
$err->raise("hta",_("File already exist"));
$err->raise("hta", _("File already exist"));
return false;
}
while (!feof($file)) {
$s = fgets($file,1024);
$t = explode(":",$s);
if ($t[0]!=$user) {
$s = fgets($file, 1024);
$t = explode(":", $s);
if ($t[0] != $user) {
fwrite($newf, "$s");
}
}
fwrite($newf, "$user:"._md5cr($newpass)."\n");
fwrite($newf, "$user:" . _md5cr($newpass) . "\n");
fclose($file);
fclose($newf);
unlink("$absolute/.htpasswd");
@ -433,7 +415,6 @@ class m_hta {
return true;
}
/**
* Check that a .htaccess file is valid (for authentication)
*
@ -444,39 +425,39 @@ class m_hta {
*/
private function _reading_htaccess($absolute) {
global $err;
$err->log("hta","_reading_htaccess",$absolute);
$file = fopen("$absolute/.htaccess","r+");
$lignes = array(1,1,1);
$err->log("hta", "_reading_htaccess", $absolute);
$file = fopen("$absolute/.htaccess", "r+");
$lignes = array(1, 1, 1);
$errr = 0;
if (!$file) {
return false;
}
while (!feof($file) && !$errr) {
$s = fgets($file,1024);
if (substr($s,0,12)!="RewriteCond " && substr($s,0,14)!="ErrorDocument " && substr($s,0,12)!="RewriteRule " && substr($s,0,14)!="RewriteEngine " && trim($s)!="") {
$s = fgets($file, 1024);
if (substr($s, 0, 12) != "RewriteCond " && substr($s, 0, 14) != "ErrorDocument " && substr($s, 0, 12) != "RewriteRule " && substr($s, 0, 14) != "RewriteEngine " && trim($s) != "") {
$errr = 1;
}
if (strtolower(trim($s))==strtolower("authuserfile $absolute/.htpasswd")) {
if (strtolower(trim($s)) == strtolower("authuserfile $absolute/.htpasswd")) {
$lignes[0] = 0;
$errr = 0;
} // authuserfile
if (strtolower(trim($s))=="require valid-user") {
if (strtolower(trim($s)) == "require valid-user") {
$lignes[1] = 0;
$errr = 0;
} //require
if (strtolower(trim($s))=="authtype basic") {
if (strtolower(trim($s)) == "authtype basic") {
$lignes[2] = 0;
$errr = 0;
} //authtype
} // Reading config file
fclose($file);
if ($errr || in_array(0,$lignes)) {
$err->raise("hta",_("An incompatible .htaccess file exists in this folder"));
if ($errr || in_array(0, $lignes)) {
$err->raise("hta", _("An incompatible .htaccess file exists in this folder"));
return false;
}
return true;
}
} /* CLASS m_hta */
}
/* CLASS m_hta */

View File

@ -1,4 +1,5 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
@ -21,102 +22,103 @@
----------------------------------------------------------------------
Purpose of file: Manage Log files for users
----------------------------------------------------------------------
*/
*/
/**
* Classe de gestion des erreurs apparaissant lors d'appels API.
*/
* Classe de gestion des erreurs apparaissant lors d'appels API.
*/
class m_log {
function m_log(){
function m_log() {
}
function list_logs_directory($dir){
global $cuid,$err;
$err->log("log","list_logs_directory");
function list_logs_directory($dir) {
global $cuid, $err;
$err->log("log", "list_logs_directory");
$c=array();
foreach( glob("${dir}/*log*") as $absfile) {
$c[]=array("name"=>basename($absfile),
"creation_date"=>date("F d Y H:i:s", filectime($absfile)),
$c = array();
foreach (glob("${dir}/*log*") as $absfile) {
$c[] = array("name" => basename($absfile),
"creation_date" => date("F d Y H:i:s", filectime($absfile)),
"mtime" => filemtime($absfile),
"filesize"=>filesize($absfile),
"downlink"=>urlencode(basename($absfile)),
"filesize" => filesize($absfile),
"downlink" => urlencode(basename($absfile)),
);
}
usort($c,"m_log::compare_logtime");
usort($c, "m_log::compare_logtime");
return $c;
}//list_logs
}
// Used by list_logs_directory to sort
private function compare_logname($a, $b) {
return strcmp($a['name'],$b['name']);
return strcmp($a['name'], $b['name']);
}
// Used by list_logs_directory to sort
private function compare_logtime($a, $b) {
return $b['mtime']-$a['mtime'];
return $b['mtime'] - $a['mtime'];
}
function hook_menu() {
$obj = array(
'title' => _("Logs"),
'ico' => 'images/logs.png',
'link' => 'logs_list.php',
'pos' => 130,
) ;
);
return $obj;
}
function list_logs_directory_all($dirs){
function list_logs_directory_all($dirs) {
global $err;
$err->log("log","get_logs_directory_all");
$c=array();
foreach($dirs as $dir=>$val){
$c[$dir]=$this->list_logs_directory($val);
$err->log("log", "get_logs_directory_all");
$c = array();
foreach ($dirs as $dir => $val) {
$c[$dir] = $this->list_logs_directory($val);
}
return $c;
}
function get_logs_directory(){
global $cuid,$mem,$err;
$err->log("log","get_logs_directory");
function get_logs_directory() {
global $cuid, $mem, $err;
$err->log("log", "get_logs_directory");
// Return an array to allow multiple directory in the future
if(defined('ALTERNC_LOGS_ARCHIVE')){
$c=array("dir"=>ALTERNC_LOGS_ARCHIVE."/".$cuid."-".$mem->user["login"]);
}else{
$c=array("dir"=>ALTERNC_LOGS."/".$cuid."-".$mem->user["login"]);
if (defined('ALTERNC_LOGS_ARCHIVE')) {
$c = array("dir" => ALTERNC_LOGS_ARCHIVE . "/" . $cuid . "-" . $mem->user["login"]);
} else {
$c = array("dir" => ALTERNC_LOGS . "/" . $cuid . "-" . $mem->user["login"]);
}
return $c;
}
function download_link($file){
global $err,$mem;
$err->log("log","download_link");
header("Content-Disposition: attachment; filename=".$file."");
function download_link($file) {
global $err;
$err->log("log", "download_link");
header("Content-Disposition: attachment; filename=" . $file . "");
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
$f=$this->get_logs_directory();
$ff=$f['dir']."/".basename($file);
$f = $this->get_logs_directory();
$ff = $f['dir'] . "/" . basename($file);
set_time_limit(0);
readfile($ff);
}
function tail($file,$lines=20) {
global $err,$mem;
$err->log("log","tail");
$lines=intval($lines); if ($lines<=0) $lines=20;
$f=$this->get_logs_directory();
$ff=$f['dir']."/".basename($file);
unset($out);
exec("tail -".$lines." ".escapeshellarg($ff),$out);
return implode("\n",$out);
function tail($file, $lines = 20) {
global $err;
$err->log("log", "tail");
$lines = intval($lines);
if ($lines <= 0) {
$lines = 20;
}
$f = $this->get_logs_directory();
$ff = $f['dir'] . "/" . basename($file);
$out=array();
exec("tail -" . $lines . " " . escapeshellarg($ff), $out);
return implode("\n", $out);
}
}
} // end class
// end class

View File

@ -22,17 +22,15 @@
----------------------------------------------------------------------
Purpose of file: Manage LXC-based virtual machine through an inetd-based protocol
----------------------------------------------------------------------
*/
*/
include_once(dirname(__FILE__) . '/vm.class.php');
/**
* Manage AlternC's virtual machine start/stop using our own inetd-based protocol.
*/
class m_lxc implements vm {
public $IP;
public $KEY;
public $PORT;
@ -40,46 +38,43 @@ class m_lxc implements vm {
public $TIMEOUT = 5;
public $error = array();
/**
* Constructor, initialize the class informations from AlternC's variables
*/
function m_lxc() {
$this->IP = variable_get('lxc_ip', '', "IP address of the Alternc's LXC server. If empty, no LXC server.", array('desc'=>'IP address','type'=>'ip'));
$this->PORT = variable_get('lxc_port', '6504', "Port of the Alternc's LXC server", array('desc'=>'Port','type'=>'integer'));
$this->KEY = variable_get('lxc_key', '', "Shared key with the Alternc's LXC server", array('desc'=>'Shared key','type'=>'string'));
$this->maxtime = variable_get('lxc_maxtime', '4', "How many hours do we allow to have a server before shutting it down", array('desc'=>'Max time','type'=>'integer'));
$this->IP = variable_get('lxc_ip', '', "IP address of the Alternc's LXC server. If empty, no LXC server.", array('desc' => 'IP address', 'type' => 'ip'));
$this->PORT = variable_get('lxc_port', '6504', "Port of the Alternc's LXC server", array('desc' => 'Port', 'type' => 'integer'));
$this->KEY = variable_get('lxc_key', '', "Shared key with the Alternc's LXC server", array('desc' => 'Shared key', 'type' => 'string'));
$this->maxtime = variable_get('lxc_maxtime', '4', "How many hours do we allow to have a server before shutting it down", array('desc' => 'Max time', 'type' => 'integer'));
}
/**
* HOOK: add the "Console Access" to AlternC's main menu
*/
function hook_menu() {
if ( empty($this->IP)) return ; // No menu if no server
if (empty($this->IP))
return; // No menu if no server
$obj = array(
'title' => _("Console access"),
'ico' => 'images/ssh.png',
'link' => 'vm.php',
'pos' => 95,
) ;
);
return $obj;
}
/**
* HOOK: remove VM history for AlternC account
*/
function hook_admin_del_member() {
global $db,$err,$cuid;
$err->log("lxc","alternc_del_member");
global $db, $err, $cuid;
$err->log("lxc", "alternc_del_member");
$db->query("DELETE FROM vm_history WHERE uid='$cuid'");
return true;
}
/**
* Send a message to a remote VM manager instance
* $params are the parameters to send as serialized data
@ -88,33 +83,34 @@ class m_lxc implements vm {
* or FALSE if an error occurred. In that case $error[] is set.
*/
private function sendMessage($params) {
global $L_FQDN,$hooks;
global $L_FQDN, $hooks;
$fp = @fsockopen($this->IP, $this->PORT, $errno, $errstr, $this->TIMEOUT);
if (!$fp) {
$this->error[] = 'Unable to connect';
return FALSE;
}
// Authenticate:
$params['server']=$L_FQDN;
$params['key']=$this->KEY;
$params['server'] = $L_FQDN;
$params['key'] = $this->KEY;
// MySQL Host for this user ?
$moreparams=$hooks->invoke("lxc_params",array($params));
foreach($moreparams as $p) {
foreach($p as $k=>$v)
$params[$k]=$v;
$moreparams = $hooks->invoke("lxc_params", array($params));
foreach ($moreparams as $p) {
foreach ($p as $k => $v) {
$params[$k] = $v;
}
}
$msg = serialize($params);
if (fwrite ($fp, $msg."\n") < 0) {
if (fwrite($fp, $msg . "\n") < 0) {
$this->error[] = 'Unable to send data';
return FALSE;
}
$resp = fgets($fp, 8192);
fclose ($fp);
fclose($fp);
$data = @unserialize($resp);
if (isset($data['error']) && $data['error']>0) {
if (isset($data['error']) && $data['error'] > 0) {
$this->error[] = $data['msg'];
return FALSE;
} else {
@ -122,7 +118,6 @@ class m_lxc implements vm {
}
}
/**
* START a Virtual Machine on the remote VM manager
* for user $login having hashed password $pass and uid $uid
@ -140,7 +135,7 @@ class m_lxc implements vm {
$pass = $pass ? $pass : $mem->user['pass'];
$uid = $uid ? $uid : $mem->user['uid'];
$msgg = array('action'=>'start', 'login'=>$login, 'pass' => $pass, 'uid'=> $uid);
$msgg = array('action' => 'start', 'login' => $login, 'pass' => $pass, 'uid' => $uid);
$msgg['mysql_host'] = $mysql->dbus->Host;
$res = $this->sendMessage($msgg);
@ -148,7 +143,7 @@ class m_lxc implements vm {
return $this->error;
} else {
$data = unserialize($res);
$error = (int)$data['error'];
$error = (int) $data['error'];
$hostname = $data['hostname'];
$msg = $data['msg'];
$date_start = 'NOW()';
@ -163,35 +158,35 @@ class m_lxc implements vm {
}
}
/**
*
*/
public function getvm($login = FALSE) {
global $db, $mem, $cuid;
global $mem;
$login = $login ? $login : $mem->user['login'];
$msgg = array('action'=>'get', 'login'=>$login);
$msgg = array('action' => 'get', 'login' => $login);
$res = $this->sendMessage($msgg);
if (!$res) return FALSE;
if (!$res) {
return FALSE;
}
return unserialize($res);
}
/**
* Stop the currently running VM
*/
public function stop() {
global $db, $mem;
$vm = $this->getvm();
if ($vm === FALSE)
if ($vm === FALSE) {
return FALSE;
if ($this->sendMessage(array('action' => 'stop', 'vm' => $vm['vm'])) === FALSE)
}
if ($this->sendMessage(array('action' => 'stop', 'vm' => $vm['vm'])) === FALSE) {
return FALSE;
}
return TRUE;
}
}
} // class m_lxc
// class m_lxc

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,5 @@
<?php
/*
$Id: m_mem.php,v 1.19 2006/01/12 08:04:43 anarcat Exp $
----------------------------------------------------------------------
@ -20,42 +21,47 @@
Purpose of file: Manage Login session on the virtual desktop and
member parameters
----------------------------------------------------------------------
*/
*/
/**
* This class manage user sessions in the web desktop.
*
* This class manage user sessions and administration in AlternC.
* @copyright AlternC-Team 2002-2005 http://alternc.org/
*
*/
* This class manage user sessions in the web desktop.
*
* This class manage user sessions and administration in AlternC.
* @copyright AlternC-Team 2002-2005 http://alternc.org/
*
*/
class m_mem {
/** Original uid for the temporary uid swapping (for administrators) */
var $olduid=0;
var $olduid = 0;
/** This array contains the Tableau contenant les champs de la table "membres" du membre courant
* Ce tableau est utilisable globalement par toutes les classes filles.
*/
var $user;
/** Tableau contenant les champs de la table "local" du membre courant
* Ce tableau est utilisable globalement par toutes les classes filles.
* Note : les champs de "local" sont spécifiques à l'bergeur.
* Note : les champs de "local" sont specifiques a l'hebergeur.
*/
var $local;
/* ----------------------------------------------------------------- */
/**
* Constructeur
*/
function m_mem() {
}
/* ----------------------------------------------------------------- */
/**
* Password kind used in this class (hook for admin class)
*/
function alternc_password_policy() {
return array("mem"=>"AlternC's account password");
return array("mem" => "AlternC's account password");
}
function hook_menu() {
@ -64,20 +70,22 @@ class m_mem {
'ico' => 'images/settings.png',
'link' => 'mem_param.php',
'pos' => 160,
) ;
);
return $obj;
}
/* ----------------------------------------------------------------- */
/** Check that the current user is an admnistrator.
* @return boolean TRUE if we are super user, or FALSE if we are not.
*/
function checkright() {
return ($this->user["su"]=="1");
return ($this->user["su"] == "1");
}
/* ----------------------------------------------------------------- */
/** Start a session in the web desktop. Check username and password.
* <b>Note : </b>If the user entered a bas password, the failure will be logged
* and told to the corresponding user on next successfull login.
@ -85,73 +93,82 @@ class m_mem {
* @param $password string User Password.
* @return boolean TRUE if the user has been successfully connected, or FALSE if an error occured.
*/
function login($username,$password,$restrictip=0,$authip_token=false) {
global $db,$err,$cuid,$authip,$admin;
$err->log("mem","login",$username);
function login($username, $password, $restrictip = 0, $authip_token = false) {
global $db, $err, $cuid, $authip;
$err->log("mem", "login", $username);
// $username=addslashes($username);
// $password=addslashes($password);
$db->query("select * from membres where login='$username';");
if ($db->num_rows()==0) {
$err->raise("mem",_("User or password incorrect"));
if ($db->num_rows() == 0) {
$err->raise("mem", _("User or password incorrect"));
return false;
}
$db->next_record();
if (_md5cr($password,$db->f("pass"))!=$db->f("pass")) {
$db->query("UPDATE membres SET lastfail=lastfail+1 WHERE uid='".$db->f("uid")."';");
$err->raise("mem",_("User or password incorrect"));
if (_md5cr($password, $db->f("pass")) != $db->f("pass")) {
$db->query("UPDATE membres SET lastfail=lastfail+1 WHERE uid='" . $db->f("uid") . "';");
$err->raise("mem", _("User or password incorrect"));
return false;
}
if (!$db->f("enabled")) {
$err->raise("mem",_("This account is locked, contact the administrator."));
$err->raise("mem", _("This account is locked, contact the administrator."));
return false;
}
$this->user=$db->Record;
$cuid=$db->f("uid");
$this->user = $db->Record;
$cuid = $db->f("uid");
if (panel_islocked() && $cuid != 2000) {
$err->raise("mem",_("This website is currently under maintenance, login is currently disabled."));
$err->raise("mem", _("This website is currently under maintenance, login is currently disabled."));
return false;
}
// AuthIP
$allowed_ip=false;
if ( $authip_token ) $allowed_ip = $this->authip_tokencheck($authip_token);
$allowed_ip = false;
if ($authip_token) {
$allowed_ip = $this->authip_tokencheck($authip_token);
}
$aga = $authip->get_allowed('panel');
foreach ($aga as $k=>$v ) {
if ( $authip->is_in_subnet(get_remote_ip(), $v['ip'], $v['subnet']) ) $allowed=true ;
foreach ($aga as $k => $v) {
if ($authip->is_in_subnet(get_remote_ip(), $v['ip'], $v['subnet'])) {
$allowed = true;
}
}
// Error if there is rules, the IP is not allowed and it's not in the whitelisted IP
if ( sizeof($aga)>1 && !$allowed_ip && !$authip->is_wl(get_remote_ip()) ) {
$err->raise("mem",_("Your IP isn't allowed to connect"));
if (sizeof($aga) > 1 && !$allowed_ip && !$authip->is_wl(get_remote_ip())) {
$err->raise("mem", _("Your IP isn't allowed to connect"));
return false;
}
// End AuthIP
if ($restrictip) {
$ip="'".get_remote_ip()."'";
} else $ip="''";
$ip = "'" . get_remote_ip() . "'";
} else {
$ip = "''";
}
/* Close sessions that are more than 2 days old. */
$db->query("DELETE FROM sessions WHERE DATE_ADD(ts,INTERVAL 2 DAY)<NOW();");
/* Delete old impersonation */
if ( isset($_COOKIE["oldid"]) ) setcookie('oldid','',0,'/');
if (isset($_COOKIE["oldid"])) {
setcookie('oldid', '', 0, '/');
}
/* Open the session : */
$sess=md5(uniqid(mt_rand()));
$_REQUEST["session"]=$sess;
$sess = md5(uniqid(mt_rand()));
$_REQUEST["session"] = $sess;
$db->query("insert into sessions (sid,ip,uid) values ('$sess',$ip,'$cuid');");
setcookie("session",$sess,0,"/");
$err->error=0;
setcookie("session", $sess, 0, "/");
$err->error = 0;
/* Fill in $local */
$db->query("SELECT * FROM local WHERE uid='$cuid';");
if ($db->num_rows()) {
$db->next_record();
$this->local=$db->Record;
$this->local = $db->Record;
}
return true;
}
/* ----------------------------------------------------------------- */
/** Start a session as another user from an administrator account.
* This function is not the same as su. setid connect the current user in the destination
* account (for good), and su allow any user to become another account for some commands only.
@ -161,63 +178,67 @@ class m_mem {
* @return boolean TRUE if the user has been successfully connected, FALSE else.
*/
function setid($id) {
global $db,$err,$cuid,$mysql,$quota;
$err->log("mem","setid",$id);
global $db, $err, $cuid, $mysql, $quota;
$err->log("mem", "setid", $id);
$db->query("select * from membres where uid='$id';");
if ($db->num_rows()==0) {
$err->raise("mem",_("User or password incorrect"));
if ($db->num_rows() == 0) {
$err->raise("mem", _("User or password incorrect"));
return false;
}
$db->next_record();
$this->user=$db->Record;
$cuid=$db->f("uid");
$this->user = $db->Record;
$cuid = $db->f("uid");
// And recreate the $db->dbus
$mysql->reload_dbus();
$ip=get_remote_ip();
$sess=md5(uniqid(mt_rand()));
$_REQUEST["session"]=$sess;
$ip = get_remote_ip();
$sess = md5(uniqid(mt_rand()));
$_REQUEST["session"] = $sess;
$db->query("insert into sessions (sid,ip,uid) values ('$sess','$ip','$cuid');");
setcookie("session",$sess,0,"/");
$err->error=0;
setcookie("session", $sess, 0, "/");
$err->error = 0;
/* Fill in $local */
$db->query("SELECT * FROM local WHERE uid='$cuid';");
if ($db->num_rows()) {
$db->next_record();
$this->local=$db->Record;
$this->local = $db->Record;
}
$quota->getquota('', true);
return true;
}
/* ----------------------------------------------------------------- */
/** Suite à la connexion de l'utilisateur, réinitialise ses paramètres de dernière connexion
/** Suite <EFBFBD> la connexion de l'utilisateur, r<EFBFBD>initialise ses param<EFBFBD>tres de derni<EFBFBD>re connexion
*/
function resetlast() {
global $db,$cuid;
$ip=addslashes(getenv("REMOTE_HOST"));
if (!$ip) $ip=addslashes(get_remote_ip());
global $db, $cuid;
$ip = addslashes(getenv("REMOTE_HOST"));
if (!$ip) {
$ip = addslashes(get_remote_ip());
}
$db->query("UPDATE membres SET lastlogin=NOW(), lastfail=0, lastip='$ip' WHERE uid='$cuid';");
}
function authip_token($bis=false) {
global $db,$cuid;
function authip_token($bis = false) {
global $db, $cuid;
$db->query("select pass from membres where uid='$cuid';");
$db->next_record();
$i=intval(time()/3600);
if ($bis) ++$i;
return md5("$i--".$db->f('pass'));
$i = intval(time() / 3600);
if ($bis) {
++$i;
}
return md5("$i--" . $db->f('pass'));
}
/**
* @param boolean $t
*/
function authip_tokencheck($t) {
if ($t==$this->authip_token() || $t==$this->authip_token(true) ) return true;
return false;
return ($t == $this->authip_token() || $t == $this->authip_token(true));
}
/* Faut finir de l'implémenter :) * /
/* Faut finir de l'implementer :) * /
function authip_class() {
global $cuid;
$c = Array();
@ -227,84 +248,87 @@ class m_mem {
return $c;
}
/* */
/* */
/* ----------------------------------------------------------------- */
/** Vérifie que la session courante est correcte (cookie ok et ip valide).
* Si besoin, et si réception des champs username & password, crée une nouvelle
* session pour l'utilisateur annoncé.
* Cette fonction doit être appellée à chaque page devant être authentifiée.
* et AVANT d'émettre des données. (un cookie peut être envoyé)
/** Verifie que la session courante est correcte (cookie ok et ip valide).
* Si besoin, et si reception des champs username & password, cree une nouvelle
* session pour l'utilisateur annonce.
* Cette fonction doit etre appellee a chaque page devant etre authentifiee.
* et AVANT d'emettre des donnees. (un cookie peut etre envoye)
* @global string $session Le cookie de session eventuel
* @global string $username/password le login/pass de l'utilisateur
* @return boolean TRUE si la session est correcte, FALSE sinon.
*/
function checkid() {
global $db,$err,$cuid,$restrictip,$authip;
global $db, $err, $cuid;
if (isset($_REQUEST["username"])) {
if ( empty($_REQUEST['password']) ) {
$err->raise("mem",_("Missing password"));
if (empty($_REQUEST['password'])) {
$err->raise("mem", _("Missing password"));
return false;
}
if ($_REQUEST["username"] && $_REQUEST["password"]) {
return $this->login($_REQUEST["username"],$_REQUEST["password"], (isset($_REQUEST["restrictip"])?$_REQUEST["restrictip"]:0) );
return $this->login($_REQUEST["username"], $_REQUEST["password"], (isset($_REQUEST["restrictip"]) ? $_REQUEST["restrictip"] : 0));
}
} // end isset
$_COOKIE["session"]=isset($_COOKIE["session"])?addslashes($_COOKIE["session"]):"";
if (strlen($_COOKIE["session"])!=32) {
$err->raise("mem",_("Identity lost or unknown, please login"));
$_COOKIE["session"] = isset($_COOKIE["session"]) ? addslashes($_COOKIE["session"]) : "";
if (strlen($_COOKIE["session"]) != 32) {
$err->raise("mem", _("Identity lost or unknown, please login"));
return false;
}
$ip=get_remote_ip();
$db->query("select uid,'$ip' as me,ip from sessions where sid='".$_COOKIE["session"]."'");
if ($db->num_rows()==0) {
$err->raise("mem",_("Session unknown, contact the administrator"));
$ip = get_remote_ip();
$db->query("select uid,'$ip' as me,ip from sessions where sid='" . $_COOKIE["session"] . "'");
if ($db->num_rows() == 0) {
$err->raise("mem", _("Session unknown, contact the administrator"));
return false;
}
$db->next_record();
if ($db->f("ip")) {
if ($db->f("me")!=$db->f("ip")) {
$err->raise("mem",_("IP address incorrect, please contact the administrator"));
if ($db->f("me") != $db->f("ip")) {
$err->raise("mem", _("IP address incorrect, please contact the administrator"));
return false;
}
}
$cuid=$db->f("uid");
$cuid = $db->f("uid");
if (panel_islocked() && $cuid != 2000) {
$err->raise("mem",_("This website is currently under maintenance, login is currently disabled."));
$err->raise("mem", _("This website is currently under maintenance, login is currently disabled."));
return false;
}
$db->query("select * from membres where uid='$cuid';");
$db->next_record();
$this->user=$db->Record;
$err->error=0;
$this->user = $db->Record;
$err->error = 0;
/* Remplissage de $local */
$db->query("SELECT * FROM local WHERE uid='$cuid';");
if ($db->num_rows()) {
$db->next_record();
$this->local=$db->Record;
$this->local = $db->Record;
}
return true;
}
/* ----------------------------------------------------------------- */
/** Change l'identité d'un utilisateur temporairement.
* @global string $uid Utilisateur dont on prends l'identité
/** Change l'identite d'un utilisateur temporairement.
* @global string $uid Utilisateur dont on prends l'identite
* @return TRUE si la session est correcte, FALSE sinon.
*/
function su($uid) {
global $cuid,$db,$err,$mysql;
if (!$this->olduid)
$this->olduid=$cuid;
global $cuid, $db, $err, $mysql;
if (!$this->olduid) {
$this->olduid = $cuid;
}
$db->query("select * from membres where uid='$uid';");
if ($db->num_rows()==0) {
$err->raise("mem",_("User or password incorrect"));
if ($db->num_rows() == 0) {
$err->raise("mem", _("User or password incorrect"));
return false;
}
$db->next_record();
$this->user=$db->Record;
$cuid=$db->f("uid");
$this->user = $db->Record;
$cuid = $db->f("uid");
// And recreate the $db->dbus
$mysql->reload_dbus();
@ -312,52 +336,54 @@ class m_mem {
}
/* ----------------------------------------------------------------- */
/** Retourne a l'identite d'origine de l'utilisateur apres su.
* @return boolean TRUE si la session est correcte, FALSE sinon.
*/
function unsu() {
global $cuid,$mysql;
if (!$this->olduid)
global $mysql;
if (!$this->olduid) {
return false;
}
$this->su($this->olduid);
$this->olduid=0;
$this->olduid = 0;
// And recreate the $db->dbus
$mysql->reload_dbus();
return true;
}
/* ----------------------------------------------------------------- */
/** Termine une session du bureau virtuel (logout)
* @return boolean TRUE si la session a bien été truite, FALSE sinon.
* @return boolean TRUE si la session a bien ete detruite, FALSE sinon.
*/
function del_session() {
global $db,$user,$err,$cuid,$classes,$hooks;
$_COOKIE["session"]=addslashes(isset($_COOKIE["session"])?$_COOKIE["session"]:'');
setcookie("session","",0,"/");
setcookie("oldid","",0,"/");
if ($_COOKIE["session"]=="") {
$err->error=0;
global $db, $user, $err, $cuid, $hooks;
$_COOKIE["session"] = addslashes(isset($_COOKIE["session"]) ? $_COOKIE["session"] : '');
setcookie("session", "", 0, "/");
setcookie("oldid", "", 0, "/");
if ($_COOKIE["session"] == "") {
$err->error = 0;
return true;
}
if (strlen($_COOKIE["session"])!=32) {
$err->raise("mem",_("Cookie incorrect, please accept the session cookie"));
if (strlen($_COOKIE["session"]) != 32) {
$err->raise("mem", _("Cookie incorrect, please accept the session cookie"));
return false;
}
$ip=get_remote_ip();
$db->query("select uid,'$ip' as me,ip from sessions where sid='".$_COOKIE["session"]."'");
if ($db->num_rows()==0) {
$err->raise("mem",_("Session unknown, contact the administrator"));
$ip = get_remote_ip();
$db->query("select uid,'$ip' as me,ip from sessions where sid='" . $_COOKIE["session"] . "'");
if ($db->num_rows() == 0) {
$err->raise("mem", _("Session unknown, contact the administrator"));
return false;
}
$db->next_record();
if ($db->f("me")!=$db->f("ip")) {
$err->raise("mem",_("IP address incorrect, please contact the administrator"));
if ($db->f("me") != $db->f("ip")) {
$err->raise("mem", _("IP address incorrect, please contact the administrator"));
return false;
}
$cuid=$db->f("uid");
$db->query("delete from sessions where sid='".$_COOKIE["session"]."';");
$err->error=0;
$cuid = $db->f("uid");
$db->query("delete from sessions where sid='" . $_COOKIE["session"] . "';");
$err->error = 0;
# Invoker le logout dans toutes les autres classes
/*
@ -375,80 +401,83 @@ class m_mem {
}
/* ----------------------------------------------------------------- */
/** Change le mot de passe de l'utilisateur courant.
* @param string $oldpass Ancien mot de passe.
* @param string $newpass Nouveau mot de passe
* @param string $newpass2 Nouveau mot de passe (à nouveau)
* @return boolean TRUE si le mot de passe a été changé, FALSE sinon.
* @param string $newpass2 Nouveau mot de passe (a nouveau)
* @return boolean TRUE si le mot de passe a ete change, FALSE sinon.
*/
function passwd($oldpass,$newpass,$newpass2) {
global $db,$err,$cuid,$admin;
$err->log("mem","passwd");
$oldpass=stripslashes($oldpass);
$newpass=stripslashes($newpass);
$newpass2=stripslashes($newpass2);
function passwd($oldpass, $newpass, $newpass2) {
global $db, $err, $cuid, $admin;
$err->log("mem", "passwd");
$oldpass = stripslashes($oldpass);
$newpass = stripslashes($newpass);
$newpass2 = stripslashes($newpass2);
if (!$this->user["canpass"]) {
$err->raise("mem",_("You are not allowed to change your password."));
$err->raise("mem", _("You are not allowed to change your password."));
return false;
}
if ($this->user["pass"]!=_md5cr($oldpass,$this->user["pass"])) {
$err->raise("mem",_("The old password is incorrect"));
if ($this->user["pass"] != _md5cr($oldpass, $this->user["pass"])) {
$err->raise("mem", _("The old password is incorrect"));
return false;
}
if ($newpass!=$newpass2) {
$err->raise("mem",_("The new passwords are differents, please retry"));
if ($newpass != $newpass2) {
$err->raise("mem", _("The new passwords are differents, please retry"));
return false;
}
$db->query("SELECT login FROM membres WHERE uid='$cuid';");
$db->next_record();
$login=$db->Record["login"];
if (!$admin->checkPolicy("mem",$login,$newpass)) {
$login = $db->Record["login"];
if (!$admin->checkPolicy("mem", $login, $newpass)) {
return false; // The error has been raised by checkPolicy()
}
$newpass=_md5cr($newpass);
$newpass = _md5cr($newpass);
$db->query("UPDATE membres SET pass='$newpass' WHERE uid='$cuid';");
$err->error=0;
$err->error = 0;
return true;
}
/* ----------------------------------------------------------------- */
/** Change les préférences administrateur d'un compte
/** Change les preferences administrateur d'un compte
* @param integer $admlist Mode de visualisation des membres (0=large 1=courte)
* @return boolean TRUE si les préférences ont été changées, FALSE sinon.
* @return boolean TRUE si les preferences ont ete changees, FALSE sinon.
*/
function adminpref($admlist) {
global $db,$err,$cuid;
$err->log("mem","admlist");
global $db, $err, $cuid;
$err->log("mem", "admlist");
if (!$this->user["su"]) {
$err->raise("mem",_("You must be a system administrator to do this."));
$err->raise("mem", _("You must be a system administrator to do this."));
return false;
}
$db->query("UPDATE membres SET admlist='$admlist' WHERE uid='$cuid';");
$err->error=0;
$err->error = 0;
return true;
}
/* ----------------------------------------------------------------- */
/** Envoie en mail le mot de passe d'un compte.
* <b>Note : </b>On ne peut demander le mot de passe qu'une seule fois par jour.
* TODO : Translate this mail into the localization program.
* TODO : Check this function's !
* @return boolean TRUE si le mot de passe a été envoyé avec succès, FALSE sinon.
* @return boolean TRUE si le mot de passe a ete envoye avec succes, FALSE sinon.
*/
function send_pass($login) {
global $err,$db,$L_HOSTING,$L_FQDN;
$err->log("mem","send_pass");
global $err, $db, $L_HOSTING, $L_FQDN;
$err->log("mem", "send_pass");
$db->query("SELECT * FROM membres WHERE login='$login';");
if (!$db->num_rows()) {
$err->raise("mem",_("This account is locked, contact the administrator."));
$err->raise("mem", _("This account is locked, contact the administrator."));
return false;
}
$db->next_record();
if (time()-$db->f("lastaskpass")<86400) {
$err->raise("mem",_("The new passwords are differents, please retry"));
if (time() - $db->f("lastaskpass") < 86400) {
$err->raise("mem", _("The new passwords are differents, please retry"));
return false;
}
$txt=sprintf(_("Hello,
$txt = sprintf(_("Hello,
You requested the modification of your password for your
account %s on %s
@ -467,33 +496,34 @@ If it happens again, please contact your server's Administrator.
Cordially.
"), $login, $L_HOSTING, $db->f("login"), $db->f("pass"));
mail($db->f("mail"),"Your password on $L_HOSTING",$txt,"From: postmaster@$L_FQDN\nReply-to: postmaster@$L_FQDN");
$db->query("UPDATE membres SET lastaskpass=".time()." WHERE login='$login';");
mail($db->f("mail"), "Your password on $L_HOSTING", $txt, "From: postmaster@$L_FQDN\nReply-to: postmaster@$L_FQDN");
$db->query("UPDATE membres SET lastaskpass=" . time() . " WHERE login='$login';");
return true;
}
/* ----------------------------------------------------------------- */
/** Change le mail d'un membre (première etape, envoi du CookiE)
/** Change le mail d'un membre (premiere etape, envoi du CookiE)
* TODO : insert this mail string into the localization system
* @param string $newmail Nouveau mail souhaité pour le membre.
* @return string le cookie si le mail a bien été envoyé, FALSE sinon
* @param string $newmail Nouveau mail souhaite pour le membre.
* @return string le cookie si le mail a bien ete envoye, FALSE sinon
*/
function ChangeMail1($newmail) {
global $err,$db,$L_HOSTING,$L_FQDN,$cuid;
$err->log("mem","changemail1",$newmail);
global $err, $db, $L_HOSTING, $L_FQDN, $cuid;
$err->log("mem", "changemail1", $newmail);
$db->query("SELECT * FROM membres WHERE uid='$cuid';");
if (!$db->num_rows()) {
$err->raise("mem",_("This account is locked, contact the administrator."));
$err->raise("mem", _("This account is locked, contact the administrator."));
return false;
}
$db->next_record();
// un cookie de 20 caractères pour le mail
$COOKIE=substr(md5(uniqid(rand(), true)),0,20);
// et de 6 pour la clé à entrer. ca me semble suffisant...
$KEY=substr(md5(uniqid(rand(), true)),0,6);
$link="https://$L_FQDN/mem_cm.php?usr=$cuid&cookie=$COOKIE";
$txt=sprintf(_("Hello,
// un cookie de 20 caract<63>res pour le mail
$COOKIE = substr(md5(uniqid(rand(), true)), 0, 20);
// et de 6 pour la cl<63> <20> entrer. ca me semble suffisant...
$KEY = substr(md5(uniqid(rand(), true)), 0, 6);
$link = "https://$L_FQDN/mem_cm.php?usr=$cuid&cookie=$COOKIE";
$txt = sprintf(_("Hello,
Someone (maybe you) requested an email's address modification of the account
%s on %s
@ -512,75 +542,77 @@ again, please contact your server's administrator.
Cordially.
"), $db->f("login"), $L_HOSTING, $link);
mail($newmail,"Email modification request on $L_HOSTING",$txt,"From: postmaster@$L_FQDN\nReply-to: postmaster@$L_FQDN");
// Supprime les demandes précédentes de ce compte !
mail($newmail, "Email modification request on $L_HOSTING", $txt, "From: postmaster@$L_FQDN\nReply-to: postmaster@$L_FQDN");
// Supprime les demandes pr<70>c<EFBFBD>dentes de ce compte !
$db->query("DELETE FROM chgmail WHERE uid='$cuid';");
$db->query("INSERT INTO chgmail (cookie,ckey,uid,mail,ts) VALUES ('$COOKIE','$KEY','$cuid','$newmail',".time().");");
$db->query("INSERT INTO chgmail (cookie,ckey,uid,mail,ts) VALUES ('$COOKIE','$KEY','$cuid','$newmail'," . time() . ");");
// Supprime les cookies de la veille :)
$lts=time()-86400;
$lts = time() - 86400;
$db->query("DELETE FROM chgmail WHERE ts<'$lts';");
return $KEY;
}
/* ----------------------------------------------------------------- */
/** Change le mail d'un membre (seconde etape, CookiE+clé = application)
* @param string $COOKIE Cookie envoyé par mail
* @param string $KEY clé affichée à l'écran
* @param integer $uid Utilisateur concerné (on est hors session)
* @return boolean TRUE si le mail a bien été modifié, FALSE sinon
/** Change le mail d'un membre (seconde etape, CookiE+cle = application)
* @param string $COOKIE Cookie envoye par mail
* @param string $KEY cle affichee a l'ecran
* @param integer $uid Utilisateur concerne (on est hors session)
* @return boolean TRUE si le mail a bien ete modifie, FALSE sinon
*/
function ChangeMail2($COOKIE,$KEY,$uid) {
global $err,$db,$L_HOSTING,$L_FQDN;
$err->log("mem","changemail2",$uid);
function ChangeMail2($COOKIE, $KEY, $uid) {
global $err, $db;
$err->log("mem", "changemail2", $uid);
$db->query("SELECT * FROM chgmail WHERE cookie='$COOKIE' and ckey='$KEY' and uid='$uid';");
if (!$db->num_rows()) {
$err->raise("mem",_("The information you entered is incorrect."));
$err->raise("mem", _("The information you entered is incorrect."));
return false;
}
$db->next_record();
// met à jour le compte :
$db->query("UPDATE membres SET mail='".$db->f("mail")."' WHERE uid='$uid';");
// met a jour le compte :
$db->query("UPDATE membres SET mail='" . $db->f("mail") . "' WHERE uid='$uid';");
$db->query("DELETE FROM chgmail WHERE uid='$uid';");
// Supprime les cookies de la veille :)
$lts=time()-86400;
$lts = time() - 86400;
$db->query("DELETE FROM chgmail WHERE ts<'$lts';");
return true;
}
/* ----------------------------------------------------------------- */
/** Modifie le paramètre d'aide en ligne (1/0)
/** Modifie le parametre d'aide en ligne (1/0)
* @param integer $show Faut-il (1) ou non (0) afficher l'aide en ligne
*/
function set_help_param($show) {
global $db,$err,$cuid;
$err->log("mem","set_help_param",$show);
global $db, $err, $cuid;
$err->log("mem", "set_help_param", $show);
$db->query("UPDATE membres SET show_help='$show' WHERE uid='$cuid';");
}
/* ----------------------------------------------------------------- */
/** Dit si l'aide en ligne est demandée
* @return boolean TRUE si l'aide en ligne est demandée, FALSE sinon.
/** Dit si l'aide en ligne est demandee
* @return boolean TRUE si l'aide en ligne est demandee, FALSE sinon.
*/
function get_help_param() {
return $this->user["show_help"];
}
/* ----------------------------------------------------------------- */
/** Affiche (echo) l'aide contextuelle
* @param integer $file Numéro de fichier d'aide à afficher.
* @return boolean TRUE si l'aide contextuelle a été trouvée, FALSE sinon
* @param integer $file Numero de fichier d'aide a afficher.
* @return boolean TRUE si l'aide contextuelle a ete trouvee, FALSE sinon
*/
function show_help($file,$force=false) {
global $err;
function show_help($file, $force = false) {
if ($this->user["show_help"] || $force) {
$hlp=_("hlp_$file");
if ($hlp!="hlp_$file") {
$hlp=preg_replace(
"#HELPID_([0-9]*)#",
"<a href=\"javascript:help(\\1);\"><img src=\"/aide/help.png\" width=\"17\" height=\"17\" style=\"vertical-align: middle;\" alt=\""._("Help")."\" /></a>",$hlp);
echo "<p class=\"hlp\">".$hlp."</p>";
$hlp = _("hlp_$file");
if ($hlp != "hlp_$file") {
$hlp = preg_replace(
"#HELPID_([0-9]*)#", "<a href=\"javascript:help(\\1);\"><img src=\"/aide/help.png\" width=\"17\" height=\"17\" style=\"vertical-align: middle;\" alt=\"" . _("Help") . "\" /></a>", $hlp);
echo "<p class=\"hlp\">" . $hlp . "</p>";
return true;
}
return false;
@ -593,71 +625,77 @@ Cordially.
* @param integer $uid
*/
function get_creator_by_uid($uid) {
global $db,$err;
$err->log("dom","get_creator_by_uid");
$uid=mysql_real_escape_string(intval($uid));
global $db, $err;
$err->log("dom", "get_creator_by_uid");
$uid = mysql_real_escape_string(intval($uid));
$db->query("select creator from membres where uid = '$uid';");
if (! $db->next_record()) return false;
return intval($db->f('creator') );
if (!$db->next_record()) {
return false;
}
return intval($db->f('creator'));
}
/* ----------------------------------------------------------------- */
/**
* Exports all the personnal user related information for an account.
* Exports all the personal user related information for an account.
* @access private
*/
function alternc_export_conf() {
global $db,$err;
$err->log("mem","export");
$str=" <member>\n";
$users=$this->user;
$str.=" <uid>".$users["uid"]."</uid>\n";
$str.=" <login>".$users["login"]."</login>\n";
$str.=" <enabled>".$users["enabled"]."</enabled>\n";
$str.=" <su>".$users["su"]."</su>\n";
$str.=" <password>".$users["pass"]."</password>\n";
$str.=" <mail>".$users["mail"]."</mail>\n";
$str.=" <created>".$users["created"]."</created>\n";
$str.=" <lastip>".$users["lastip"]."</lastip>\n";
$str.=" <lastlogin>".$users["lastlogin"]."</lastlogin>\n";
$str.=" <lastfail>".$users["lastfail"]."</lastfail>\n";
global $db, $err;
$err->log("mem", "export");
$str = " <member>\n";
$users = $this->user;
$str.=" <uid>" . $users["uid"] . "</uid>\n";
$str.=" <login>" . $users["login"] . "</login>\n";
$str.=" <enabled>" . $users["enabled"] . "</enabled>\n";
$str.=" <su>" . $users["su"] . "</su>\n";
$str.=" <password>" . $users["pass"] . "</password>\n";
$str.=" <mail>" . $users["mail"] . "</mail>\n";
$str.=" <created>" . $users["created"] . "</created>\n";
$str.=" <lastip>" . $users["lastip"] . "</lastip>\n";
$str.=" <lastlogin>" . $users["lastlogin"] . "</lastlogin>\n";
$str.=" <lastfail>" . $users["lastfail"] . "</lastfail>\n";
$str.=" </member>\n";
return $str;
}
function session_tempo_params_get($v) {
global $uid;
if (empty($_COOKIE['session'])) return false;
$sid=$_COOKIE['session'];
if ( empty($_SESSION[$sid.'-'.$uid]) ) { // si pas de session de params tempo
if (empty($_COOKIE['session'])) {
return false;
}
$j=$_SESSION[$sid.'-'.$uid];
$j=json_decode($j, true);
if ( ! empty($j[$v] ) ) { // si on a bien qque chose a retourner :)
$sid = $_COOKIE['session'];
if (empty($_SESSION[$sid . '-' . $uid])) { // si pas de session de params tempo
return false;
}
$j = $_SESSION[$sid . '-' . $uid];
$j = json_decode($j, true);
if (!empty($j[$v])) { // si on a bien qque chose a retourner :)
return $j[$v];
}
return false;
}
function session_tempo_params_set($k, $v, $ecrase=false) {
function session_tempo_params_set($k, $v, $ecrase = false) {
global $uid;
if (empty($_COOKIE['session'])) return false;
$sid=$_COOKIE['session'];
$p=Array();
if ( ! empty($_SESSION[$sid.'-'.$uid]) ) {
$p = json_decode($_SESSION[$sid.'-'.$uid], true);
if (empty($_COOKIE['session'])) {
return false;
}
if (! $ecrase && (isset($p[$k]) && is_array($p[$k])) && is_array($v) ) {
$v=array_merge($p[$k], $v); // overwrite entry with the same name
$sid = $_COOKIE['session'];
$p = Array();
if (!empty($_SESSION[$sid . '-' . $uid])) {
$p = json_decode($_SESSION[$sid . '-' . $uid], true);
}
if (!$ecrase && (isset($p[$k]) && is_array($p[$k])) && is_array($v)) {
$v = array_merge($p[$k], $v); // overwrite entry with the same name
}
$p[$k]=$v;
$_SESSION[$sid.'-'.$uid]=json_encode($p);
$p[$k] = $v;
$_SESSION[$sid . '-' . $uid] = json_encode($p);
return true;
}
} /* Classe Membre */
}
?>
/* Classe Membre */

View File

@ -1,4 +1,5 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
@ -21,7 +22,7 @@
----------------------------------------------------------------------
Purpose of file: Manage hook system.
----------------------------------------------------------------------
*/
*/
/**
* This class manage menu.
@ -29,20 +30,20 @@
* @copyright AlternC-Team 2002-2005 http://alternc.org/
*/
class m_menu {
/* --------------------------------------------------------------------------- */
/*---------------------------------------------------------------------------*/
/** Constructor
* menu([$mid]) Constructeur de la classe menu, ne fait rien pour le moment
*/
function m_menu() {
}
function getmenu() {
global $hooks, $quota, $mem;
// Force rebuilding quota, in case of add or edit of the quota and cache not up-to-date
$mesq = $quota->getquota("",true); // rebuild quota
$mesq = $quota->getquota("", true); // rebuild quota
// Get menu objects
$lsto = $hooks->invoke('hook_menu');
@ -50,15 +51,15 @@ class m_menu {
$sm = $this->system_menu();
// Merge it !
$lst = array_merge($sm,$lsto);
$lst = array_merge($sm, $lsto);
// Sort it
uasort($lst, 'm_menu::order_menu');
// Get user specific menu visibility options
$mop = $mem->session_tempo_params_get('menu_toggle') ;
$mop = $mem->session_tempo_params_get('menu_toggle');
foreach( $lst as $k => $v ) {
foreach ($lst as $k => $v) {
if (empty($v)) {
unset($lst[$k]);
@ -67,35 +68,39 @@ class m_menu {
// Set the javascript toggle link for menu asking for it
if ($v['link'] == 'toggle') {
$lst[$k]['link'] = 'javascript:menu_toggle(\'menu-'.$k.'\');';
$lst[$k]['link'] = 'javascript:menu_toggle(\'menu-' . $k . '\');';
}
// Be sure that the default visibility is true
if (! isset($lst[$k]['visibility'])) $lst[$k]['visibility'] = true;
if (!isset($lst[$k]['visibility'])) {
$lst[$k]['visibility'] = true;
}
// Set the user's specific visibility option
if (isset($mop["menu-$k"])) {
if ($mop["menu-$k"] == "hidden") $lst[$k]['visibility'] = false;
if ($mop["menu-$k"] == "visible") $lst[$k]['visibility'] = true;
if ($mop["menu-$k"] == "hidden") {
$lst[$k]['visibility'] = false;
}
if ($mop["menu-$k"] == "visible") {
$lst[$k]['visibility'] = true;
}
}
if ( isset($mesq[$k])) { // if there are some quota for this class
if (isset($mesq[$k])) { // if there are some quota for this class
// Hide the menu if there are none and not allowed to create
if ( $mesq[$k]['t'] < 1 && $mesq[$k]['u'] < 1 ) {
if ($mesq[$k]['t'] < 1 && $mesq[$k]['u'] < 1) {
unset($lst[$k]);
continue;
}
// Set the quota in the menu object
$lst[$k]['quota_used'] = $mesq[$k]['u'] ;
$lst[$k]['quota_total'] = $mesq[$k]['t'] ;
$lst[$k]['quota_used'] = $mesq[$k]['u'];
$lst[$k]['quota_total'] = $mesq[$k]['t'];
} // end if there are some quota for this class
}
return $lst;
} //getmenu
}
function order_menu($a, $b) {
// Use to order the menu with a usort
@ -106,8 +111,7 @@ class m_menu {
// Here some needed menu who don't have a class
global $help_baseurl, $lang_translation, $locales;
$m =
array(
$m = array(
'home' =>
array(
'title' => _("Home / Information"),
@ -139,37 +143,13 @@ class m_menu {
'links' => array(),
'pos' => 150,
)
) ;
foreach($locales as $l) {
$m['lang']['links'][] = array ( 'txt' => (isset($lang_translation[$l]))?$lang_translation[$l]:$l, 'url' => "/login.php?setlang=$l");
);
foreach ($locales as $l) {
$m['lang']['links'][] = array('txt' => (isset($lang_translation[$l])) ? $lang_translation[$l] : $l, 'url' => "/login.php?setlang=$l");
}
return $m;
}
}
/*
<div class="menu-box">
<a href="javascript:menu_toggle('menu-lang');">
<div class="menu-title">
<img src="/images/lang.png" alt="<?php __("Languages"); ?>" />&nbsp;<?php __("Languages"); ?>
<img src="/images/menu_moins.png" alt="" style="float:right;" id="menu-lang-img"/>
</div>
</a>
<div class="menu-content" id="menu-lang">
<ul>
<?php foreach($locales as $l) { ?>
<li><a href="/login.php?setlang=<?php echo $l; ?>" target="_top"><?php if (isset($lang_translation[$l])) echo $lang_translation[$l]; else echo $l; ?></a></li>
<?php } ?>
</ul>
</div>
</div>
*/
} //system_menu
} /* Class menu */
/* Class menu */

File diff suppressed because it is too large Load Diff

View File

@ -1,4 +1,5 @@
<?php
/*
----------------------------------------------------------------------
AlternC - Web Hosting System
@ -21,7 +22,7 @@
----------------------------------------------------------------------
Purpose of file: Manage user quota
----------------------------------------------------------------------
*/
*/
/**
* Class for hosting quotas management
@ -37,23 +38,21 @@
*/
class m_quota {
var $disk=Array(); /* disk resource for which we will manage quotas */
var $disk = Array(); /* disk resource for which we will manage quotas */
var $disk_quota_enable;
var $quotas;
var $clquota; // Which class manage which quota.
/* ----------------------------------------------------------------- */
/**
* Constructor
*/
function m_quota() {
$this->disk_quota_enable = variable_get('disk_quota_enable', 1,'Are disk quota enabled for this server', array('desc'=>'Enabled','type'=>'boolean'));
if ( $this->disk_quota_enable ) {
$this->disk = Array( "web"=>"web" );
$this->disk_quota_enable = variable_get('disk_quota_enable', 1, 'Are disk quota enabled for this server', array('desc' => 'Enabled', 'type' => 'boolean'));
if ($this->disk_quota_enable) {
$this->disk = Array("web" => "web");
}
}
private function dummy_for_translation() {
@ -68,53 +67,54 @@ class m_quota {
'pos' => 110,
'divclass' => 'menu-quota',
'links' => array(),
) ;
);
$q=$this->getquota();
$q = $this->getquota();
foreach ( array('web', 'bw_web') as $key ) {
if ( ! isset($q[$key]["u"]) || empty($q[$key]["t"])) continue;
foreach (array('web', 'bw_web') as $key) {
if (!isset($q[$key]["u"]) || empty($q[$key]["t"])) {
continue;
}
$usage_percent = (int) ($q[$key]["u"] / $q[$key]["t"] * 100);
$obj['links'][] = array( 'txt'=>_("quota_".$key) . " " . sprintf(_("%s%% of %s"),$usage_percent,format_size($q[$key]["t"]*1024)), 'url'=>($key == 'bw_web' ? 'stats_show_per_month.php' : 'quota_show.php') );
$obj['links'][] = array( 'txt'=>'progressbar', 'total' => $q[$key]["t"], 'used' => $q[$key]["u"]);
$obj['links'][] = array('txt' => _("quota_" . $key) . " " . sprintf(_("%s%% of %s"), $usage_percent, format_size($q[$key]["t"] * 1024)), 'url' => ($key == 'bw_web' ? 'stats_show_per_month.php' : 'quota_show.php'));
$obj['links'][] = array('txt' => 'progressbar', 'total' => $q[$key]["t"], 'used' => $q[$key]["u"]);
}
return $obj;
}
/* ----------------------------------------------------------------- */
/** Check if a user can use a ressource.
* @param string $ressource the ressource name (a named quota)
* @Return TRUE if the user can create a ressource (= is there any quota left ?)
* @return boolean
*/
function cancreate($ressource="") {
$t=$this->getquota($ressource);
return $t["u"]<$t["t"];
function cancreate($ressource = "") {
$t = $this->getquota($ressource);
return $t["u"] < $t["t"];
}
/* ----------------------------------------------------------------- */
/** List the quota-managed services in the server
* @Return array the quota names and description (translated)
*/
function qlist() {
global $classes,$hooks;
$qlist=array();
$qlist = array();
reset($this->disk);
while (list($key,$val)=each($this->disk)) {
$qlist[$key]=_("quota_".$key); // those are specific disks quotas.
while (list($key, $val) = each($this->disk)) {
$qlist[$key] = _("quota_" . $key); // those are specific disks quotas.
}
foreach($this->getquota() as $qq) {
foreach ($this->getquota() as $qq) {
if (isset($qq['name'])) {
$qlist[$qq['name']]=$qq['description'];
$qlist[$qq['name']] = $qq['description'];
}
}
return $qlist;
}
/**
* Synchronise the quotas of the users with the quota of the
* user's profile.
@ -123,10 +123,12 @@ class m_quota {
* the defaults value.
*/
function synchronise_user_profile() {
global $db,$err;
$err->log("quota","synchronise_user_profile");
$q="insert into quotas select m.uid as uid, d.quota as name, d.value as total from membres m, defquotas d left join quotas q on q.name=d.quota where m.type=d.type ON DUPLICATE KEY UPDATE total = greatest(d.value, quotas.total);";
if (!$db->query($q)) return false;
global $db, $err;
$err->log("quota", "synchronise_user_profile");
$q = "insert into quotas select m.uid as uid, d.quota as name, d.value as total from membres m, defquotas d left join quotas q on q.name=d.quota where m.type=d.type ON DUPLICATE KEY UPDATE total = greatest(d.value, quotas.total);";
if (!$db->query($q)) {
return false;
}
return true;
}
@ -135,13 +137,14 @@ class m_quota {
* when a new quota appear
*
*/
function create_missing_quota_profile() {
global $db,$quota,$err;
$err->log("quota","create_missing_quota_profile");
$qt=$quota->getquota('',true);
$type=$quota->listtype();
foreach($type as $t) {
foreach($qt as $q=>$vv) {
global $db, $quota, $err;
$err->log("quota", "create_missing_quota_profile");
$qt = $quota->getquota('', true);
$type = $quota->listtype();
foreach ($type as $t) {
foreach ($qt as $q => $vv) {
$db->query("INSERT IGNORE defquotas (value,quota,type) VALUES (0,'$q','$t');");
}
}
@ -149,66 +152,64 @@ class m_quota {
}
/* ----------------------------------------------------------------- */
/** Return a ressource usage (u) and total quota (t)
* @param string $ressource ressource to get quota of
* @Return array the quota used and total for this ressource (or for all ressource if unspecified)
*/
function getquota($ressource="",$recheck=false) {
global $db,$err,$cuid,$get_quota_cache,$hooks,$mem;
$err->log("quota","getquota",$ressource);
function getquota($ressource = "", $recheck = false) {
global $db, $err, $cuid, $get_quota_cache, $hooks, $mem;
$err->log("quota", "getquota", $ressource);
if ($recheck) { // rebuilding quota
$get_quota_cache=null;
$this->quotas=array();
$get_quota_cache = null;
$this->quotas = array();
}
if (! empty($get_quota_cache[$cuid]) ) {
if (!empty($get_quota_cache[$cuid])) {
// This function is called many time each webpage, so I cache the result
$this->quotas = $get_quota_cache[$cuid];
} else {
$res=$hooks->invoke("hook_quota_get");
foreach($res as $r) {
$this->quotas[$r['name']]=$r;
$this->quotas[$r['name']]['u']=$r['used']; // retrocompatibilité
$this->quotas[$r['name']]['t']=0; // Default quota = 0
$res = $hooks->invoke("hook_quota_get");
foreach ($res as $r) {
$this->quotas[$r['name']] = $r;
$this->quotas[$r['name']]['u'] = $r['used']; // retrocompatibilité
$this->quotas[$r['name']]['t'] = 0; // Default quota = 0
}
reset($this->disk);
if (!empty ($this->disk)) { // Check if there are some disk quota to check
if (!empty($this->disk)) { // Check if there are some disk quota to check
// Look if there are some cached value
$disk_cached = $mem->session_tempo_params_get('quota_cache_disk');
while (list($key,$val)=each($this->disk)) {
$a=array();
while (list($key, $val) = each($this->disk)) {
$a = array();
if (
isset($disk_cached[$val])
&& !empty($disk_cached[$val])
&& $disk_cached[$val]['uid'] == $cuid
&& $disk_cached[$val]['timestamp'] > ( time() - (90) ) // Cache, en seconde
isset($disk_cached[$val]) && !empty($disk_cached[$val]) && $disk_cached[$val]['uid'] == $cuid && $disk_cached[$val]['timestamp'] > ( time() - (90) ) // Cache, en seconde
) {
// If there is a cached value
$a = $disk_cached[$val];
} else {
exec("/usr/lib/alternc/quota_get ".intval($cuid) ,$ak);
$a['u']=intval($ak[0]);
$a['t']=@intval($ak[1]);
exec("/usr/lib/alternc/quota_get " . intval($cuid), $ak);
$a['u'] = intval($ak[0]);
$a['t'] = @intval($ak[1]);
$a['timestamp'] = time();
$a['uid'] = $cuid;
$disk_cached = $mem->session_tempo_params_set('quota_cache_disk', array($val=>$a));
$disk_cached = $mem->session_tempo_params_set('quota_cache_disk', array($val => $a));
}
$this->quotas[$val]=array("name"=>"$val", 'description'=>_("quota_".$val), "t"=>$a['t'],"u"=>$a['u']);
$this->quotas[$val] = array("name" => "$val", 'description' => _("quota_" . $val), "t" => $a['t'], "u" => $a['u']);
}
}
// Get the allowed quota from database.
$db->query("select name, total from quotas where uid='$cuid';");
while ( $db->next_record() ) {
$this->quotas[$db->f('name')]['t']=$db->f('total');
while ($db->next_record()) {
$this->quotas[$db->f('name')]['t'] = $db->f('total');
}
$get_quota_cache[$cuid] = $this->quotas;
}
if ($ressource) {
if (isset($this->quotas[$ressource]) ) {
if (isset($this->quotas[$ressource])) {
return $this->quotas[$ressource];
} else {
return 0;
@ -218,23 +219,26 @@ class m_quota {
}
}
/* ----------------------------------------------------------------- */
/** Set the quota for a user (and for a ressource)
* @param string $ressource ressource to set quota of
* @param integer size of the quota (available or used)
*/
function setquota($ressource,$size) {
global $err,$db,$cuid;
$err->log("quota","setquota",$ressource."/".$size);
if (floatval($size)==0) $size="0";
function setquota($ressource, $size) {
global $err, $db, $cuid;
$err->log("quota", "setquota", $ressource . "/" . $size);
if (floatval($size) == 0) {
$size = "0";
}
if (isset($this->disk[$ressource])) {
// It's a disk resource, update it with shell command
exec("sudo /usr/lib/alternc/quota_edit ".intval($cuid)." ".intval($size)." &> /dev/null &");
exec("sudo /usr/lib/alternc/quota_edit " . intval($cuid) . " " . intval($size) . " &> /dev/null &");
// Now we check that the value has been written properly :
exec("sudo /usr/lib/alternc/quota_get ".intval($cuid)." &> /dev/null &",$a);
if (!isset($a[1]) || $size!=$a[1]) {
$err->raise("quota",_("Error writing the quota entry!"));
$a = array();
exec("sudo /usr/lib/alternc/quota_get " . intval($cuid) . " &> /dev/null &", $a);
if (!isset($a[1]) || $size != $a[1]) {
$err->raise("quota", _("Error writing the quota entry!"));
return false;
}
}
@ -248,99 +252,102 @@ class m_quota {
return true;
}
/* ----------------------------------------------------------------- */
/**
* Erase all quota information about the user.
*/
function delquotas() {
global $db,$err,$cuid;
$err->log("quota","delquota");
global $db, $err, $cuid;
$err->log("quota", "delquota");
$db->query("DELETE FROM quotas WHERE uid='$cuid';");
return true;
}
/* ----------------------------------------------------------------- */
/** Get the default quotas as an associative array
* @return array the array of the default quotas
*/
function getdefaults() {
global $db;
$c=array();
$c = array();
$db->query("SELECT type,quota FROM defquotas WHERE type='default'");
if(!$db->next_record())
if (!$db->next_record()) {
$this->addtype('default');
}
$db->query("SELECT value,quota,type FROM defquotas ORDER BY type,quota");
while($db->next_record()) {
while ($db->next_record()) {
$type = $db->f("type");
$c[$type][$db->f("quota")] = $db->f("value");
}
return $c;
}
/* ----------------------------------------------------------------- */
/** Set the default quotas
* @param array associative array of quota (key=>val)
*/
function setdefaults($newq) {
global $db;
$qlist=$this->qlist();
$qlist = $this->qlist();
foreach($newq as $type => $quotas) {
foreach($quotas as $qname => $value) {
if(array_key_exists($qname, $qlist)) {
if(!$db->query("REPLACE INTO defquotas (value,quota,type) VALUES ($value,'$qname','$type');"))
foreach ($newq as $type => $quotas) {
foreach ($quotas as $qname => $value) {
if (array_key_exists($qname, $qlist)) {
if (!$db->query("REPLACE INTO defquotas (value,quota,type) VALUES ($value,'$qname','$type');")) {
return false;
}
}
}
}
return true;
}
/* ----------------------------------------------------------------- */
/** Add an account type for quotas
* @param string $type account type to be added
* @return boolean true if all went ok
*/
function addtype($type) {
global $db,$err;
$qlist=$this->qlist();
if(empty($type)) return false;
$type=strtolower($type);
if (!preg_match("#^[a-z0-9]*$#",$type)) {
global $db, $err;
$qlist = $this->qlist();
if (empty($type)) {
return false;
}
$type = strtolower($type);
if (!preg_match("#^[a-z0-9]*$#", $type)) {
$err->raise("quota", "Type can only contains characters a-z and 0-9");
return false;
}
while (list($key,$val)=each($qlist)) {
if(!$db->query("INSERT IGNORE INTO defquotas (quota,type) VALUES('$key', '$type');")
|| $db->affected_rows() == 0)
while (list($key, $val) = each($qlist)) {
if (!$db->query("INSERT IGNORE INTO defquotas (quota,type) VALUES('$key', '$type');") || $db->affected_rows() == 0) {
return false;
}
}
return true;
}
/* ----------------------------------------------------------------- */
/** List for quotas
* @return array
*/
function listtype() {
global $db;
$db->query("SELECT distinct(type) FROM defquotas ORDER by type");
$t=array();
$t = array();
while ($db->next_record()) {
$t[] = $db->f("type");
}
return $t;
}
/* ----------------------------------------------------------------- */
/** Delete an account type for quotas
* @param string $type account type to be deleted
* @return boolean true if all went ok
@ -348,7 +355,7 @@ class m_quota {
function deltype($type) {
global $db;
if($db->query("UPDATE membres SET type='default' WHERE type='$type'") &&
if ($db->query("UPDATE membres SET type='default' WHERE type='$type'") &&
$db->query("DELETE FROM defquotas WHERE type='$type'")) {
return true;
} else {
@ -356,26 +363,26 @@ class m_quota {
}
}
/* ----------------------------------------------------------------- */
/** Create default quotas entries for a new user.
* The user we are talking about is in the global $cuid.
*/
function addquotas() {
global $db,$err,$cuid;
$err->log("quota","addquota");
$ql=$this->qlist();
global $db, $err, $cuid;
$err->log("quota", "addquota");
$ql = $this->qlist();
reset($ql);
$db->query("SELECT type,quota FROM defquotas WHERE type='default'");
if(!$db->next_record())
if (!$db->next_record()) {
$this->addtype('default');
}
$db->query("SELECT type FROM membres WHERE uid='$cuid'");
$db->next_record();
$t = $db->f("type");
foreach($ql as $res => $val) {
foreach ($ql as $res => $val) {
$db->query("SELECT value FROM defquotas WHERE quota='$res' AND type='$t'");
$q = $db->next_record() ? $db->f("value") : 0;
$this->setquota($res, $q);
@ -383,8 +390,8 @@ class m_quota {
return true;
}
/* ----------------------------------------------------------------- */
/** Return a quota value with its unit (when it is a space quota)
* in MB, GB, TB ...
* @param string $type The quota type
@ -396,16 +403,16 @@ class m_quota {
case 'bw_web':
return format_size($value);
case 'web':
return format_size($value*1024);
return format_size($value * 1024);
default:
return $value;
}
}
/* get size_xx function (filled by spoolsize.php) */
function _get_sum_sql($sql) {
global $db,$err,$cuid;
global $db;
$db->query($sql);
if ($db->num_rows() == 0) {
return -1;
@ -417,7 +424,7 @@ class m_quota {
}
function _get_count_sql($sql) {
global $db,$err,$cuid;
global $db;
$db->query($sql);
if ($db->num_rows() == 0) {
return 0;
@ -429,7 +436,7 @@ class m_quota {
}
function _get_size_and_record_sql($sql) {
global $db,$err,$cuid;
global $db;
$db->query($sql);
if ($db->num_rows() == 0) {
return array();
@ -443,103 +450,122 @@ class m_quota {
}
/* sum of websites sizes from all users */
function get_size_web_sum_all() {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_web;");
}
/* sum of websites sizes from one user */
function get_size_web_sum_user($u) {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_web WHERE uid='$u';");
}
/* sum of mailbox sizes from all domains */
function get_size_mail_sum_all() {
return $this->_get_sum_sql("SELECT SUM(bytes) AS sum FROM mailbox;");
}
/* sum of mailbox sizes for one domain */
function get_size_mail_sum_domain($dom) {
global $mail;
return $mail->get_total_size_for_domain($dom);
}
/* count of mailbox sizes from all domains */
function get_size_mail_count_all() {
return $this->_get_count_sql("SELECT COUNT(*) AS count FROM mailbox;");
}
/* count of mailbox for one domain */
function get_size_mail_count_domain($dom) {
return $this->_get_count_sql("SELECT COUNT(*) AS count FROM dovecot_view WHERE user LIKE '%@{$dom}'");
}
/* get list of mailbox alias and size for one domain */
function get_size_mail_details_domain($dom) {
return $this->_get_size_and_record_sql("SELECT user as alias,quota_dovecot as size FROM dovecot_view WHERE user LIKE '%@{$dom}' ORDER BY alias;");
}
/* sum of mailman lists sizes from all domains */
function get_size_mailman_sum_all() {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman;");
}
/* sum of mailman lists sizes for one domain */
function get_size_mailman_sum_domain($dom) {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman WHERE list LIKE '%@{$dom}'");
}
/* sum of mailman lists for one user */
function get_size_mailman_sum_user($u) {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman WHERE uid = '{$u}'");
}
/* count of mailman lists sizes from all domains */
function get_size_mailman_count_all() {
return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_mailman;");
}
/* count of mailman lists for one user */
function get_size_mailman_count_user($u) {
return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_mailman WHERE uid = '{$u}'");
}
/* get list of mailman list and size for one user */
function get_size_mailman_details_user($u) {
return $this->_get_size_and_record_sql("SELECT s.size,CONCAT(m.list,'@',m.domain) as list FROM size_mailman s LEFT JOIN mailman m ON s.list=m.name WHERE s.uid='{$u}' ORDER BY s.list ASC");
}
/* sum of databases sizes from all users */
function get_size_db_sum_all() {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_db;");
}
/* sum of databases sizes for one user */
function get_size_db_sum_user($u) {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_db WHERE db = '{$u}' OR db LIKE '{$u}\_%'");
}
/* count of databases from all users */
function get_size_db_count_all() {
return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_db;");
}
/* count of databases for one user */
function get_size_db_count_user($u) {
return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_db WHERE db = '{$u}' OR db LIKE '{$u}\_%'");
}
/* get list of databases name and size for one user */
function get_size_db_details_user($u) {
return $this->_get_size_and_record_sql("SELECT db,size FROM size_db WHERE db='{$u}' OR db LIKE '{$u}\_%';");
}
/* Return appropriate value and unit of a size given in Bytes (e.g. 1024 Bytes -> return 1 KB) */
function get_size_unit($size) {
$units=array(1073741824=>_("GB"), 1048576=>_("MB"), 1024=>_("KB"), 0=>_("B"));
foreach($units as $value=>$unit){
if($size>=$value){
$size=str_pad(round($size/($value ? $value : 1), 1), 5, ' ', STR_PAD_LEFT);
return array('size'=>$size, 'unit'=>$unit);
$units = array(1073741824 => _("GB"), 1048576 => _("MB"), 1024 => _("KB"), 0 => _("B"));
foreach ($units as $value => $unit) {
if ($size >= $value) {
$size = str_pad(round($size / ($value ? $value : 1), 1), 5, ' ', STR_PAD_LEFT);
return array('size' => $size, 'unit' => $unit);
}
}
}
@ -549,26 +575,26 @@ class m_quota {
// 0 = Pas de changement de couleur
// 1 = Progression du vert vers le rouge en fonction du porcentage
// 2 = Progression du rouge vers le vert en fonction du porcentage
function quota_displaybar($usage, $color_type=1) {
function quota_displaybar($usage, $color_type = 1) {
if ($color_type == 1) {
$csscolor = " background-color:".PercentToColor($usage);
$csscolor = " background-color:" . PercentToColor($usage);
} elseif ($color_type == 2) {
$csscolor = " background-color:".PercentToColor(100-$usage);
$csscolor = " background-color:" . PercentToColor(100 - $usage);
} else {
$csscolor = "";
}
echo '<div class="progress-bar">';
echo '<div class="barre" style="width:'.$usage.'%;'.$csscolor.'" ></div>';
echo '<div class="txt">'.$usage.'%</div>';
echo '<div class="barre" style="width:' . $usage . '%;' . $csscolor . '" ></div>';
echo '<div class="txt">' . $usage . '%</div>';
echo '</div>';
}
/* ==== Hook functions ==== */
/* ----------------------------------------------------------------- */
/** Hook function call when a user is deleted
* AlternC's standard function called when a user is deleted
* globals $cuid is the appropriate user
@ -577,41 +603,42 @@ class m_quota {
$this->delquotas();
}
/* ----------------------------------------------------------------- */
/** Hook function called when a user is created
* This function initialize the user's quotas.
* globals $cuid is the appropriate user
*/
function hook_admin_add_member() {
global $err;
$err->log("quota","hook_admin_add_member");
$err->log("quota", "hook_admin_add_member");
$this->addquotas();
$this->getquota('',true); // actualise quota
$this->getquota('', true); // actualise quota
}
/* ----------------------------------------------------------------- */
/** Exports all the quota related information for an account.
* @access private
* EXPERIMENTAL function ;)
*/
function alternc_export_conf() {
global $db,$err;
$err->log("quota","export");
$str=" <quota>";
global $err;
$err->log("quota", "export");
$str = " <quota>";
$q=$this->getquota();
foreach ($q as $k=>$v) {
$q = $this->getquota();
foreach ($q as $k => $v) {
$str.=" <$k>\n";
$str.=" <used>".($v["u"])."</used>\n";
$str.=" <total>".($v["t"])."</total>\n";
$str.=" <used>" . ($v["u"]) . "</used>\n";
$str.=" <total>" . ($v["t"]) . "</total>\n";
$str.=" </$k>\n";
}
$str.="</quota>\n";
return $str;
}
}
} /* Class m_quota */
/* Class m_quota */