[cosm] reindent, check language of comments, ensure /** phpdoc style comments, simplify file header (license only) etc.

This commit is contained in:
Benjamin Sonntag 2017-10-06 23:42:39 +02:00
parent 8dac9a499d
commit 3de55aca37
31 changed files with 2485 additions and 2557 deletions

View File

@ -2,40 +2,40 @@
class system_bind { class system_bind {
var $ZONE_TEMPLATE ="/etc/alternc/templates/bind/templates/zone.template"; var $ZONE_TEMPLATE ="/etc/alternc/templates/bind/templates/zone.template";
var $NAMED_TEMPLATE ="/etc/alternc/templates/bind/templates/named.template"; var $NAMED_TEMPLATE ="/etc/alternc/templates/bind/templates/named.template";
var $NAMED_CONF ="/var/lib/alternc/bind/automatic.conf"; var $NAMED_CONF ="/var/lib/alternc/bind/automatic.conf";
var $RNDC ="/usr/sbin/rndc"; var $RNDC ="/usr/sbin/rndc";
var $dkim_trusted_host_file = "/etc/opendkim/TrustedHosts"; var $dkim_trusted_host_file = "/etc/opendkim/TrustedHosts";
var $dkim_keytable_file = "/etc/opendkim/KeyTable"; var $dkim_keytable_file = "/etc/opendkim/KeyTable";
var $dkim_signingtable_file = "/etc/opendkim/SigningTable"; var $dkim_signingtable_file = "/etc/opendkim/SigningTable";
var $cache_conf_db = array(); var $cache_conf_db = array();
var $cache_get_persistent = array(); var $cache_get_persistent = array();
var $cache_zone_file = array(); var $cache_zone_file = array();
var $cache_domain_summary = array(); var $cache_domain_summary = array();
var $zone_file_directory = '/var/lib/alternc/bind/zones/'; var $zone_file_directory = '/var/lib/alternc/bind/zones/';
/** /**
* *
*/ */
function system_bind() { function system_bind() {
// Constructeur // Constructeur
} }
/** /**
* Return the part of the conf we got from the database * Return the part of the conf we got from the database
* *
* @global m_mysql $db * @global m_mysql $db
* @param string $domain * @param string $domain
* @return array $this->cache_conf_db * @return array $this->cache_conf_db
*/ */
function conf_from_db($domain=false) { function conf_from_db($domain=false) {
global $db; global $db;
// Use cache, fill cache if empty // Use cache, fill cache if empty
if (empty($this->cache_conf_db)) { if (empty($this->cache_conf_db)) {
$db->query(" $db->query("
select select
sd.domaine, sd.domaine,
replace(replace(dt.entry,'%TARGET%',sd.valeur), '%SUB%', if(length(sd.sub)>0,sd.sub,'@')) as entry replace(replace(dt.entry,'%TARGET%',sd.valeur), '%SUB%', if(length(sd.sub)>0,sd.sub,'@')) as entry
@ -46,290 +46,290 @@ class system_bind {
sd.type=dt.name sd.type=dt.name
and sd.enable in ('ENABLE', 'ENABLED') and sd.enable in ('ENABLE', 'ENABLED')
order by entry ;"); order by entry ;");
$t=array(); $t=array();
while ($db->next_record()) { while ($db->next_record()) {
$t[$db->f('domaine')][] = $db->f('entry'); $t[$db->f('domaine')][] = $db->f('entry');
} }
$this->cache_conf_db = $t; $this->cache_conf_db = $t;
}
if ($domain) {
if (isset($this->cache_conf_db[$domain])) {
return $this->cache_conf_db[$domain];
} else {
return array();
}
} // if domain
return $this->cache_conf_db;
} }
if ($domain) {
if (isset($this->cache_conf_db[$domain])) {
return $this->cache_conf_db[$domain];
} else {
return array();
}
} // if domain
return $this->cache_conf_db;
}
/** /**
* Return full path of the zone configuration file * Return full path of the zone configuration file
* *
* @param string $domain * @param string $domain
* @return string * @return string
*/ */
function get_zone_file_uri($domain) { function get_zone_file_uri($domain) {
return $this->zone_file_directory.$domain; return $this->zone_file_directory.$domain;
}
/**
*
* @param string $domain
* @return string zone file path
*/
function get_zone_file($domain) {
// Use cache, fill cache if empty
if (!isset($this->cache_zone_file[$domain]) ) {
if (file_exists($this->get_zone_file_uri($domain))) {
$this->cache_zone_file[$domain] = @file_get_contents($this->get_zone_file_uri($domain));
} else {
$this->cache_zone_file[$domain] = false;
}
} }
return $this->cache_zone_file[$domain] ;
}
/** /**
* *
* @param string $domain * @param string $domain
* @return string * @return string zone file path
*/ */
function get_serial($domain) { function get_zone_file($domain) {
// Return the next serial the domain must have. // Use cache, fill cache if empty
// Choose between a generated and an incremented. if (!isset($this->cache_zone_file[$domain]) ) {
if (file_exists($this->get_zone_file_uri($domain))) {
$this->cache_zone_file[$domain] = @file_get_contents($this->get_zone_file_uri($domain));
} else {
$this->cache_zone_file[$domain] = false;
}
}
return $this->cache_zone_file[$domain] ;
}
/**
*
* @param string $domain
* @return string
*/
function get_serial($domain) {
// Return the next serial the domain must have.
// Choose between a generated and an incremented.
// Calculated : // Calculated :
$calc = date('Ymd').'00'."\n"; $calc = date('Ymd').'00'."\n";
// Old one : // Old one :
$old=$calc; // default value $old=$calc; // default value
$file = $this->get_zone_file($domain); $file = $this->get_zone_file($domain);
preg_match_all("/\s*(\d{10})\s+\;\sserial\s?/", $file, $output_array); preg_match_all("/\s*(\d{10})\s+\;\sserial\s?/", $file, $output_array);
if (isset($output_array[1][0]) && !empty($output_array[1][0])) { if (isset($output_array[1][0]) && !empty($output_array[1][0])) {
$old = $output_array[1][0]; $old = $output_array[1][0];
}
// Return max between newly calculated, and old one incremented
return max(array($calc,$old)) + 1 ;
} }
// Return max between newly calculated, and old one incremented /**
return max(array($calc,$old)) + 1 ; * Return lines that are after ;;; END ALTERNC AUTOGENERATE CONFIGURATION
} *
* @param string $domain
/** * @return string
* Return lines that are after ;;; END ALTERNC AUTOGENERATE CONFIGURATION */
* function get_persistent($domain) {
* @param string $domain if ( ! isset($this->cache_get_persistent[$domain] )) {
* @return string preg_match_all('/\;\s*END\sALTERNC\sAUTOGENERATE\sCONFIGURATION(.*)/s', $this->get_zone_file($domain), $output_array);
*/ if (isset($output_array[1][0]) && !empty($output_array[1][0])) {
function get_persistent($domain) { $this->cache_get_persistent[$domain] = $output_array[1][0];
if ( ! isset($this->cache_get_persistent[$domain] )) { } else {
preg_match_all('/\;\s*END\sALTERNC\sAUTOGENERATE\sCONFIGURATION(.*)/s', $this->get_zone_file($domain), $output_array); $this->cache_get_persistent[$domain] = false;
if (isset($output_array[1][0]) && !empty($output_array[1][0])) { }
$this->cache_get_persistent[$domain] = $output_array[1][0]; } // isset
} else { return $this->cache_get_persistent[$domain];
$this->cache_get_persistent[$domain] = false; }
}
} // isset
return $this->cache_get_persistent[$domain];
}
/** /**
* *
* @return string * @return string
*/ */
function get_zone_header() { function get_zone_header() {
return file_get_contents($this->ZONE_TEMPLATE); return file_get_contents($this->ZONE_TEMPLATE);
} }
/** /**
* *
* @global m_dom $dom * @global m_dom $dom
* @param string $domain * @param string $domain
* @return array Retourne un tableau * @return array Retourne un tableau
*/ */
function get_domain_summary($domain=false) { function get_domain_summary($domain=false) {
global $dom; global $dom;
// Use cache if is filled, if not, fill it // Use cache if is filled, if not, fill it
if (empty($this->cache_domain_summary)) { if (empty($this->cache_domain_summary)) {
$this->cache_domain_summary = $dom->get_domain_all_summary(); $this->cache_domain_summary = $dom->get_domain_all_summary();
}
if ($domain) return $this->cache_domain_summary[$domain];
else return $this->cache_domain_summary;
} }
if ($domain) return $this->cache_domain_summary[$domain]; /**
else return $this->cache_domain_summary; *
} * @param string $domain
* @return boolean
/** */
* function dkim_delete($domain) {
* @param string $domain $target_dir = "/etc/opendkim/keys/$domain";
* @return boolean if (file_exists($target_dir)) {
*/ @unlink("$target_dir/alternc_private");
function dkim_delete($domain) { @unlink("$target_dir/alternc.txt");
$target_dir = "/etc/opendkim/keys/$domain"; @rmdir($target_dir);
if (file_exists($target_dir)) { }
@unlink("$target_dir/alternc_private"); return true;
@unlink("$target_dir/alternc.txt");
@rmdir($target_dir);
} }
return true;
}
/** /**
* Generate the domain DKIM key * Generate the domain DKIM key
* *
* @param string $domain * @param string $domain
* @return null|boolean * @return null|boolean
*/ */
function dkim_generate_key($domain) { function dkim_generate_key($domain) {
// Stop here if we do not manage the mail // Stop here if we do not manage the mail
$domainInfo = $this->get_domain_summary($domain); $domainInfo = $this->get_domain_summary($domain);
if ( ! $domainInfo['gesmx'] ) return; if ( ! $domainInfo['gesmx'] ) return;
$target_dir = "/etc/opendkim/keys/$domain"; $target_dir = "/etc/opendkim/keys/$domain";
if (file_exists($target_dir.'/alternc.txt')) return; // Do not generate if exist if (file_exists($target_dir.'/alternc.txt')) return; // Do not generate if exist
if (! is_dir($target_dir)) mkdir($target_dir); // create dir if (! is_dir($target_dir)) mkdir($target_dir); // create dir
// Generate the key // Generate the key
$old_dir=getcwd(); $old_dir=getcwd();
chdir($target_dir); chdir($target_dir);
exec('opendkim-genkey -r -d '.escapeshellarg($domain).' -s "alternc" '); exec('opendkim-genkey -r -d '.escapeshellarg($domain).' -s "alternc" ');
chdir($old_dir); chdir($old_dir);
// opendkim must be owner of the key // opendkim must be owner of the key
chown("$target_dir/alternc.private", 'opendkim'); chown("$target_dir/alternc.private", 'opendkim');
chgrp("$target_dir/alternc.private", 'opendkim'); chgrp("$target_dir/alternc.private", 'opendkim');
return true; // FIXME handle error return true; // FIXME handle error
}
/**
* Refresh DKIM configuration: be sure to list the domain having a private key (and only them)
*/
function dkim_refresh_list() {
// so ugly... but there is only 1 pass, not 3. Still ugly.
$trusted_host_new = "# WARNING: this file is auto generated by AlternC.\n# Add your changes after the last line\n";
$keytable_new = "# WARNING: this file is auto generated by AlternC.\n# Add your changes after the last line\n";
$signingtable_new = "# WARNING: this file is auto generated by AlternC.\n# Add your changes after the last line\n";
# Generate automatic entry
foreach ($this->get_domain_summary() as $domain => $ds ) {
// Skip if delete in progress, or if we do not manage dns or mail
if ( ! $ds['gesdns'] || ! $ds['gesmx'] || strtoupper($ds['dns_action']) == 'DELETE' ) continue;
// Skip if there is no key generated
if (! file_exists("/etc/opendkim/keys/$domain/alternc.txt")) continue;
// Modif the files.
$trusted_host_new.="$domain\n";
$keytable_new .="alternc._domainkey.$domain $domain:alternc:/etc/opendkim/keys/$domain/alternc.private\n";
$signingtable_new.="$domain alternc._domainkey.$domain\n";
} }
$trusted_host_new.="# END AUTOMATIC FILE. ADD YOUR CHANGES AFTER THIS LINE\n";
$keytable_new .="# END AUTOMATIC FILE. ADD YOUR CHANGES AFTER THIS LINE\n";
$signingtable_new.="# END AUTOMATIC FILE. ADD YOUR CHANGES AFTER THIS LINE\n";
# Get old files /**
$trusted_host_old=@file_get_contents($this->dkim_trusted_host_file); * Refresh DKIM configuration: be sure to list the domain having a private key (and only them)
$keytable_old =@file_get_contents($this->dkim_keytable_file); */
$signingtable_old=@file_get_contents($this->dkim_signingtable_file); function dkim_refresh_list() {
// so ugly... but there is only 1 pass, not 3. Still ugly.
$trusted_host_new = "# WARNING: this file is auto generated by AlternC.\n# Add your changes after the last line\n";
$keytable_new = "# WARNING: this file is auto generated by AlternC.\n# Add your changes after the last line\n";
$signingtable_new = "# WARNING: this file is auto generated by AlternC.\n# Add your changes after the last line\n";
# Generate automatic entry
foreach ($this->get_domain_summary() as $domain => $ds ) {
// Skip if delete in progress, or if we do not manage dns or mail
if ( ! $ds['gesdns'] || ! $ds['gesmx'] || strtoupper($ds['dns_action']) == 'DELETE' ) continue;
// Skip if there is no key generated
if (! file_exists("/etc/opendkim/keys/$domain/alternc.txt")) continue;
// Modif the files.
$trusted_host_new.="$domain\n";
$keytable_new .="alternc._domainkey.$domain $domain:alternc:/etc/opendkim/keys/$domain/alternc.private\n";
$signingtable_new.="$domain alternc._domainkey.$domain\n";
}
$trusted_host_new.="# END AUTOMATIC FILE. ADD YOUR CHANGES AFTER THIS LINE\n";
$keytable_new .="# END AUTOMATIC FILE. ADD YOUR CHANGES AFTER THIS LINE\n";
$signingtable_new.="# END AUTOMATIC FILE. ADD YOUR CHANGES AFTER THIS LINE\n";
# Get old files
$trusted_host_old=@file_get_contents($this->dkim_trusted_host_file);
$keytable_old =@file_get_contents($this->dkim_keytable_file);
$signingtable_old=@file_get_contents($this->dkim_signingtable_file);
# Keep manuel entry # Keep manuel entry
preg_match_all('/\#\s*END\ AUTOMATIC\ FILE\.\ ADD\ YOUR\ CHANGES\ AFTER\ THIS\ LINE(.*)/s', $trusted_host_old, $output_array); preg_match_all('/\#\s*END\ AUTOMATIC\ FILE\.\ ADD\ YOUR\ CHANGES\ AFTER\ THIS\ LINE(.*)/s', $trusted_host_old, $output_array);
if (isset($output_array[1][0]) && !empty($output_array[1][0])) { if (isset($output_array[1][0]) && !empty($output_array[1][0])) {
$trusted_host_new.=$output_array[1][0]; $trusted_host_new.=$output_array[1][0];
} }
preg_match_all('/\#\s*END\ AUTOMATIC\ FILE\.\ ADD\ YOUR\ CHANGES\ AFTER\ THIS\ LINE(.*)/s', $keytable_old, $output_array); preg_match_all('/\#\s*END\ AUTOMATIC\ FILE\.\ ADD\ YOUR\ CHANGES\ AFTER\ THIS\ LINE(.*)/s', $keytable_old, $output_array);
if (isset($output_array[1][0]) && !empty($output_array[1][0])) { if (isset($output_array[1][0]) && !empty($output_array[1][0])) {
$keytable_new.=$output_array[1][0]; $keytable_new.=$output_array[1][0];
} }
preg_match_all('/\#\s*END\ AUTOMATIC\ FILE\.\ ADD\ YOUR\ CHANGES\ AFTER\ THIS\ LINE(.*)/s', $signingtable_old, $output_array); preg_match_all('/\#\s*END\ AUTOMATIC\ FILE\.\ ADD\ YOUR\ CHANGES\ AFTER\ THIS\ LINE(.*)/s', $signingtable_old, $output_array);
if (isset($output_array[1][0]) && !empty($output_array[1][0])) { if (isset($output_array[1][0]) && !empty($output_array[1][0])) {
$signingtable_new.=$output_array[1][0]; $signingtable_new.=$output_array[1][0];
} }
// Save if there are some diff // Save if there are some diff
if ( $trusted_host_new != $trusted_host_old ) { if ( $trusted_host_new != $trusted_host_old ) {
file_put_contents($this->dkim_trusted_host_file, $trusted_host_new); file_put_contents($this->dkim_trusted_host_file, $trusted_host_new);
}
if ( $keytable_new != $keytable_old ) {
file_put_contents($this->dkim_keytable_file, $keytable_new);
}
if ( $signingtable_new != $signingtable_old ) {
file_put_contents($this->dkim_signingtable_file, $signingtable_new);
}
} }
if ( $keytable_new != $keytable_old ) { /**
file_put_contents($this->dkim_keytable_file, $keytable_new); *
} * @param string $domain
if ( $signingtable_new != $signingtable_old ) { * @return string
file_put_contents($this->dkim_signingtable_file, $signingtable_new); */
function dkim_entry($domain) {
$keyfile="/etc/opendkim/keys/$domain/alternc.txt";
$domainInfo = $this->get_domain_summary($domain);
if (! file_exists($keyfile) && $domainInfo['gesmx'] ) {
$this->dkim_generate_key($domain);
}
return @file_get_contents($keyfile);
} }
} /**
/** * Conditionnal generation autoconfig entry for outlook / thunderbird
* * If entry with the same name allready exist, skip it.
* @param string $domain *
* @return string * @param string $domain
*/ * @return string
function dkim_entry($domain) { */
$keyfile="/etc/opendkim/keys/$domain/alternc.txt"; function mail_autoconfig_entry($domain) {
$domainInfo = $this->get_domain_summary($domain); $zone= implode("\n",$this->conf_from_db($domain))."\n".$this->get_persistent($domain);
if (! file_exists($keyfile) && $domainInfo['gesmx'] ) {
$this->dkim_generate_key($domain); $entry='';
$domainInfo = $this->get_domain_summary($domain);
if ( $domainInfo['gesmx'] ) {
// If we manage the mail
// Check if there is no the same entry (defined or manual)
// can be toto IN A or toto.fqdn.tld. IN A
if (! preg_match("/autoconfig(\s|\.".str_replace('.','\.',$domain)."\.)/", $zone )) {
$entry.="autoconfig IN CNAME %%fqdn%%.\n";
}
if (! preg_match("/autodiscover(\s|\.".str_replace('.','\.',$domain)."\.)/", $zone )) {
$entry.="autodiscover IN CNAME %%fqdn%%.\n";
}
} // if gesmx
return $entry;
} }
return @file_get_contents($keyfile);
}
/**
* Conditionnal generation autoconfig entry for outlook / thunderbird
* If entry with the same name allready exist, skip it.
*
* @param string $domain
* @return string
*/
function mail_autoconfig_entry($domain) {
$zone= implode("\n",$this->conf_from_db($domain))."\n".$this->get_persistent($domain);
$entry='';
$domainInfo = $this->get_domain_summary($domain);
if ( $domainInfo['gesmx'] ) {
// If we manage the mail
// Check if there is no the same entry (defined or manual)
// can be toto IN A or toto.fqdn.tld. IN A
if (! preg_match("/autoconfig(\s|\.".str_replace('.','\.',$domain)."\.)/", $zone )) {
$entry.="autoconfig IN CNAME %%fqdn%%.\n";
}
if (! preg_match("/autodiscover(\s|\.".str_replace('.','\.',$domain)."\.)/", $zone )) {
$entry.="autodiscover IN CNAME %%fqdn%%.\n";
}
} // if gesmx
return $entry;
}
/** /**
* *
* Return a fully generated zone * Return a fully generated zone
* *
* @global string $L_FQDN * @global string $L_FQDN
* @global string $L_NS1_HOSTNAME * @global string $L_NS1_HOSTNAME
* @global string $L_NS2_HOSTNAME * @global string $L_NS2_HOSTNAME
* @global string $L_DEFAULT_MX * @global string $L_DEFAULT_MX
* @global string $L_DEFAULT_SECONDARY_MX * @global string $L_DEFAULT_SECONDARY_MX
* @global string $L_PUBLIC_IP * @global string $L_PUBLIC_IP
* @param string $domain * @param string $domain
* @return string * @return string
*/ */
function get_zone($domain) { function get_zone($domain) {
global $L_FQDN, $L_NS1_HOSTNAME, $L_NS2_HOSTNAME, $L_DEFAULT_MX, $L_DEFAULT_SECONDARY_MX, $L_PUBLIC_IP; global $L_FQDN, $L_NS1_HOSTNAME, $L_NS2_HOSTNAME, $L_DEFAULT_MX, $L_DEFAULT_SECONDARY_MX, $L_PUBLIC_IP;
$zone =$this->get_zone_header(); $zone =$this->get_zone_header();
$zone.=implode("\n",$this->conf_from_db($domain)); $zone.=implode("\n",$this->conf_from_db($domain));
$zone.="\n;;;HOOKED ENTRY\n"; $zone.="\n;;;HOOKED ENTRY\n";
$zone.= $this->dkim_entry($domain); $zone.= $this->dkim_entry($domain);
$zone.= $this->mail_autoconfig_entry($domain); $zone.= $this->mail_autoconfig_entry($domain);
$zone.="\n;;; END ALTERNC AUTOGENERATE CONFIGURATION\n"; $zone.="\n;;; END ALTERNC AUTOGENERATE CONFIGURATION\n";
$zone.=$this->get_persistent($domain); $zone.=$this->get_persistent($domain);
$domainInfo = $this->get_domain_summary($domain); $domainInfo = $this->get_domain_summary($domain);
// FIXME check those vars // FIXME check those vars
$zone = strtr($zone, array( $zone = strtr($zone, array(
"%%fqdn%%"=>"$L_FQDN", "%%fqdn%%"=>"$L_FQDN",
"%%ns1%%"=>"$L_NS1_HOSTNAME", "%%ns1%%"=>"$L_NS1_HOSTNAME",
"%%ns2%%"=>"$L_NS2_HOSTNAME", "%%ns2%%"=>"$L_NS2_HOSTNAME",
@ -344,146 +344,146 @@ class system_bind {
"@@SERIAL@@"=>$this->get_serial($domain), "@@SERIAL@@"=>$this->get_serial($domain),
"@@PUBLIC_IP@@"=>"$L_PUBLIC_IP", "@@PUBLIC_IP@@"=>"$L_PUBLIC_IP",
"@@ZONETTL@@"=> $domainInfo['zonettl'], "@@ZONETTL@@"=> $domainInfo['zonettl'],
)); ));
return $zone; return $zone;
}
/**
*
* @param string $domain
*/
function reload_zone($domain) {
exec($this->RNDC." reload ".escapeshellarg($domain), $output, $return_value);
if ($return_value != 0 ) {
echo "ERROR: Reload zone failed for zone $domain\n";
} }
}
/** /**
* return true if zone is locked *
* * @param string $domain
* @param string $domain */
* @return boolean function reload_zone($domain) {
*/ exec($this->RNDC." reload ".escapeshellarg($domain), $output, $return_value);
function is_locked($domain) { if ($return_value != 0 ) {
preg_match_all("/(\;\s*LOCKED:YES)/i", $this->get_zone_file($domain), $output_array); echo "ERROR: Reload zone failed for zone $domain\n";
if (isset($output_array[1][0]) && !empty($output_array[1][0])) { }
return true;
} }
return false;
}
/** /**
* * return true if zone is locked
* @global m_mysql $db *
* @global m_dom $dom * @param string $domain
* @param string $domain * @return boolean
* @return boolean */
*/ function is_locked($domain) {
function save_zone($domain) { preg_match_all("/(\;\s*LOCKED:YES)/i", $this->get_zone_file($domain), $output_array);
global $db, $dom; if (isset($output_array[1][0]) && !empty($output_array[1][0])) {
return true;
}
return false;
}
// Do not save if the zone is LOCKED /**
if ( $this->is_locked($domain)) { *
$dom->set_dns_result($domain, "The zone file of this domain is locked. Contact your administrator."); // If edit, change dummy_for_translation * @global m_mysql $db
$dom->set_dns_action($domain, 'OK'); * @global m_dom $dom
return false; * @param string $domain
} * @return boolean
*/
function save_zone($domain) {
global $db, $dom;
// Do not save if the zone is LOCKED
if ( $this->is_locked($domain)) {
$dom->set_dns_result($domain, "The zone file of this domain is locked. Contact your administrator."); // If edit, change dummy_for_translation
$dom->set_dns_action($domain, 'OK');
return false;
}
// Save file, and apply chmod/chown // Save file, and apply chmod/chown
$file=$this->get_zone_file_uri($domain); $file=$this->get_zone_file_uri($domain);
file_put_contents($file, $this->get_zone($domain)); file_put_contents($file, $this->get_zone($domain));
chown($file, 'bind'); chown($file, 'bind');
chmod($file, 0640); chmod($file, 0640);
$dom->set_dns_action($domain, 'OK'); $dom->set_dns_action($domain, 'OK');
return true; // fixme add tests return true; // fixme add tests
}
/**
* Delete the zone configuration file
*
* @param string $domain
* @return boolean
*/
function delete_zone($domain) {
$file=$this->get_zone_file_uri($domain);
if (file_exists($file)) {
unlink($file);
}
$this->dkim_delete($domain);
return true;
}
/**
*
* @global m_hooks $hooks
* @return boolean
*/
function reload_named() {
global $hooks;
// Generate the new conf file
$new_named_conf="// DO NOT EDIT\n// This file is generated by Alternc.\n// Every changes you'll make will be overwrited.\n";
$tpl=file_get_contents($this->NAMED_TEMPLATE);
foreach ($this->get_domain_summary() as $domain => $ds ) {
if ( ! $ds['gesdns'] || strtoupper($ds['dns_action']) == 'DELETE' ) continue;
$new_named_conf.=strtr($tpl, array("@@DOMAINE@@"=>$domain, "@@ZONE_FILE@@"=>$this->get_zone_file_uri($domain)));
} }
// Get the actual conf file /**
$old_named_conf = @file_get_contents($this->NAMED_CONF); * Delete the zone configuration file
*
// Apply new configuration only if there are some differences * @param string $domain
if ($old_named_conf != $new_named_conf ) { * @return boolean
file_put_contents($this->NAMED_CONF,$new_named_conf); */
chown($this->NAMED_CONF, 'bind'); function delete_zone($domain) {
chmod($this->NAMED_CONF, 0640); $file=$this->get_zone_file_uri($domain);
exec($this->RNDC." reconfig"); if (file_exists($file)) {
$hooks->invoke_scripts("/usr/lib/alternc/reload.d", array('dns_reconfig') ); unlink($file);
}
$this->dkim_delete($domain);
return true;
} }
return true; /**
} *
* @global m_hooks $hooks
* @return boolean
*/
function reload_named() {
global $hooks;
// Generate the new conf file
$new_named_conf="// DO NOT EDIT\n// This file is generated by Alternc.\n// Every changes you'll make will be overwrited.\n";
$tpl=file_get_contents($this->NAMED_TEMPLATE);
foreach ($this->get_domain_summary() as $domain => $ds ) {
if ( ! $ds['gesdns'] || strtoupper($ds['dns_action']) == 'DELETE' ) continue;
$new_named_conf.=strtr($tpl, array("@@DOMAINE@@"=>$domain, "@@ZONE_FILE@@"=>$this->get_zone_file_uri($domain)));
}
/** // Get the actual conf file
* Regenerate bind configuration and load it $old_named_conf = @file_get_contents($this->NAMED_CONF);
*
* @global m_hooks $hooks
* @param boolean $all
* @return boolean
*/
function regenerate_conf($all=false) {
global $hooks;
foreach ($this->get_domain_summary() as $domain => $ds ) { // Apply new configuration only if there are some differences
if ( ! $ds['gesdns'] && strtoupper($ds['dns_action']) == 'OK' ) continue; // Skip if we do not manage DNS and is up-to-date for this domain if ($old_named_conf != $new_named_conf ) {
file_put_contents($this->NAMED_CONF,$new_named_conf);
chown($this->NAMED_CONF, 'bind');
chmod($this->NAMED_CONF, 0640);
exec($this->RNDC." reconfig");
$hooks->invoke_scripts("/usr/lib/alternc/reload.d", array('dns_reconfig') );
}
if ( (strtoupper($ds['dns_action']) == 'DELETE' ) || return true;
(strtoupper($ds['dns_action']) == 'UPDATE' && $ds['gesdns']==false ) // in case we update the zone to disable DNS management }
) {
$this->delete_zone($domain);
continue;
}
if ( ( $all || strtoupper($ds['dns_action']) == 'UPDATE' ) && $ds['gesdns'] ) { /**
$this->save_zone($domain); * Regenerate bind configuration and load it
$this->reload_zone($domain); *
$hooks->invoke_scripts("/usr/lib/alternc/reload.d", array('dns_reload_zone', $domain) ); * @global m_hooks $hooks
} * @param boolean $all
} // end foreach domain * @return boolean
*/
function regenerate_conf($all=false) {
global $hooks;
$this->dkim_refresh_list(); foreach ($this->get_domain_summary() as $domain => $ds ) {
$this->reload_named(); if ( ! $ds['gesdns'] && strtoupper($ds['dns_action']) == 'OK' ) continue; // Skip if we do not manage DNS and is up-to-date for this domain
return true;
}
/** if ( (strtoupper($ds['dns_action']) == 'DELETE' ) ||
* (strtoupper($ds['dns_action']) == 'UPDATE' && $ds['gesdns']==false ) // in case we update the zone to disable DNS management
*/ ) {
private function dummy_for_translation() { $this->delete_zone($domain);
_("The zone file of this domain is locked. Contact your administrator."); continue;
} }
if ( ( $all || strtoupper($ds['dns_action']) == 'UPDATE' ) && $ds['gesdns'] ) {
$this->save_zone($domain);
$this->reload_zone($domain);
$hooks->invoke_scripts("/usr/lib/alternc/reload.d", array('dns_reload_zone', $domain) );
}
} // end foreach domain
$this->dkim_refresh_list();
$this->reload_named();
return true;
}
/**
*
*/
private function dummy_for_translation() {
_("The zone file of this domain is locked. Contact your administrator.");
}
} // class } // class

View File

@ -27,7 +27,7 @@
Original Author of file: Benjamin Sonntag Original Author of file: Benjamin Sonntag
Purpose of file: General configuration file for AlternC Desktop Purpose of file: General configuration file for AlternC Desktop
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
define('DO_XHPROF_STATS', FALSE); define('DO_XHPROF_STATS', FALSE);
if (DO_XHPROF_STATS) { if (DO_XHPROF_STATS) {
@ -45,15 +45,15 @@ session_start();
/* /*
Si vous voulez mettre le bureau en maintenance, decommentez le code ci-dessous Si vous voulez mettre le bureau en maintenance, decommentez le code ci-dessous
et mettez votre ip dans le IF pour que seule votre ip puisse acceder au bureau : et mettez votre ip dans le IF pour que seule votre ip puisse acceder au bureau :
*/ */
/* * / /* * /
if (getenv("REMOTE_ADDR")!="127.0.0.1") { if (getenv("REMOTE_ADDR")!="127.0.0.1") {
echo "Le bureau AlternC est en vacances jusqu'a minuit pour maintenance.<br> echo "Le bureau AlternC est en vacances jusqu'a minuit pour maintenance.<br>
Merci de revenir plus tard."; Merci de revenir plus tard.";
exit(); exit();
} }
/* */ /* */
if (ini_get("safe_mode")) { if (ini_get("safe_mode")) {
echo _("SAFE MODE IS ENABLED for the web panel ! It's a bug in your php or apache configuration, please fix it !!"); echo _("SAFE MODE IS ENABLED for the web panel ! It's a bug in your php or apache configuration, please fix it !!");
@ -125,10 +125,10 @@ require_once($root . "/class/variables.php");
*/ */
class DB_system extends DB_Sql { class DB_system extends DB_Sql {
function __construct() { function __construct() {
global $L_MYSQL_HOST,$L_MYSQL_DATABASE,$L_MYSQL_LOGIN,$L_MYSQL_PWD; global $L_MYSQL_HOST,$L_MYSQL_DATABASE,$L_MYSQL_LOGIN,$L_MYSQL_PWD;
parent::__construct($L_MYSQL_DATABASE, $L_MYSQL_HOST, $L_MYSQL_LOGIN, $L_MYSQL_PWD); parent::__construct($L_MYSQL_DATABASE, $L_MYSQL_HOST, $L_MYSQL_LOGIN, $L_MYSQL_PWD);
} }
} }
$db = new DB_system(); $db = new DB_system();
@ -147,8 +147,8 @@ foreach (glob($root . "class/m_*.php") as $di) {
} }
} }
/* THE DEFAULT CLASSES ARE : /* THE DEFAULT CLASSES ARE :
dom, ftp, mail, quota, bro, admin, mem, mysql, err, variables dom, ftp, mail, quota, bro, admin, mem, mysql, err, variables
*/ */
// Load file for the system class. // Load file for the system class.
// Those class will not be build by default. // Those class will not be build by default.
@ -176,8 +176,8 @@ if (isset($_SERVER["HTTP_X_FORWARDED_PROTO"]) && $_SERVER["HTTP_X_FORWARDED_PROT
if ((variable_get('force_https', '0', "This variable is set to 0 (default) if users can access the management desktop through HTTP, otherwise we force HTTPS")&&(!isset($_SERVER["HTTPS"])|| ($_SERVER["HTTPS"] != "on")))) { if ((variable_get('force_https', '0', "This variable is set to 0 (default) if users can access the management desktop through HTTP, otherwise we force HTTPS")&&(!isset($_SERVER["HTTPS"])|| ($_SERVER["HTTPS"] != "on")))) {
// do not redirect if access is not by HTTP(s) // do not redirect if access is not by HTTP(s)
if (isset($_SERVER['REQUEST_URI'])) { if (isset($_SERVER['REQUEST_URI'])) {
header("Location: https://".$_SERVER["HTTP_HOST"].$_SERVER['REQUEST_URI']); header("Location: https://".$_SERVER["HTTP_HOST"].$_SERVER['REQUEST_URI']);
exit; exit;
} }
} }
@ -186,10 +186,10 @@ if ((variable_get('force_https', '0', "This variable is set to 0 (default) if us
$fatalcsrf=false; $fatalcsrf=false;
if (count($_POST) && !defined("NOCSRF")) { if (count($_POST) && !defined("NOCSRF")) {
if (csrf_check()<=0) { if (csrf_check()<=0) {
// We will trigger the error LATER in the code => need initialization of classes // We will trigger the error LATER in the code => need initialization of classes
$fatalcsrf=true; $fatalcsrf=true;
} }
} }
/* Check the User identity (if required) */ /* Check the User identity (if required) */
@ -233,10 +233,10 @@ if ((variable_get('sql_max_username_length', NULL)==NULL)||(variable_get('sql_ma
$result = $db->query("SELECT (SELECT CHARACTER_MAXIMUM_LENGTH length FROM information_schema.columns WHERE TABLE_SCHEMA='mysql' and TABLE_NAME='user' and COLUMN_NAME='User') username, (SELECT CHARACTER_MAXIMUM_LENGTH length FROM information_schema.columns WHERE TABLE_SCHEMA='mysql' and TABLE_NAME='db' and COLUMN_NAME='Db') `database`"); $result = $db->query("SELECT (SELECT CHARACTER_MAXIMUM_LENGTH length FROM information_schema.columns WHERE TABLE_SCHEMA='mysql' and TABLE_NAME='user' and COLUMN_NAME='User') username, (SELECT CHARACTER_MAXIMUM_LENGTH length FROM information_schema.columns WHERE TABLE_SCHEMA='mysql' and TABLE_NAME='db' and COLUMN_NAME='Db') `database`");
if ($db->next_record($result)) { if ($db->next_record($result)) {
$variable = $db->Record; $variable = $db->Record;
$variable['username']=min(128, $variable['username']); $variable['username']=min(128, $variable['username']);
$variable['database']=min($variable['database'], $variable['username']); $variable['database']=min($variable['database'], $variable['username']);
variable_set('sql_max_username_length', $variable['username'], 'Maximum length allowed for SQL usernames by your SQL server (do not modify unless you know what you do)'); variable_set('sql_max_username_length', $variable['username'], 'Maximum length allowed for SQL usernames by your SQL server (do not modify unless you know what you do)');
variable_set('sql_max_database_length', $variable['database'], 'Maximum length allowed for SQL database names by your SQL server (do not modify unless you know what you do)'); variable_set('sql_max_database_length', $variable['database'], 'Maximum length allowed for SQL database names by your SQL server (do not modify unless you know what you do)');
} }
} }

View File

@ -27,7 +27,7 @@
Original Author of file: Benjamin Sonntag Original Author of file: Benjamin Sonntag
Purpose of file: General configuration file for AlternC Desktop Purpose of file: General configuration file for AlternC Desktop
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
define('NOCHECK', 1); define('NOCHECK', 1);
require_once("config.php"); require_once("config.php");

View File

@ -10,287 +10,287 @@
class DB_Sql { class DB_Sql {
/* public: connection parameters */ /* public: connection parameters */
private $Host; private $Host;
private $Database; private $Database;
private $User; private $User;
private $Password; private $Password;
/* public: configuration parameters */ /* public: configuration parameters */
private $Auto_Free = False; // Set to True for automatic mysql_free_result() private $Auto_Free = False; // Set to True for automatic mysql_free_result()
private $Debug = False; // Set to 1 for debugging messages. private $Debug = False; // Set to 1 for debugging messages.
private $Halt_On_Error = "no"; // "yes" (halt with message), "no" (ignore errors quietly), "report" (ignore errror, but spit a warning) private $Halt_On_Error = "no"; // "yes" (halt with message), "no" (ignore errors quietly), "report" (ignore errror, but spit a warning)
private $Seq_Table = "db_sequence"; private $Seq_Table = "db_sequence";
/* public: result array and current row number */ /* public: result array and current row number */
public /* FIXME */ $Record = array(); public /* FIXME */ $Record = array();
private $Row = 0; private $Row = 0;
private $num_rows; private $num_rows;
/* public: current error number and error text */ /* public: current error number and error text */
private $Errno; private $Errno;
private $Error; private $Error;
/* private: link and query handles */ /* private: link and query handles */
private $Query_String; private $Query_String;
/* PDO related variables */ /* PDO related variables */
private $pdo_instance = NULL; private $pdo_instance = NULL;
private $pdo_query = NULL; private $pdo_query = NULL;
/** /**
* Constructor * Constructor
*/ */
function __construct($db, $host, $user, $passwd) { function __construct($db, $host, $user, $passwd) {
$dsn = sprintf('mysql:dbname=%s;host=%s', $db, $host); $dsn = sprintf('mysql:dbname=%s;host=%s', $db, $host);
try { try {
$this->pdo_instance = new PDO($dsn, $user, $passwd); $this->pdo_instance = new PDO($dsn, $user, $passwd);
} catch (PDOException $e) { } catch (PDOException $e) {
echo "Mysql", "PDO instance", $e->getMessage(); echo "Mysql", "PDO instance", $e->getMessage();
return FALSE; return FALSE;
}
}
/**
* function for MySQL database connection management
*
* This function manages the connection to the MySQL database.
*
* @param $Database name of the database
* @param $Host DNS of the MySQL hosting server
* @param $User the user's name
* @param $Password the user's password
*
* @return the class variable $Link_ID
*/
function connect($Database = "", $Host = "", $User = "", $Password = "") {
$this->halt('Mysql::connect() : This function should no longer be used');
/* Handle defaults */
if ("" == $Database)
$Database = $this->Database;
if ("" == $Host)
$Host = $this->Host;
if ("" == $User)
$User = $this->User;
if ("" == $Password)
$Password = $this->Password;
if (!$this->pdo_instance) {
$dsn = sprintf('mysql:dbname=%s;host=%s', $Database, $Host);
try {
$this->pdo_instance = new PDO($dsn, $User, $Password);
} catch (PDOException $e) {
$this->halt("Mysql::PDO_instance" . $e->getMessage());
return FALSE;
} }
} }
/**
* function for MySQL database connection management
*
* This function manages the connection to the MySQL database.
*
* @param $Database name of the database
* @param $Host DNS of the MySQL hosting server
* @param $User the user's name
* @param $Password the user's password
*
* @return the class variable $Link_ID
*/
function connect($Database = "", $Host = "", $User = "", $Password = "") {
$this->halt('Mysql::connect() : This function should no longer be used');
/* Handle defaults */
if ("" == $Database)
$Database = $this->Database;
if ("" == $Host)
$Host = $this->Host;
if ("" == $User)
$User = $this->User;
if ("" == $Password)
$Password = $this->Password;
if (!$this->pdo_instance) {
$dsn = sprintf('mysql:dbname=%s;host=%s', $Database, $Host);
try {
$this->pdo_instance = new PDO($dsn, $User, $Password);
} catch (PDOException $e) {
$this->halt("Mysql::PDO_instance" . $e->getMessage());
return FALSE;
}
}
return True; return True;
} }
/** /**
* Discard the query result * Discard the query result
* *
* This function discards the last query result. * This function discards the last query result.
*/ */
function free() { function free() {
$this->pdo_query->closeCursor(); $this->pdo_query->closeCursor();
} }
function is_connected() { function is_connected() {
return $this->pdo_instance != FALSE; return $this->pdo_instance != FALSE;
} }
function last_error() { function last_error() {
return $this->Error; return $this->Error;
} }
/** /**
* Perform a query * Perform a query
* *
* This function performs the MySQL query described in the string parameter * This function performs the MySQL query described in the string parameter
* *
* @param a string describing the MySQL query * @param a string describing the MySQL query
* @param arguments is an optionnal array for future use with PDO parametrized requests * @param arguments is an optionnal array for future use with PDO parametrized requests
* @return the $Query_ID class variable (null if fails) * @return the $Query_ID class variable (null if fails)
*/ */
function query($Query_String, $arguments = false) { function query($Query_String, $arguments = false) {
global $debug_alternc; global $debug_alternc;
if (empty($Query_String) || !$this->is_connected()) if (empty($Query_String) || !$this->is_connected())
return FALSE; return FALSE;
$this->Query_String = $Query_String; $this->Query_String = $Query_String;
if ($this->Debug) if ($this->Debug)
printf("Debug: query = %s<br />\n", $Query_String); printf("Debug: query = %s<br />\n", $Query_String);
$debug_chrono_start = microtime(true); $debug_chrono_start = microtime(true);
if ($arguments===false) { if ($arguments===false) {
$this->pdo_query = $this->pdo_instance->query($Query_String); $this->pdo_query = $this->pdo_instance->query($Query_String);
$exec_state = is_object($this->pdo_query); $exec_state = is_object($this->pdo_query);
} else { } else {
$this->pdo_query = $this->pdo_instance->prepare($this->Query_String); $this->pdo_query = $this->pdo_instance->prepare($this->Query_String);
$exec_state = ($arguments) ? $this->pdo_query->execute($arguments) $exec_state = ($arguments) ? $this->pdo_query->execute($arguments)
: $this->pdo_query->execute(); : $this->pdo_query->execute();
// WARNING: this ternary is when we pass array() as $arguments // WARNING: this ternary is when we pass array() as $arguments
} }
$debug_chrono_start = (microtime(true) - $debug_chrono_start)*1000; $debug_chrono_start = (microtime(true) - $debug_chrono_start)*1000;
$this->Row = 0; $this->Row = 0;
if ($exec_state == FALSE) { if ($exec_state == FALSE) {
if (is_object($this->pdo_query)) { if (is_object($this->pdo_query)) {
$this->Errno = $this->pdo_query->errorCode();
$this->Error = $this->pdo_query->errorInfo();
} else {
$this->Errno = $this->pdo_instance->errorCode();
$this->Error = $this->pdo_instance->errorInfo();
}
if( defined("THROW_EXCEPTIONS") && THROW_EXCEPTIONS ){
throw new \Exception("Mysql query failed : $this->Error");
}
$this->halt("SQL Error: ".$Query_String);
return FALSE;
}
if (isset($debug_alternc)) {
$debug_alternc->add("SQL Query : (".substr($debug_chrono_start,0,5)." ms)\t $Query_String");
$debug_alternc->nb_sql_query++;
$debug_alternc->tps_sql_query += $debug_chrono_start;
}
return TRUE;
}
/**
* walk result set
*
* This function tests if a new record is available in the current
* query result.
*
* @return TRUE if a new record is available
*/
function next_record() {
if (!$this->pdo_query) {
$this->halt("next_record called with no query pending.");
return FALSE;
}
$this->Record = $this->pdo_query->fetch(PDO::FETCH_BOTH);
$this->Row++;
$this->Errno = $this->pdo_query->errorCode(); $this->Errno = $this->pdo_query->errorCode();
$this->Error = $this->pdo_query->errorInfo(); $this->Error = $this->pdo_query->errorInfo();
} else {
$this->Errno = $this->pdo_instance->errorCode();
$this->Error = $this->pdo_instance->errorInfo();
}
if( defined("THROW_EXCEPTIONS") && THROW_EXCEPTIONS ){ if ($this->Record == FALSE) {
throw new \Exception("Mysql query failed : $this->Error"); if ($this->Auto_Free)
$this->free();
return FALSE;
} }
$this->halt("SQL Error: ".$Query_String);
return FALSE;
}
if (isset($debug_alternc)) {
$debug_alternc->add("SQL Query : (".substr($debug_chrono_start,0,5)." ms)\t $Query_String");
$debug_alternc->nb_sql_query++;
$debug_alternc->tps_sql_query += $debug_chrono_start;
}
return TRUE; return TRUE;
}
/**
* walk result set
*
* This function tests if a new record is available in the current
* query result.
*
* @return TRUE if a new record is available
*/
function next_record() {
if (!$this->pdo_query) {
$this->halt("next_record called with no query pending.");
return FALSE;
}
$this->Record = $this->pdo_query->fetch(PDO::FETCH_BOTH);
$this->Row++;
$this->Errno = $this->pdo_query->errorCode();
$this->Error = $this->pdo_query->errorInfo();
if ($this->Record == FALSE) {
if ($this->Auto_Free)
$this->free();
return FALSE;
} }
return TRUE; /* public: table locking */
} function lock($table, $mode="write") {
if (!$this->is_connected())
/* public: table locking */ return FALSE;
function lock($table, $mode="write") {
if (!$this->is_connected())
return FALSE;
$query="lock tables "; $query="lock tables ";
if (is_array($table)) { if (is_array($table)) {
while (list($key,$value)=each($table)) { while (list($key,$value)=each($table)) {
if ($key=="read" && $key!=0) { if ($key=="read" && $key!=0) {
$query.="$value read, "; $query.="$value read, ";
} else { } else {
$query.="$value $mode, "; $query.="$value $mode, ";
} }
}
$query=substr($query,0,-2);
} else {
$query.="$table $mode";
} }
$query=substr($query,0,-2);
} else {
$query.="$table $mode";
}
if (!$this->query($query)) { if (!$this->query($query)) {
$this->halt("lock($table, $mode) failed."); $this->halt("lock($table, $mode) failed.");
return FALSE; return FALSE;
} }
return TRUE; return TRUE;
} }
function unlock() { function unlock() {
if (!$this->is_connected()) if (!$this->is_connected())
return FALSE; return FALSE;
if (!$this->query('unlock tables')) { if (!$this->query('unlock tables')) {
$this->halt("unlock() failed."); $this->halt("unlock() failed.");
return FALSE; return FALSE;
} }
} }
/* public: evaluate the result (size, width) */ /* public: evaluate the result (size, width) */
function affected_rows() { function affected_rows() {
return $this->pdo_query->rowCount(); return $this->pdo_query->rowCount();
} }
function num_rows() { function num_rows() {
return $this->pdo_query->rowCount(); return $this->pdo_query->rowCount();
} }
function num_fields() { function num_fields() {
return $this->pdo_query->columnCount(); return $this->pdo_query->columnCount();
} }
/* public: shorthand notation */ /* public: shorthand notation */
function nf() { function nf() {
return $this->num_rows(); return $this->num_rows();
} }
function np() { function np() {
print $this->num_rows(); print $this->num_rows();
} }
/** /**
* @param string $Name * @param string $Name
* @return integer * @return integer
*/ */
function f($Name) { function f($Name) {
if (isset($this->Record[$Name])) if (isset($this->Record[$Name]))
return $this->Record[$Name]; return $this->Record[$Name];
else else
return false; return false;
} }
function current_record() { function current_record() {
return $this->Record; return $this->Record;
} }
function p($Name) { function p($Name) {
print $this->Record[$Name]; print $this->Record[$Name];
} }
function lastid() { function lastid() {
return $this->pdo_instance->lastInsertId(); return $this->pdo_instance->lastInsertId();
} }
/** /**
* Escape a string to use it into a SQL PDO query * Escape a string to use it into a SQL PDO query
* @param string string to escape * @param string string to escape
* @return string escaped string * @return string escaped string
*/ */
function quote($string) { function quote($string) {
return $this->pdo_instance->quote($string); return $this->pdo_instance->quote($string);
} }
/** /**
@ -298,85 +298,85 @@ class DB_Sql {
* @param query string query to execute * @param query string query to execute
* @return integer the number of affected rows * @return integer the number of affected rows
*/ */
function exec($query) { function exec($query) {
return $this->pdo_instance->exec($query); return $this->pdo_instance->exec($query);
} }
/* public: sequence numbers */ /* public: sequence numbers */
function nextid($seq_name) { function nextid($seq_name) {
if (!$this->is_connected()) if (!$this->is_connected())
return FALSE; return FALSE;
if ($this->lock($this->Seq_Table)) { if ($this->lock($this->Seq_Table)) {
/* get sequence number (locked) and increment */ /* get sequence number (locked) and increment */
$q = sprintf("select nextid from %s where seq_name = '%s'", $q = sprintf("select nextid from %s where seq_name = '%s'",
$this->Seq_Table, $this->Seq_Table,
$seq_name); $seq_name);
$this->query($q); $this->query($q);
$this->next_record(); $this->next_record();
$id = $this->f('nextid'); $id = $this->f('nextid');
/* No current value, make one */ /* No current value, make one */
if (!$id) { if (!$id) {
$currentid = 0; $currentid = 0;
$q = sprintf("insert into %s values('%s', %s)", $q = sprintf("insert into %s values('%s', %s)",
$this->Seq_Table, $this->Seq_Table,
$seq_name, $seq_name,
$currentid); $currentid);
$this->query($q); $this->query($q);
} else { } else {
$currentid = $id; $currentid = $id;
} }
$nextid = $currentid + 1; $nextid = $currentid + 1;
$q = sprintf("update %s set nextid = '%s' where seq_name = '%s'", $q = sprintf("update %s set nextid = '%s' where seq_name = '%s'",
$this->Seq_Table, $this->Seq_Table,
$nextid, $nextid,
$seq_name); $seq_name);
$this->query($q); $this->query($q);
$this->unlock(); $this->unlock();
} else { } else {
$this->halt("cannot lock ".$this->Seq_Table." - has it been created?"); $this->halt("cannot lock ".$this->Seq_Table." - has it been created?");
return FALSE; return FALSE;
} }
return $nextid; return $nextid;
} }
/* public: return table metadata */ /* public: return table metadata */
function metadata($table='',$full=false) { function metadata($table='',$full=false) {
global $msg; global $msg;
$msg->raise("ERROR", 'Mysql', 'function is no longer implemented (metadata())'); $msg->raise("ERROR", 'Mysql', 'function is no longer implemented (metadata())');
return FALSE; return FALSE;
} }
/* private: error handling */ /* private: error handling */
function halt($msg) { function halt($msg) {
if ($this->Halt_On_Error == "no") if ($this->Halt_On_Error == "no")
return; return;
$this->haltmsg($msg); $this->haltmsg($msg);
if ($this->Halt_On_Error != "report") if ($this->Halt_On_Error != "report")
die("Session halted."); die("Session halted.");
} }
function haltmsg($msg) { function haltmsg($msg) {
printf("</td></tr></table><b>Database error:</b> %s<br />\n", $msg); printf("</td></tr></table><b>Database error:</b> %s<br />\n", $msg);
printf("<b>MySQL Error</b>: %s (%s)<br />\n", printf("<b>MySQL Error</b>: %s (%s)<br />\n",
$this->Errno, $this->Errno,
implode("\n", $this->Error)); implode("\n", $this->Error));
} }
function table_names() { function table_names() {
$this->query("SHOW TABLES"); $this->query("SHOW TABLES");
$return = array(); $return = array();
while ($this->next_record()) while ($this->next_record())
$return[] = array('table_name' => $this->p(0), 'tablespace_name' => $this->Database, 'database' => $this->Database); $return[] = array('table_name' => $this->p(0), 'tablespace_name' => $this->Database, 'database' => $this->Database);
return $return; return $return;
} }
} }
?> ?>

View File

@ -22,7 +22,7 @@
---------------------------------------------------------------------- ----------------------------------------------------------------------
Purpose of file: Miscellaneous functions globally used Purpose of file: Miscellaneous functions globally used
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
/** /**
* Format a field value for input or textarea : * Format a field value for input or textarea :
@ -528,7 +528,7 @@ function _md5cr($pass, $salt = "") {
function split_mysql_database_name($dbname) { function split_mysql_database_name($dbname) {
$db_exploded_name = explode("_", $dbname); $db_exploded_name = explode("_", $dbname);
return array($db_exploded_name[0], return array($db_exploded_name[0],
implode("_", array_slice($db_exploded_name, 1))); implode("_", array_slice($db_exploded_name, 1)));
} }
/* ----------------------------------------------------------------- */ /* ----------------------------------------------------------------- */
@ -614,16 +614,16 @@ function eoption($values, $cur, $onedim = false) {
} }
/** /**
/* Echo the HTMLSpecialChars version of a value. /* Echo the HTMLSpecialChars version of a value.
* Must be called when pre-filling fields values in forms such as : * Must be called when pre-filling fields values in forms such as :
* <input type="text" name="toto" value="<?php ehe($toto); ?>" /> * <input type="text" name="toto" value="<?php ehe($toto); ?>" />
* Use the charset of the current language for transcription * Use the charset of the current language for transcription
* *
* @global string $charset * @global string $charset
* @param string $str * @param string $str
* @param boolean $affiche * @param boolean $affiche
* @return string * @return string
*/ */
function ehe($str, $affiche = TRUE) { function ehe($str, $affiche = TRUE) {
global $charset; global $charset;
$retour = htmlspecialchars($str, ENT_QUOTES|ENT_SUBSTITUTE, $charset); $retour = htmlspecialchars($str, ENT_QUOTES|ENT_SUBSTITUTE, $charset);
@ -634,16 +634,16 @@ function ehe($str, $affiche = TRUE) {
} }
/** /**
/* Echo the URLENCODED version of a value. /* Echo the URLENCODED version of a value.
* Must be called when pre-filling fields values in URLS such as : * Must be called when pre-filling fields values in URLS such as :
* document.location='logs_tail.php?file=<?php eue($file); ?> * document.location='logs_tail.php?file=<?php eue($file); ?>
* Use the charset of the current language for transcription * Use the charset of the current language for transcription
* *
* @global string $charset * @global string $charset
* @param string $str * @param string $str
* @param boolean $affiche * @param boolean $affiche
* @return string * @return string
*/ */
function eue($str, $affiche = TRUE) { function eue($str, $affiche = TRUE) {
global $charset; global $charset;
$retour = urlencode($str); $retour = urlencode($str);
@ -677,26 +677,26 @@ function getFields($fields, $requestOnly = false) {
$method = "_" . strtoupper($options[0]); $method = "_" . strtoupper($options[0]);
} }
switch ($options[1]) { switch ($options[1]) {
case "integer": case "integer":
$vars[$name] = (isset($GLOBALS[$method][$name]) && is_numeric($GLOBALS[$method][$name]) ? intval($GLOBALS[$method][$name]) : $options[2]); $vars[$name] = (isset($GLOBALS[$method][$name]) && is_numeric($GLOBALS[$method][$name]) ? intval($GLOBALS[$method][$name]) : $options[2]);
break; break;
case "float": case "float":
$vars[$name] = (isset($GLOBALS[$method][$name]) && is_numeric($GLOBALS[$method][$name]) ? floatval($GLOBALS[$method][$name]) : $options[2]); $vars[$name] = (isset($GLOBALS[$method][$name]) && is_numeric($GLOBALS[$method][$name]) ? floatval($GLOBALS[$method][$name]) : $options[2]);
break; break;
case "string": case "string":
$vars[$name] = (isset($GLOBALS[$method][$name]) ? trim($GLOBALS[$method][$name]) : $options[2]); $vars[$name] = (isset($GLOBALS[$method][$name]) ? trim($GLOBALS[$method][$name]) : $options[2]);
break; break;
case "array": case "array":
$vars[$name] = (isset($GLOBALS[$method][$name]) && is_array($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]); $vars[$name] = (isset($GLOBALS[$method][$name]) && is_array($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]);
break; break;
case "boolean": case "boolean":
$vars[$name] = (isset($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]); $vars[$name] = (isset($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]);
break; break;
case "file": case "file":
$vars[$name] = (isset($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]); $vars[$name] = (isset($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]);
break; break;
default: default:
die("Illegal method type used for field " . $name . " : " . $options[1]); die("Illegal method type used for field " . $name . " : " . $options[1]);
} }
} }
@ -1000,41 +1000,41 @@ function fHSVtoRGB($iH, $iS, $iV) {
$dX = $dC * (1 - abs($dT - 1)); // as used in the Wikipedia link $dX = $dC * (1 - abs($dT - 1)); // as used in the Wikipedia link
switch ($dH) { switch ($dH) {
case($dH >= 0.0 && $dH < 1.0): case($dH >= 0.0 && $dH < 1.0):
$dR = $dC; $dR = $dC;
$dG = $dX; $dG = $dX;
$dB = 0.0; $dB = 0.0;
break; break;
case($dH >= 1.0 && $dH < 2.0): case($dH >= 1.0 && $dH < 2.0):
$dR = $dX; $dR = $dX;
$dG = $dC; $dG = $dC;
$dB = 0.0; $dB = 0.0;
break; break;
case($dH >= 2.0 && $dH < 3.0): case($dH >= 2.0 && $dH < 3.0):
$dR = 0.0; $dR = 0.0;
$dG = $dC; $dG = $dC;
$dB = $dX; $dB = $dX;
break; break;
case($dH >= 3.0 && $dH < 4.0): case($dH >= 3.0 && $dH < 4.0):
$dR = 0.0; $dR = 0.0;
$dG = $dX; $dG = $dX;
$dB = $dC; $dB = $dC;
break; break;
case($dH >= 4.0 && $dH < 5.0): case($dH >= 4.0 && $dH < 5.0):
$dR = $dX; $dR = $dX;
$dG = 0.0; $dG = 0.0;
$dB = $dC; $dB = $dC;
break; break;
case($dH >= 5.0 && $dH < 6.0): case($dH >= 5.0 && $dH < 6.0):
$dR = $dC; $dR = $dC;
$dG = 0.0; $dG = 0.0;
$dB = $dX; $dB = $dX;
break; break;
default: default:
$dR = 0.0; $dR = 0.0;
$dG = 0.0; $dG = 0.0;
$dB = 0.0; $dB = 0.0;
break; break;
} }
$dM = $dV - $dC; $dM = $dV - $dC;
@ -1130,8 +1130,8 @@ function csrf_get($return=false) {
$_SESSION["csrf"]=md5(mt_rand().mt_rand().mt_rand()); $_SESSION["csrf"]=md5(mt_rand().mt_rand().mt_rand());
} }
if ($token=="") { if ($token=="") {
$token=md5(mt_rand().mt_rand().mt_rand()); $token=md5(mt_rand().mt_rand().mt_rand());
$db->query("INSERT INTO csrf SET cookie=?, token=?, created=NOW(), used=0;",array($_SESSION["csrf"],$token)); $db->query("INSERT INTO csrf SET cookie=?, token=?, created=NOW(), used=0;",array($_SESSION["csrf"],$token));
} }
if ($return) if ($return)
return $token; return $token;

View File

@ -3,11 +3,11 @@
$lang_translation = array(# If you comment lang here, it won't be displayed. $lang_translation = array(# If you comment lang here, it won't be displayed.
"fr_FR" => "Français", "fr_FR" => "Français",
"en_US" => "English", "en_US" => "English",
"es_ES" => "Español", "es_ES" => "Español",
# "it_IT" => "Italiano", # "it_IT" => "Italiano",
# "de_DE" => "Deutsch", # "de_DE" => "Deutsch",
# "pt_BR" => "Portuguese", # "pt_BR" => "Portuguese",
# "nl_NL" => "Dutch", # "nl_NL" => "Dutch",
); );
global $arr_lang_translation; global $arr_lang_translation;

View File

@ -9,10 +9,10 @@ $L_VERSION_HELP = "3.0";
/* To ease the transition, we define a lookup table for old names */ /* To ease the transition, we define a lookup table for old names */
$compat = array('DEFAULT_MX' => 'MX', $compat = array('DEFAULT_MX' => 'MX',
'MYSQL_USER' => 'MYSQL_LOGIN', 'MYSQL_USER' => 'MYSQL_LOGIN',
'MYSQL_PASS' => 'MYSQL_PWD', 'MYSQL_PASS' => 'MYSQL_PWD',
'NS1_HOSTNAME' => 'NS1', 'NS1_HOSTNAME' => 'NS1',
'NS2_HOSTNAME' => 'NS2'); 'NS2_HOSTNAME' => 'NS2');
$config_file = fopen('/etc/alternc/local.sh', 'r'); $config_file = fopen('/etc/alternc/local.sh', 'r');
@ -31,18 +31,18 @@ $config_file = fopen('/etc/alternc/my.cnf', 'r');
while (false!== ($line = fgets($config_file))) { while (false!== ($line = fgets($config_file))) {
if (preg_match('/^([A-Za-z0-9_]*) *= *"?(.*?)"?$/', trim($line), $regs)) { if (preg_match('/^([A-Za-z0-9_]*) *= *"?(.*?)"?$/', trim($line), $regs)) {
switch ($regs[1]) { switch ($regs[1]) {
case "user": case "user":
$GLOBALS['L_MYSQL_LOGIN'] = $regs[2]; $GLOBALS['L_MYSQL_LOGIN'] = $regs[2];
break; break;
case "password": case "password":
$GLOBALS['L_MYSQL_PWD'] = $regs[2]; $GLOBALS['L_MYSQL_PWD'] = $regs[2];
break; break;
case "host": case "host":
$GLOBALS['L_MYSQL_HOST'] = $regs[2]; $GLOBALS['L_MYSQL_HOST'] = $regs[2];
break; break;
case "database": case "database":
$GLOBALS['L_MYSQL_DATABASE'] = $regs[2]; $GLOBALS['L_MYSQL_DATABASE'] = $regs[2];
break; break;
} }
} }
} }

View File

@ -18,7 +18,7 @@
Original Author of file: Lerider Steven Original Author of file: Lerider Steven
Purpose of file: Manage generic actions. Purpose of file: Manage generic actions.
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
/** /**
* This class manage actions to be performed on the file system on behalf of alternc Classes * This class manage actions to be performed on the file system on behalf of alternc Classes
@ -197,19 +197,19 @@ class m_action {
global $db, $msg; global $db, $msg;
$msg->log("action", "set", $type); $msg->log("action", "set", $type);
$serialized = serialize($parameters); $serialized = serialize($parameters);
$type = strtoupper($type); $type = strtoupper($type);
if (in_array($type, array('CHMOD', if (in_array($type, array('CHMOD',
'CREATE_FILE', 'CREATE_FILE',
'CREATE_DIR', 'CREATE_DIR',
'MOVE', 'MOVE',
'FIX_USER', 'FIX_USER',
'FIX_FILE', 'FIX_FILE',
'FIX_DIR', 'FIX_DIR',
'DELETE'))) { 'DELETE'))) {
$query = "INSERT INTO `actions` (type, parameters, creation, user) VALUES('$type', '$serialized', now(), '$user');"; $query = "INSERT INTO `actions` (type, parameters, creation, user) VALUES('$type', '$serialized', now(), '$user');";
} else { } else {
return False; return False;
} }
if (!$db->query($query)) { if (!$db->query($query)) {
$msg->raise("ERROR", "action", _("Error setting actions")); $msg->raise("ERROR", "action", _("Error setting actions"));

View File

@ -22,7 +22,7 @@
---------------------------------------------------------------------- ----------------------------------------------------------------------
Purpose of file: Administrate members and rights. Purpose of file: Administrate members and rights.
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
/* ----------------------------------------------------------------- */ /* ----------------------------------------------------------------- */
@ -692,27 +692,27 @@ class m_admin {
if ($db->next_record()) { if ($db->next_record()) {
// TODO: put that string into gettext ! // TODO: put that string into gettext !
$mail = <<<EOF $mail = <<<EOF
A new AlternC account was created on %fqdn by %creator. A new AlternC account was created on %fqdn by %creator.
Account details Account details
--------------- ---------------
login: %login (%uid) login: %login (%uid)
email: %mail email: %mail
createor: %creator (%cuid) createor: %creator (%cuid)
can change password: %canpass can change password: %canpass
type: %type type: %type
notes: %notes notes: %notes
EOF; EOF;
$mail = strtr($mail, array('%fqdn' => $L_FQDN, $mail = strtr($mail, array('%fqdn' => $L_FQDN,
'%creator' => $db->Record['parentlogin'], '%creator' => $db->Record['parentlogin'],
'%uid' => $db->Record['uid'], '%uid' => $db->Record['uid'],
'%login' => $db->Record['login'], '%login' => $db->Record['login'],
'%mail' => $db->Record['mail'], '%mail' => $db->Record['mail'],
'%cuid' => $db->Record['creator'], '%cuid' => $db->Record['creator'],
'%canpass' => $db->Record['canpass'], '%canpass' => $db->Record['canpass'],
'%type' => $db->Record['type'], '%type' => $db->Record['type'],
'%notes' => $db->Record['notes'])); '%notes' => $db->Record['notes']));
$subject = sprintf(_("New account %s from %s on %s"), $db->Record['login'], $db->Record['parentlogin'], $L_HOSTING); $subject = sprintf(_("New account %s from %s on %s"), $db->Record['login'], $db->Record['parentlogin'], $L_HOSTING);
if (mail($dest, $subject, $mail, "From: postmaster@$L_FQDN")) { if (mail($dest, $subject, $mail, "From: postmaster@$L_FQDN")) {
//sprintf(_("Email successfully sent to %s"), $dest); //sprintf(_("Email successfully sent to %s"), $dest);
@ -884,7 +884,7 @@ EOF;
$hooks->invoke("hook_admin_del_member"); $hooks->invoke("hook_admin_del_member");
if (($db->query("DELETE FROM membres WHERE uid= ?;", array($uid))) && if (($db->query("DELETE FROM membres WHERE uid= ?;", array($uid))) &&
($db->query("DELETE FROM local WHERE uid= ?;", array($uid)))) { ($db->query("DELETE FROM local WHERE uid= ?;", array($uid)))) {
$mem->unsu(); $mem->unsu();
// If this user was (one day) an administrator one, he may have a list of his own accounts. Let's associate those accounts to nobody as a creator. // If this user was (one day) an administrator one, he may have a list of his own accounts. Let's associate those accounts to nobody as a creator.
$db->query("UPDATE membres SET creator=2000 WHERE creator= ?;", array($uid)); $db->query("UPDATE membres SET creator=2000 WHERE creator= ?;", array($uid));
@ -940,7 +940,7 @@ EOF;
} }
} else { } else {
if ($db->query("UPDATE membres SET duration = ? WHERE uid= ?", array($duration, $uid)) && if ($db->query("UPDATE membres SET duration = ? WHERE uid= ?", array($duration, $uid)) &&
$db->query("UPDATE membres SET renewed = NOW() WHERE uid= ? and renewed is null;", array($uid))) { $db->query("UPDATE membres SET renewed = NOW() WHERE uid= ? and renewed is null;", array($uid))) {
return true; return true;
} }
} }
@ -995,12 +995,12 @@ EOF;
global $db; global $db;
if (!$db->query("SELECT *, m.renewed + INTERVAL duration MONTH 'expiry'," . if (!$db->query("SELECT *, m.renewed + INTERVAL duration MONTH 'expiry'," .
" CASE WHEN m.duration IS NULL THEN 0" . " CASE WHEN m.duration IS NULL THEN 0" .
" WHEN m.renewed + INTERVAL m.duration MONTH <= NOW() THEN 3" . " WHEN m.renewed + INTERVAL m.duration MONTH <= NOW() THEN 3" .
" WHEN m.renewed <= NOW() THEN 2" . " WHEN m.renewed <= NOW() THEN 2" .
" ELSE 1 END 'status' FROM membres m, local l" . " ELSE 1 END 'status' FROM membres m, local l" .
" WHERE m.uid = l.uid" . " WHERE m.uid = l.uid" .
" HAVING status=2 or status=3 ORDER BY status DESC, expiry;")) { " HAVING status=2 or status=3 ORDER BY status DESC, expiry;")) {
return false; return false;
} else { } else {
$res = array(); $res = array();
@ -1171,7 +1171,7 @@ EOF;
if (!in_array($L_NS1 . ".", $out) || !in_array($L_NS2 . ".", $out)) { if (!in_array($L_NS1 . ".", $out) || !in_array($L_NS2 . ".", $out)) {
$errno = 1; $errno = 1;
$errstr.=sprintf(_("NS for this domain are not %s and %s BUT %s"), $errstr.=sprintf(_("NS for this domain are not %s and %s BUT %s"),
$L_NS1, $L_NS2, implode(",", $out)) . "\n"; $L_NS1, $L_NS2, implode(",", $out)) . "\n";
} }
} }
} }

View File

@ -1,25 +1,25 @@
<?php <?php
/** /**
$Id: m_authip.php $Id: m_authip.php
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
This program is free software; you can redistribute it and/or This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL) modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2 as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version. of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Original Author of file: Fufroma Original Author of file: Fufroma
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
/** /**
* Classe de gestion des IP authorisée * Classe de gestion des IP authorisée
@ -80,7 +80,7 @@ class m_authip {
while ($db->next_record()) { while ($db->next_record()) {
$r[$db->f('id')] = $db->Record; $r[$db->f('id')] = $db->Record;
if ((checkip($db->f('ip')) && $db->f('subnet') == 32) || if ((checkip($db->f('ip')) && $db->f('subnet') == 32) ||
(checkipv6($db->f('ip')) && $db->f('subnet') == 128)) { (checkipv6($db->f('ip')) && $db->f('subnet') == 128)) {
$r[$db->f('id')]['ip_human'] = $db->f('ip'); $r[$db->f('id')]['ip_human'] = $db->f('ip');
} else { } 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');
@ -216,7 +216,7 @@ class m_authip {
} }
$id = intval($id); $id = intval($id);
$infos = $db->quote(trim($infos)); $infos = $db->quote(trim($infos));
// Extract subnet from ipsub // Extract subnet from ipsub
$tmp = explode('/', $ipsub); $tmp = explode('/', $ipsub);

View File

@ -22,7 +22,7 @@
---------------------------------------------------------------------- ----------------------------------------------------------------------
Purpose of file: file browser class. Purpose of file: file browser class.
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
/* Add the mime type list */ /* Add the mime type list */
@include("mime.php"); @include("mime.php");
@ -213,8 +213,8 @@ class m_bro {
if ($file != "." && $file != "..") { if ($file != "." && $file != "..") {
$stat=stat($absolute . "/" . $file); $stat=stat($absolute . "/" . $file);
$c[] = array("name" => $file, "size" => $this->fsize($absolute . "/" . $file, $showdirsize), $c[] = array("name" => $file, "size" => $this->fsize($absolute . "/" . $file, $showdirsize),
"date" => filemtime($absolute . "/" . $file), "type" => (!is_dir($absolute . "/" . $file)), "date" => filemtime($absolute . "/" . $file), "type" => (!is_dir($absolute . "/" . $file)),
"permissions" => $stat[2] ); "permissions" => $stat[2] );
} }
} }
closedir($dir); closedir($dir);
@ -245,22 +245,22 @@ class m_bro {
} }
/** /**
Modifie les prfrences de l'utilisateur courant. Modifie les prfrences de l'utilisateur courant.
* *
* @global m_mysql $db * @global m_mysql $db
* @global int $cuid * @global int $cuid
* @param integer $editsizex Taille de l'diteur (nombre de colonnes) * @param integer $editsizex Taille de l'diteur (nombre de colonnes)
* @param integer $editsizey Taille de l'diteur (nombre de lignes) * @param integer $editsizey Taille de l'diteur (nombre de lignes)
* @param integer $listmode Mode d'affichage de la liste des fichiers * @param integer $listmode Mode d'affichage de la liste des fichiers
* @param integer $showicons Faut-il afficher / cacher les icones des fichiers * @param integer $showicons Faut-il afficher / cacher les icones des fichiers
* @param integer $downfmt Dans quel format faut-il tlcharger les dossiers compresss * @param integer $downfmt Dans quel format faut-il tlcharger les dossiers compresss
* @param integer $createfile Faut-il editer/revenir au browser aprs cration d'un fichier * @param integer $createfile Faut-il editer/revenir au browser aprs cration d'un fichier
* @param integer $showtype Faut-il afficher le type mime des fichiers * @param integer $showtype Faut-il afficher le type mime des fichiers
* @param integer $editor_font Quelle police faut-il utiliser pour l'diteur * @param integer $editor_font Quelle police faut-il utiliser pour l'diteur
* @param integer $editor_size Quelle taille de police faut-il utiliser pour l'diteur * @param integer $editor_size Quelle taille de police faut-il utiliser pour l'diteur
* @param integer $golastdir Faut-il revenir la racine ou au dernier dossier visit ? * @param integer $golastdir Faut-il revenir la racine ou au dernier dossier visit ?
* @return boolean * @return boolean
*/ */
function SetPrefs($editsizex, $editsizey, $listmode, $showicons, $downfmt, $createfile, $showtype, $editor_font, $editor_size, $golastdir) { function SetPrefs($editsizex, $editsizey, $listmode, $showicons, $downfmt, $createfile, $showtype, $editor_font, $editor_size, $golastdir) {
global $db, $cuid; global $db, $cuid;
$editsizex = intval($editsizex); $editsizex = intval($editsizex);
@ -612,18 +612,18 @@ class m_bro {
// there was an error, raise it // there was an error, raise it
$msg->log("bro", "uploadfile", "Problem when uploading a file"); $msg->log("bro", "uploadfile", "Problem when uploading a file");
switch ($_FILES['userfile']['error']) { switch ($_FILES['userfile']['error']) {
case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_INI_SIZE:
$erstr = _("The uploaded file exceeds the max file size allowed"); $erstr = _("The uploaded file exceeds the max file size allowed");
break; break;
case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_FORM_SIZE:
case UPLOAD_ERR_PARTIAL: case UPLOAD_ERR_PARTIAL:
case UPLOAD_ERR_NO_FILE: case UPLOAD_ERR_NO_FILE:
case UPLOAD_ERR_NO_TMP_DIR: case UPLOAD_ERR_NO_TMP_DIR:
case UPLOAD_ERR_CANT_WRITE: case UPLOAD_ERR_CANT_WRITE:
case UPLOAD_ERR_EXTENSION: case UPLOAD_ERR_EXTENSION:
default: default:
$erstr = _("Undefined error ") . $_FILES['userfile']['error']; $erstr = _("Undefined error ") . $_FILES['userfile']['error'];
break; break;
} }
$msg->raise("ERROR", "bro", _("Error during the upload of the file: ") . $erstr); $msg->raise("ERROR", "bro", _("Error during the upload of the file: ") . $erstr);
return false; return false;
@ -686,7 +686,7 @@ class m_bro {
if ($ret) { if ($ret) {
$msg->raise("ERROR", "bro", _("I cannot find a way to extract the file %s, it is an unsupported compressed format"), $file); $msg->raise("ERROR", "bro", _("I cannot find a way to extract the file %s, it is an unsupported compressed format"), $file);
return false; return false;
} }
return true; return true;
} }
@ -904,21 +904,21 @@ class m_bro {
if (($parts = explode(".", $name))) { if (($parts = explode(".", $name))) {
$ext = array_pop($parts); $ext = array_pop($parts);
switch ($ext) { switch ($ext) {
case "gz": case "gz":
case "bz": case "bz":
case "bz2": case "bz2":
$ext = array_pop($parts) . $ext; $ext = array_pop($parts) . $ext;
/* FALLTHROUGH */ /* FALLTHROUGH */
case "tar.gz": case "tar.gz":
case "tar.bz": case "tar.bz":
case "tar.bz2": case "tar.bz2":
case "tgz": case "tgz":
case "tbz": case "tbz":
case "tbz2": case "tbz2":
case "tar": case "tar":
case "Z": case "Z":
case "zip": case "zip":
return true; return true;
} }
} }
return false; return false;
@ -1006,7 +1006,7 @@ class m_bro {
$msg->raise("ERROR", "bro", _("File or folder name is incorrect")); $msg->raise("ERROR", "bro", _("File or folder name is incorrect"));
return false; return false;
} }
return true; return true;
} }
/** /**
@ -1074,7 +1074,7 @@ class m_bro {
header("Content-Transfer-Encoding: binary"); header("Content-Transfer-Encoding: binary");
$d = $this->convertabsolute($dir, false); $d = $this->convertabsolute($dir, false);
set_time_limit(0); set_time_limit(0);
chdir(dirname($d)); chdir(dirname($d));
passthru("/usr/bin/zip -r - ".escapeshellarg(basename($d))); passthru("/usr/bin/zip -r - ".escapeshellarg(basename($d)));
} }

View File

@ -22,7 +22,7 @@
---------------------------------------------------------------------- ----------------------------------------------------------------------
Purpose of file: Manage hook system. Purpose of file: Manage hook system.
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
/** /**
* This class manage web-cron tasks * This class manage web-cron tasks
@ -78,7 +78,7 @@ class m_cron {
'ico' => 'images/schedule.png', 'ico' => 'images/schedule.png',
'link' => 'cron.php', 'link' => 'cron.php',
'pos' => 120, 'pos' => 120,
); );
return $obj; return $obj;
} }
@ -163,8 +163,8 @@ class m_cron {
if (!$db->next_record()) { if (!$db->next_record()) {
return "false"; return "false";
} // return false if pb } // return false if pb
if ($db->f('uid') != $cuid) { if ($db->f('uid') != $cuid) {
$msg->raise("ERROR", "cron", _("Identity problem")); $msg->raise("ERROR", "cron", _("Identity problem"));
return false; return false;
} }
} }
@ -304,11 +304,11 @@ class m_cron {
// add additional curl options here // add additional curl options here
$std_options = array(CURLOPT_RETURNTRANSFER => true, $std_options = array(CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false, CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 240, // 4 minutes timeout for a page CURLOPT_TIMEOUT => 240, // 4 minutes timeout for a page
CURLOPT_USERAGENT => "AlternC (Cron Daemon)", CURLOPT_USERAGENT => "AlternC (Cron Daemon)",
CURLOPT_MAXREDIRS => 0); CURLOPT_MAXREDIRS => 0);
if ($GLOBALS["DEBUG"]) { if ($GLOBALS["DEBUG"]) {
$std_options[CURLOPT_VERBOSE] = true; $std_options[CURLOPT_VERBOSE] = true;

View File

@ -4,27 +4,27 @@ class m_crypto {
function encrypt($sValue, $sSecretKey) { function encrypt($sValue, $sSecretKey) {
return rtrim( return rtrim(
base64_encode( base64_encode(
mcrypt_encrypt( 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_get_iv_size(
MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB
), MCRYPT_RAND ), MCRYPT_RAND
) )
) )
), "\0" ), "\0"
); );
} }
function decrypt($sValue, $sSecretKey) { function decrypt($sValue, $sSecretKey) {
return rtrim( return rtrim(
mcrypt_decrypt( 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_get_iv_size(
MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB
), MCRYPT_RAND ), MCRYPT_RAND
) )
), "\0" ), "\0"
); );
} }

View File

@ -1,6 +1,7 @@
<?php <?php
/* /*
----------------------------------------------------------------------
LICENSE LICENSE
This program is free software; you can redistribute it and/or This program is free software; you can redistribute it and/or
@ -15,10 +16,7 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Original Author of file: Camille Lafitte */
Purpose of file: Manage hook system.
----------------------------------------------------------------------
*/
/** /**
* This class manage debug. * This class manage debug.

File diff suppressed because it is too large Load Diff

View File

@ -1,155 +1,154 @@
<?php <?php
/* /*
$Id: m_err.php,v 1.4 2004/05/19 14:23:06 benjamin Exp $ ----------------------------------------------------------------------
---------------------------------------------------------------------- LICENSE
LICENSE
This program is free software; you can redistribute it and/or This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL) modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2 as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version. of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Original Author of file: Benjamin Sonntag, Franck Missoum
----------------------------------------------------------------------
*/ */
/** /**
* Classe de gestion des erreurs apparaissant lors d'appels API. * Classe de gestion des erreurs apparaissant lors d'appels API.
* *
* <p>Cette classe gère les erreurs qui peuvent apparaitre lors d'appels * <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 * à 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é. * (Classe ID et Numéro d'erreur) ainsi qu'un texte facultatif associé.
* Des textes d'erreurs localisés sont aussi disponibles.</p> * 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 * <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 * dans les logs du système dans /var/log/alternc/bureau.log
* </p> * </p>
* Copyleft {@link http://alternc.net/ AlternC Team} * Copyleft {@link http://alternc.net/ AlternC Team}
* *
* @copyright AlternC-Team 2002-11-01 http://alternc.net/ * @copyright AlternC-Team 2002-11-01 http://alternc.net/
*/ */
class m_err { class m_err {
/** Numero de classe d'erreur actuelle */ /** Numero de classe d'erreur actuelle */
var $clsid=0; var $clsid=0;
/** Dernière erreur enregistrée par la classe */ /** Dernière erreur enregistrée par la classe */
var $error=0; var $error=0;
/** Paramètre chaine eventuellement associé à la dernière erreur */ /** Paramètre chaine eventuellement associé à la dernière erreur */
var $param=""; var $param="";
/** Emplacement du fichier de logs d'AlternC */ /** 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 * Leve une erreur, signale celle-ci dans les logs et stocke le code erreur
* *
* Cette fonction lance une erreur, l'ajoute dans les logs d'AlternC, * Cette fonction lance une erreur, l'ajoute dans les logs d'AlternC,
* et la met à disposition pour le bureau virtuel pour affichage ultérieur. * et la met à disposition pour le bureau virtuel pour affichage ultérieur.
* *
* @todo ne plus utiliser $error de façon numérique, nulle part * @todo ne plus utiliser $error de façon numérique, nulle part
* *
* @param integer $clsid Classe qui lève l'erreur * @param integer $clsid Classe qui lève l'erreur
* @param mixed $error Numéro de l'erreur ou chaîne décrivant l'erreur * @param mixed $error Numéro de l'erreur ou chaîne décrivant l'erreur
* @param string $param Paramètre chaine associé à l'erreur (facultatif) * @param string $param Paramètre chaine associé à l'erreur (facultatif)
* @return boolean TRUE si l'erreur est connue, FALSE sinon. * @return boolean TRUE si l'erreur est connue, FALSE sinon.
* *
*/ */
function raise($clsid,$error,$param="") { function raise($clsid,$error,$param="") {
// This is the old method, deprecation warning // This is the old method, deprecation warning
$this->deprecated(); $this->deprecated();
/* Leve une exception. Si elle existe, sinon, stocke un message d'erreur sur erreur ...*/ /* Leve une exception. Si elle existe, sinon, stocke un message d'erreur sur erreur ...*/
if (_("err_".$clsid."_".$error)!="err_".$clsid."_".$error || is_string($error)) { if (_("err_".$clsid."_".$error)!="err_".$clsid."_".$error || is_string($error)) {
$this->clsid=$clsid; $this->clsid=$clsid;
$this->error=$error; $this->error=$error;
$args = func_get_args(); $args = func_get_args();
$this->param=array_slice($args, 2); $this->param=array_slice($args, 2);
$this->logerr(); $this->logerr();
return true; return true;
} else { } else {
$this->clsid="err"; $this->clsid="err";
$this->error=1; $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->param="Error # $error in Class $clsid, Value is $param. (sorry, no text for this error in your language at the moment)";
$this->logerr(); $this->logerr();
return false; return false;
}
} }
}
/** /**
* Retourne la chaine d'erreur correspondant à la dernière erreur rencontrée * Retourne la chaine d'erreur correspondant à la dernière erreur rencontrée
* *
* Si la dernière erreur rencontrée est connue, retourne l'erreur en toute lettre * Si la dernière erreur rencontrée est connue, retourne l'erreur en toute lettre
* dans la langue actuellement sélectionnée, ou en anglais par défaut. * dans la langue actuellement sélectionnée, ou en anglais par défaut.
* Si l'erreur n'est pas connue, retourne son numéro de classe et d'ereur. * Si l'erreur n'est pas connue, retourne son numéro de classe et d'ereur.
* *
* @return string Chaine d'erreur. * @return string Chaine d'erreur.
* *
*/ */
function errstr() { function errstr() {
if (is_string($this->error)) { if (is_string($this->error)) {
// new way of handling errors: message directly in the class // new way of handling errors: message directly in the class
$str = $this->error."\n"; $str = $this->error."\n";
} else { } else {
// old way: message in the locales files (ugly) // 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)) {
array_unshift($args, $str);
$msg = call_user_func_array("sprintf", $args);
return $msg;
} else {
return $args;
}
} }
$args = $this->param;
if (is_array($args)) { /**
array_unshift($args, $str); * Envoi un log d'erreur dans /var/log/alternc/bureau.log
$msg = call_user_func_array("sprintf", $args); *
return $msg; * Cette fonction Loggue la dernière erreur dans /var/log sur la machine,
} else { * permettant ainsi aux admins de savoir ce qu'il se passe...
return $args; * Elle est appelée automatiquement par error
* @access private
*/
function logerr() {
global $mem;
@file_put_contents($this->logfile, date("d/m/Y H:i:s")." - ERROR - ".$mem->user["login"]." - ".$this->errstr(), FILE_APPEND );
} }
}
/** /**
* Envoi un log d'erreur dans /var/log/alternc/bureau.log * Envoi un log d'appel d'API dans /var/log/alternc/bureau.log
* *
* Cette fonction Loggue la dernière erreur dans /var/log sur la machine, * Cette fonction loggue dans /var/log l'appel à la fonction de l'API
* permettant ainsi aux admins de savoir ce qu'il se passe... * d'AlternC.
* Elle est appelée automatiquement par error *
* @access private * @param integer $clsid Numéro de la classe dont on a appelé une fonction
*/ * @param string $function Nom de la fonction appelée
function logerr() { * @param string $param Paramètre (facultatif) passés à la fonction de l'API.
global $mem; * @return boolean TRUE si le log a été ajouté, FALSE sinon
@file_put_contents($this->logfile, date("d/m/Y H:i:s")." - ERROR - ".$mem->user["login"]." - ".$this->errstr(), FILE_APPEND ); *
} */
function log($clsid,$function,$param="") {
global $mem,$cuid;
// This is the old method, deprecation warning
$this->deprecated();
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 );
}
/**
* This method is present in order to allow slow deprecation
*/
function deprecated(){
global $msg;
$trace = debug_backtrace();
$caller = $trace[2];
$msg->raise( "error","err","Deprecation warning: The old messaging class is still used by ".json_encode( $caller ));
}
} /* Classe m_err */
/**
* Envoi un log d'appel d'API dans /var/log/alternc/bureau.log
*
* Cette fonction loggue dans /var/log l'appel à la fonction de l'API
* d'AlternC.
*
* @param integer $clsid Numéro de la classe dont on a appelé une fonction
* @param string $function Nom de la fonction appelée
* @param string $param Paramètre (facultatif) passés à la fonction de l'API.
* @return boolean TRUE si le log a été ajouté, FALSE sinon
*
*/
function log($clsid,$function,$param="") {
global $mem,$cuid;
// This is the old method, deprecation warning
$this->deprecated();
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 );
}
/**
* This method is present in order to allow slow deprecation
*/
function deprecated(){
global $msg;
$trace = debug_backtrace();
$caller = $trace[2];
$msg->raise( "error","err","Deprecation warning: The old messaging class is still used by ".json_encode( $caller ));
}
}; /* Classe m_err */
?>

View File

@ -3,10 +3,10 @@
/* --------------------------------------------------------------------------- */ /* --------------------------------------------------------------------------- */
/** Constructor /** Constructor
Classe d'export de compte Alternc. 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, 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. presentes dans les classes concernées.
*/ */
Class m_export { Class m_export {
function m_export() { function m_export() {
@ -20,8 +20,8 @@ Class m_export {
} }
/** le repertoire de base est passé en paramettre puis en construit une arborescence de la forme /** 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 <dir>/<user>/<timestamp/ qui contiendra les dossier de dump html et sql
*/ */
function export_data($dir) { function export_data($dir) {
global $hooks, $mem; global $hooks, $mem;

View File

@ -1,10 +1,6 @@
<?php <?php
/* /*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
@ -20,9 +16,7 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Purpose of file: Manage FTP accounts */
----------------------------------------------------------------------
*/
/** /**
* FTP account management class * FTP account management class
@ -31,17 +25,15 @@ class m_ftp {
var $srv_name; var $srv_name;
/* ----------------------------------------------------------------- */
/** /**
* Constructeur * Constructor
*/ */
function m_ftp() { function m_ftp() {
global $L_FQDN; 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) * Password kind used in this class (hook for admin class)
@ -50,6 +42,11 @@ class m_ftp {
return array("ftp" => "FTP accounts"); return array("ftp" => "FTP accounts");
} }
/**
* hook function called by menu class
* to add menu to the left panel
*/
function hook_menu() { function hook_menu() {
global $quota; global $quota;
$q = $quota->getquota("ftp"); $q = $quota->getquota("ftp");
@ -81,8 +78,11 @@ class m_ftp {
return $obj; return $obj;
} }
// Return the values needed to activate security access. See get_auth_class()
// in authip for more informations /**
* Return the values needed to activate security access. See get_auth_class()
* in authip for more informations
*/
function authip_class() { function authip_class() {
$c = Array(); $c = Array();
$c['name'] = "FTP"; $c['name'] = "FTP";
@ -100,7 +100,10 @@ class m_ftp {
return $c; return $c;
} }
// Switch enabled status of an account
/**
* Switch enabled status of an account
*/
function switch_enabled($id, $status = null) { function switch_enabled($id, $status = null) {
global $cuid, $db, $msg; global $cuid, $db, $msg;
if (!$jj = $this->get_ftp_details($id)) { if (!$jj = $this->get_ftp_details($id)) {
@ -114,7 +117,6 @@ class m_ftp {
$status = 1; $status = 1;
} }
} }
// Be sure what is in $status, in case of it was a parameter // Be sure what is in $status, in case of it was a parameter
$status = ($status ? 1 : 0); $status = ($status ? 1 : 0);
@ -126,9 +128,9 @@ class m_ftp {
} }
} }
/* ----------------------------------------------------------------- */
/** Retourne la liste des comptes FTP du compte h<EFBFBD>berg<EFBFBD> /**
* 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 * Retourne la liste des comptes FTP sous forme de tableau index<EFBFBD> de
* tableaus associatifs comme suit : * tableaus associatifs comme suit :
* $a["id"]= ID du compte ftp * $a["id"]= ID du compte ftp
@ -158,9 +160,9 @@ class m_ftp {
} }
} }
/* ----------------------------------------------------------------- */
/** Retourne les details d'un compte FTP (voir get_list) /**
* Retourne les details d'un compte FTP (voir get_list)
* Le tableau est celui du compte d'id specifie * Le tableau est celui du compte d'id specifie
* @param integer $id Numero du compte dont on souhaite obtenir les d<EFBFBD>tails * @param integer $id Numero du compte dont on souhaite obtenir les d<EFBFBD>tails
* @return array Tableau associatif contenant les infos du comptes ftp * @return array Tableau associatif contenant les infos du comptes ftp
@ -196,9 +198,9 @@ class m_ftp {
} }
} }
/* ----------------------------------------------------------------- */
/** Retourne la liste des prefixes utilisables par le compte courant /**
* Retourne la liste des prefixes utilisables par le compte courant
* @return array tableau contenant la liste des prefixes (domaines + login) * @return array tableau contenant la liste des prefixes (domaines + login)
* du compte actuel. * du compte actuel.
*/ */
@ -213,14 +215,13 @@ class m_ftp {
return $r; return $r;
} }
/** /**
* Check if the login is fine (syntax) * Check if the login is fine (syntax)
*
* @param string $l * @param string $l
*/ */
function check_login($l) { function check_login($l) {
global $msg; global $msg;
// special chars and the max numbers of them allowed // special chars and the max numbers of them allowed
// to be able to give a specific error // to be able to give a specific error
$vv = array('_' => '1', ' ' => 0); $vv = array('_' => '1', ' ' => 0);
@ -230,7 +231,6 @@ class m_ftp {
return false; return false;
} }
} }
// Explicitly look for only allowed chars // 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)) {
$msg->raise("ERROR", 'ftp', _("FTP login is incorrect")); $msg->raise("ERROR", 'ftp', _("FTP login is incorrect"));
@ -239,9 +239,9 @@ class m_ftp {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Affiche (ECHO) la liste des prefixes disponibles sous forme de champs d'option /**
* Affiche (ECHO) la liste des prefixes disponibles sous forme de champs d'option
* Les champs sont affich<EFBFBD>s sous la forme <option>prefixe</option>... * Les champs sont affich<EFBFBD>s sous la forme <option>prefixe</option>...
* La valeur $current se voit affubl<EFBFBD>e de la balise SELECTED. * La valeur $current se voit affubl<EFBFBD>e de la balise SELECTED.
* @param string $current Prefixe s<EFBFBD>lectionn<EFBFBD> par d<EFBFBD>faut * @param string $current Prefixe s<EFBFBD>lectionn<EFBFBD> par d<EFBFBD>faut
@ -261,9 +261,9 @@ class m_ftp {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Modifie les param<EFBFBD>tres du comptes FTP $id. /**
* 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 integer $id Num<EFBFBD>ro du compte dont on veut modifier les param<EFBFBD>tres
* @param string $prefixe Prefixe du compte FTP * @param string $prefixe Prefixe du compte FTP
* @param string $login login ajout<EFBFBD> au pr<EFBFBD>fixe ($prefixe_$login) * @param string $login login ajout<EFBFBD> au pr<EFBFBD>fixe ($prefixe_$login)
@ -327,9 +327,9 @@ class m_ftp {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Efface le compte ftp specifie /**
* Efface le compte ftp specifie
* @param integer $id Numero du compte FTP a supprimer. * @param integer $id Numero du compte FTP a supprimer.
* @return boolean TRUE si le compte a ete efface, FALSE sinon. * @return boolean TRUE si le compte a ete efface, FALSE sinon.
*/ */
@ -347,15 +347,14 @@ class m_ftp {
return $name; return $name;
} }
/* ----------------------------------------------------------------- */
/** Cree un nouveau compte FTP. /**
* Cree un nouveau compte FTP.
* @param string $prefixe Prefixe au login * @param string $prefixe Prefixe au login
* @param string $login Login ftp (login=prefixe_login) * @param string $login Login ftp (login=prefixe_login)
* @param string $pass Mot de passe FTP * @param string $pass Mot de passe FTP
* @param string $dir Repertoire racine du compte relatif à la racine du membre * @param string $dir Repertoire racine du compte relatif à la racine du membre
* @return boolean TRUE si le compte a ete cree, FALSE sinon. * @return boolean TRUE si le compte a ete cree, FALSE sinon.
*
*/ */
function add_ftp($prefixe, $login, $pass, $dir) { function add_ftp($prefixe, $login, $pass, $dir) {
global $db, $msg, $quota, $bro, $cuid, $admin; global $db, $msg, $quota, $bro, $cuid, $admin;
@ -414,9 +413,9 @@ class m_ftp {
} }
} }
/* ----------------------------------------------------------------- */
/** Retourne TRUE si $dir possee un compte FTP /**
* Retourne TRUE si $dir possee un compte FTP
* @param string $dir Dossier a tester, relatif a la racine du compte courant * @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. * @return boolean retourne TRUE si $dir a un compte FTP, FALSE sinon.
*/ */
@ -435,9 +434,9 @@ class m_ftp {
} }
} }
/* ----------------------------------------------------------------- */
/** Fonction appellee par domains quand un domaine est supprime pour le membre /**
* Fonction appellee par domains quand un domaine est supprime pour le membre
* @param string $dom Domaine à detruire. * @param string $dom Domaine à detruire.
* @access private * @access private
*/ */
@ -448,9 +447,9 @@ class m_ftp {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Fonction appellee par membres quand un membre est efface /**
* Fonction appellee par membres quand un membre est efface
* @access private * @access private
*/ */
function alternc_del_member() { function alternc_del_member() {
@ -460,7 +459,6 @@ class m_ftp {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** /**
* Returns the used quota for the $name service for the current user. * Returns the used quota for the $name service for the current user.
@ -479,7 +477,6 @@ class m_ftp {
return $q; return $q;
} }
/* ----------------------------------------------------------------- */
/** /**
* Exporte toutes les informations ftp du compte AlternC * Exporte toutes les informations ftp du compte AlternC
@ -500,9 +497,9 @@ class m_ftp {
return $str; return $str;
} }
/* ----------------------------------------------------------------- */
/** hook function called by AlternC-upnp to know which open /**
* hook function called by AlternC-upnp to know which open
* tcp or udp ports this class requires or suggests * tcp or udp ports this class requires or suggests
* @return array a key => value list of port protocol name mandatory values * @return array a key => value list of port protocol name mandatory values
* @access private * @access private
@ -513,6 +510,5 @@ class m_ftp {
); );
} }
} } /* Class m_ftp */
/* Class m_ftp */

View File

@ -1,10 +1,6 @@
<?php <?php
/* /*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
@ -20,26 +16,14 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Purpose of file: Manage hook system. */
----------------------------------------------------------------------
*/
/** /**
* This class manage hooks. * This class manage hooks.
* *
* @copyright AlternC-Team 2002-2005 http://alternc.org/
*/ */
class m_hooks { 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 * invoke() permet de lancer une fonction donné en parametre dans toute les classes
@ -79,7 +63,6 @@ class m_hooks {
return $val; return $val;
} }
/* --------------------------------------------------------------------------- */
/** /**
* invoke each executable script of the directory (or the specified script) * invoke each executable script of the directory (or the specified script)
@ -119,7 +102,5 @@ class m_hooks {
return true; return true;
} }
} } /* Class hooks */
/* Class hooks */

View File

@ -1,14 +1,6 @@
<?php <?php
/* /*
$Id: m_hta.php,v 1.5 2004/11/29 17:15:37 anonymous Exp $
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2002 by the AlternC Development Team.
http://alternc.org/
----------------------------------------------------------------------
Based on:
Valentin Lacambre's web hosting softwares: http://altern.org/
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
@ -24,40 +16,28 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Original Author of file: */
Purpose of file:
----------------------------------------------------------------------
*/
/** /**
* This class handle folder web restricted access through .htaccess/.htpassword * This class handle folder web restricted access through .htaccess/.htpassword
* files. * files.
* *
* Copyleft {@link http://alternc.net/ AlternC Team}
*
* @copyright AlternC-Team 2002-11-01 http://alternc.org/
*
*/ */
class m_hta { class m_hta {
/**
* Constructor
*/
function m_webaccess() {
}
/** /**
* Password kind used in this class (hook for admin class) * Password kind used in this class (hook for admin class)
*
* @return array * @return array
*/ */
function alternc_password_policy() { function alternc_password_policy() {
return array("hta" => "Protected folders passwords"); return array("hta" => "Protected folders passwords");
} }
/** /**
* * hook called by menu class to add a menu
* to the left panel
* @return array * @return array
*/ */
function hook_menu() { function hook_menu() {
@ -71,6 +51,7 @@ class m_hta {
return $obj; return $obj;
} }
/** /**
* Create a protected folder (.htaccess et .htpasswd) * Create a protected folder (.htaccess et .htpasswd)
* @param string $dir Folder to protect (relative to user root) * @param string $dir Folder to protect (relative to user root)
@ -115,6 +96,7 @@ class m_hta {
return true; return true;
} }
/** /**
* Returns the list of all user folder currently protected by a .htpasswd file * Returns the list of all user folder currently protected by a .htpasswd file
* *
@ -144,6 +126,7 @@ class m_hta {
return $r; return $r;
} }
/** /**
* Tells if a folder is protected. * Tells if a folder is protected.
* *
@ -163,6 +146,7 @@ class m_hta {
} }
} }
/** /**
* Returns the list of login for a protected folder. * Returns the list of login for a protected folder.
* *
@ -177,9 +161,9 @@ class m_hta {
$absolute = ALTERNC_HTML . "/" . substr($mem->user["login"], 0, 1) . "/" . $mem->user["login"] . "/$dir"; $absolute = ALTERNC_HTML . "/" . substr($mem->user["login"], 0, 1) . "/" . $mem->user["login"] . "/$dir";
if (file_exists("$absolute/.htaccess")) { if (file_exists("$absolute/.htaccess")) {
/* if (!_reading_htaccess($absolute)) { /* if (!_reading_htaccess($absolute)) {
return false; return false;
} }
*/ */
} }
$file = @fopen("$absolute/.htpasswd", "r"); $file = @fopen("$absolute/.htpasswd", "r");
$i = 0; $i = 0;
@ -187,7 +171,7 @@ class m_hta {
if (!$file) { if (!$file) {
return false; return false;
} }
// TODO: Tester la validité du .htpasswd // TODO: Test the validity of a .htpasswd
while (!feof($file)) { while (!feof($file)) {
$s = fgets($file, 1024); $s = fgets($file, 1024);
$t = explode(":", $s); $t = explode(":", $s);
@ -200,6 +184,7 @@ class m_hta {
return $res; return $res;
} }
/** /**
* Unprotect a folder * Unprotect a folder
* *
@ -261,6 +246,7 @@ class m_hta {
return true; return true;
} }
/** /**
* Add a user to a protected folder * Add a user to a protected folder
* *
@ -326,6 +312,7 @@ class m_hta {
} }
} }
/** /**
* Delete a user from a protected folder. * Delete a user from a protected folder.
* *
@ -367,6 +354,7 @@ class m_hta {
return true; return true;
} }
/** /**
* Change the password of a user in a protected folder * Change the password of a user in a protected folder
* @param string $user The users whose password should be changed * @param string $user The users whose password should be changed
@ -412,6 +400,7 @@ class m_hta {
return true; return true;
} }
/** /**
* Check that a .htaccess file is valid (for authentication) * Check that a .htaccess file is valid (for authentication)
* *
@ -455,6 +444,5 @@ class m_hta {
return true; return true;
} }
} } /* class m_hta */
/* CLASS m_hta */

View File

@ -1,10 +1,6 @@
<?php <?php
/* /*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
@ -20,19 +16,16 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Purpose of file: Manage Log files for users */
----------------------------------------------------------------------
*/
/** /**
* Classe de gestion des erreurs apparaissant lors d'appels API. * This class shows error or access logs of web server to the web panel
*/ */
class m_log { class m_log {
function m_log() { /**
* List all logs files in a directory
} */
function list_logs_directory($dir) { function list_logs_directory($dir) {
global $cuid, $msg; global $cuid, $msg;
$msg->log("log", "list_logs_directory"); $msg->log("log", "list_logs_directory");
@ -40,37 +33,51 @@ class m_log {
$c = array(); $c = array();
foreach (glob("${dir}/*log*") as $absfile) { foreach (glob("${dir}/*log*") as $absfile) {
$c[] = array("name" => basename($absfile), $c[] = array("name" => basename($absfile),
"creation_date" => date("F d Y H:i:s", filectime($absfile)), "creation_date" => date("F d Y H:i:s", filectime($absfile)),
"mtime" => filemtime($absfile), "mtime" => filemtime($absfile),
"filesize" => filesize($absfile), "filesize" => filesize($absfile),
"downlink" => urlencode(basename($absfile)), "downlink" => urlencode(basename($absfile)),
); );
} }
usort($c, "m_log::compare_logtime"); usort($c, "m_log::compare_logtime");
return $c; return $c;
} }
// Used by list_logs_directory to sort
/**
* Used by list_logs_directory to sort
*/
private function compare_logname($a, $b) { 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
/**
* Used by list_logs_directory to sort
*/
private function compare_logtime($a, $b) { private function compare_logtime($a, $b) {
return $b['mtime'] - $a['mtime']; return $b['mtime'] - $a['mtime'];
} }
/**
* hook called by the menu class
* to add menu to the left panel
*/
function hook_menu() { function hook_menu() {
$obj = array( $obj = array(
'title' => _("Logs"), 'title' => _("Logs"),
'ico' => 'images/logs.png', 'ico' => 'images/logs.png',
'link' => 'logs_list.php', 'link' => 'logs_list.php',
'pos' => 130, 'pos' => 130,
); );
return $obj; return $obj;
} }
/**
* list all log files in all log directories
*/
function list_logs_directory_all($dirs) { function list_logs_directory_all($dirs) {
global $msg; global $msg;
$msg->log("log", "get_logs_directory_all"); $msg->log("log", "get_logs_directory_all");
@ -81,6 +88,7 @@ class m_log {
return $c; return $c;
} }
function get_logs_directory() { function get_logs_directory() {
global $cuid, $mem, $msg; global $cuid, $mem, $msg;
$msg->log("log", "get_logs_directory"); $msg->log("log", "get_logs_directory");
@ -93,6 +101,10 @@ class m_log {
return $c; return $c;
} }
/**
* download a log file
*/
function download_link($file) { function download_link($file) {
global $msg; global $msg;
$msg->log("log", "download_link"); $msg->log("log", "download_link");
@ -105,6 +117,9 @@ class m_log {
readfile($ff); readfile($ff);
} }
/**
* show the last lines of a file
*/
function tail($file, $lines = 20) { function tail($file, $lines = 20) {
global $msg; global $msg;
$msg->log("log", "tail"); $msg->log("log", "tail");
@ -119,6 +134,4 @@ class m_log {
return implode("\n", $out); return implode("\n", $out);
} }
} } /* class m_log */
// end class

View File

@ -1,10 +1,6 @@
<?php <?php
/* /*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2013 by the AlternC Development Team.
https://alternc.org/
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
@ -20,13 +16,12 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Purpose of file: Manage LXC-based virtual machine through an inetd-based protocol */
----------------------------------------------------------------------
*/
include_once(dirname(__FILE__) . '/vm.class.php'); include_once(dirname(__FILE__) . '/vm.class.php');
/** /**
*
* Manage AlternC's virtual machine start/stop using our own inetd-based protocol. * Manage AlternC's virtual machine start/stop using our own inetd-based protocol.
*/ */
class m_lxc implements vm { class m_lxc implements vm {
@ -38,6 +33,7 @@ class m_lxc implements vm {
public $TIMEOUT = 5; public $TIMEOUT = 5;
public $error = array(); public $error = array();
/** /**
* Constructor, initialize the class informations from AlternC's variables * Constructor, initialize the class informations from AlternC's variables
*/ */
@ -48,6 +44,7 @@ class m_lxc implements vm {
$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->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 * HOOK: add the "Console Access" to AlternC's main menu
*/ */
@ -60,11 +57,12 @@ class m_lxc implements vm {
'ico' => 'images/ssh.png', 'ico' => 'images/ssh.png',
'link' => 'vm.php', 'link' => 'vm.php',
'pos' => 95, 'pos' => 95,
); );
return $obj; return $obj;
} }
/** /**
* HOOK: remove VM history for AlternC account * HOOK: remove VM history for AlternC account
*/ */
@ -75,6 +73,7 @@ class m_lxc implements vm {
return true; return true;
} }
/** /**
* Send a message to a remote VM manager instance * Send a message to a remote VM manager instance
* $params are the parameters to send as serialized data * $params are the parameters to send as serialized data
@ -118,6 +117,7 @@ class m_lxc implements vm {
} }
} }
/** /**
* START a Virtual Machine on the remote VM manager * START a Virtual Machine on the remote VM manager
* for user $login having hashed password $pass and uid $uid * for user $login having hashed password $pass and uid $uid
@ -158,6 +158,7 @@ class m_lxc implements vm {
} }
} }
/** /**
* *
*/ */
@ -173,6 +174,7 @@ class m_lxc implements vm {
return unserialize($res); return unserialize($res);
} }
/** /**
* Stop the currently running VM * Stop the currently running VM
*/ */
@ -187,6 +189,5 @@ class m_lxc implements vm {
return TRUE; return TRUE;
} }
} } /* class m_lxc */
// class m_lxc

View File

@ -1,10 +1,6 @@
<?php <?php
/* /*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
@ -20,50 +16,48 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Purpose of file: Manage Email accounts and aliases. */
----------------------------------------------------------------------
*/
/** /**
* This class handle emails (pop and/or aliases and even wrapper for internal * This class handle emails (pop and/or aliases and even wrapper for internal
* classes) of hosted users. * classes) of hosted users.
* *
* @copyright AlternC-Team 2012-09-01 http://alternc.com/
* This class is directly using the following alternc MySQL tables: * This class is directly using the following alternc MySQL tables:
* address = any used email address will be defined here, mailbox = pop/imap mailboxes, recipient = redirection from an email to another * address = any used email address will be defined here, mailbox = pop/imap mailboxes, recipient = redirection from an email to another
* and indirectly the domain class, to know domain names from their id in the DB. * and indirectly the domain class, to know domain names from their id in the DB.
* This class is also defining a few hooks, search ->invoke in the code. * This class is also defining a few hooks, search ->invoke in the code.
*/ */
class m_mail { class m_mail {
/* ----------------------------------------------------------------- */
/** domain list for this account /**
* domain list for this account
* @access private * @access private
*/ */
var $domains; var $domains;
/* ----------------------------------------------------------------- */
/** If an email has those chars, 'not nice in shell env' ;) /**
* If an email has those chars, 'not nice in shell env' ;)
* we don't store the email in $mail/u/{user}_domain, but in $mail/_/{address_id}_domain * we don't store the email in $mail/u/{user}_domain, but in $mail/_/{address_id}_domain
* @access private * @access private
*/ */
var $specialchars = array('"', "'", '\\', '/'); var $specialchars = array('"', "'", '\\', '/');
/* ----------------------------------------------------------------- */
/** If an email has those chars, we will ONLY allow RECIPIENTS, NOT POP/IMAP for DOVECOT ! /**
* If an email has those chars, we will ONLY allow RECIPIENTS, NOT POP/IMAP for DOVECOT !
* Since Dovecot doesn't allow those characters * Since Dovecot doesn't allow those characters
* @access private * @access private
*/ */
var $forbiddenchars = array('"', "'", '\\', '/', '?', '!', '*', '$', '|', '#', '+'); var $forbiddenchars = array('"', "'", '\\', '/', '?', '!', '*', '$', '|', '#', '+');
/* ----------------------------------------------------------------- */
/** Number of results for a pager display /**
* Number of results for a pager display
* @access public * @access public
*/ */
var $total; var $total;
// Human server name for help // Human server name for help
var $srv_submission; var $srv_submission;
var $srv_smtp; var $srv_smtp;
@ -75,7 +69,6 @@ class m_mail {
var $cache_domain_mail_size = array(); var $cache_domain_mail_size = array();
var $enum_domains = array(); var $enum_domains = array();
/* ----------------------------------------------------------------- */
/** /**
* Constructeur * Constructeur
@ -91,6 +84,10 @@ class m_mail {
$this->srv_pop3s = variable_get('mail_human_pop3s', $L_FQDN, 'Human name for POP3s mail server', array('desc' => 'Name', 'type' => 'string')); $this->srv_pop3s = variable_get('mail_human_pop3s', $L_FQDN, 'Human name for POP3s mail server', array('desc' => 'Name', 'type' => 'string'));
} }
/**
* Hook called by menu class to add the email menu to the left pane
*/
function hook_menu() { function hook_menu() {
$obj = array( $obj = array(
'title' => _("Email Addresses"), 'title' => _("Email Addresses"),
@ -110,6 +107,7 @@ class m_mail {
return $obj; return $obj;
} }
function get_total_size_for_domain($domain) { function get_total_size_for_domain($domain) {
global $db; global $db;
if (empty($this->cache_domain_mail_size)) { if (empty($this->cache_domain_mail_size)) {
@ -125,7 +123,6 @@ class m_mail {
return 0; return 0;
} }
// FIXME documenter
/** /**
* @param string $domain_id * @param string $domain_id
@ -157,6 +154,7 @@ class m_mail {
return $rr; return $rr;
} }
/** /**
* @param string $domain_id * @param string $domain_id
*/ */
@ -168,6 +166,7 @@ class m_mail {
return $this->delete($catch['mail_id']); return $this->delete($catch['mail_id']);
} }
/** /**
* @param string $domain_id * @param string $domain_id
* @param string $target * @param string $target
@ -179,9 +178,9 @@ class m_mail {
$target = '@' . $target; $target = '@' . $target;
} }
if (substr($target, 0, 1) == '@') { // le premier caractere est un @ if (substr($target, 0, 1) == '@') { // the first character is @
// FIXME validate domain // FIXME validate domain
} else { // ca doit être un mail } else { // it MUST be an email
if (!filter_var($target, FILTER_VALIDATE_EMAIL)) { if (!filter_var($target, FILTER_VALIDATE_EMAIL)) {
$msg->raise("ERROR", "mail", _("The email you entered is syntaxically incorrect")); $msg->raise("ERROR", "mail", _("The email you entered is syntaxically incorrect"));
return false; return false;
@ -191,9 +190,9 @@ class m_mail {
return $this->create_alias($domain_id, '', $target, "catchall", true); return $this->create_alias($domain_id, '', $target, "catchall", true);
} }
/* ----------------------------------------------------------------- */
/** get_quota (hook for quota class), returns the number of used /**
* get_quota (hook for quota class), returns the number of used
* service for a quota-bound service * service for a quota-bound service
* @param $name string the named quota we want * @param $name string the named quota we want
* @return the number of used service for the specified quota, * @return the number of used service for the specified quota,
@ -211,18 +210,18 @@ class m_mail {
return $q; return $q;
} }
/* ----------------------------------------------------------------- */
/** Password policy kind used in this class (hook for admin class) /**
* Password policy kind used in this class (hook for admin class)
* @return array an array of policykey => "policy name (for humans)" * @return array an array of policykey => "policy name (for humans)"
*/ */
function alternc_password_policy() { function alternc_password_policy() {
return array("pop" => _("Email account password")); return array("pop" => _("Email account password"));
} }
/* ----------------------------------------------------------------- */
/** Returns the list of mail-hosting domains for a user /**
* Returns the list of mail-hosting domains for a user
* @return array indexed array of hosted domains * @return array indexed array of hosted domains
*/ */
function enum_domains($uid = -1) { function enum_domains($uid = -1) {
@ -231,7 +230,7 @@ class m_mail {
if ($uid == -1) { if ($uid == -1) {
$uid = $cuid; $uid = $cuid;
} }
$db->query(" $db->query("
SELECT SELECT
d.id, d.id,
d.domaine, d.domaine,
@ -254,9 +253,9 @@ ORDER BY
return $this->enum_domains; return $this->enum_domains;
} }
/* ----------------------------------------------------------------- */
/** available: tells if an email address can be installed in the server /**
* available: tells if an email address can be installed in the server
* check the domain part (is it mine too), the syntax, and the availability. * check the domain part (is it mine too), the syntax, and the availability.
* @param $mail string email to check * @param $mail string email to check
* @return boolean true if the email can be installed on the server * @return boolean true if the email can be installed on the server
@ -283,15 +282,15 @@ ORDER BY
} }
} }
/* ----------------------------------------------------------------- */
/* function used to list every mail address hosted on a domain. /**
* function used to list every mail address hosted on a domain.
* @param $dom_id integer the domain id. * @param $dom_id integer the domain id.
* @param $search string search that string in recipients or address. * @param $search string search that string in recipients or address.
* @param $offset integer skip THAT much emails in the result. * @param $offset integer skip THAT much emails in the result.
* @param $count integer return no more than THAT much emails. -1 for ALL. Offset is ignored then. * @param $count integer return no more than THAT much emails. -1 for ALL. Offset is ignored then.
* @result an array of each mail hosted under the domain. * @result an array of each mail hosted under the domain.
*/ */
function enum_domain_mails($dom_id = null, $search = "", $offset = 0, $count = 30, $show_systemmails = false) { function enum_domain_mails($dom_id = null, $search = "", $offset = 0, $count = 30, $show_systemmails = false) {
global $db, $msg, $hooks; global $db, $msg, $hooks;
$msg->log("mail", "enum_domains_mail"); $msg->log("mail", "enum_domains_mail");
@ -311,8 +310,8 @@ ORDER BY
$db->next_record(); $db->next_record();
$this->total = $db->f("total"); $this->total = $db->f("total");
if ($count != -1) { if ($count != -1) {
$offset = intval($offset); $offset = intval($offset);
$count = intval($count); $count = intval($count);
$limit = " LIMIT $offset, $count "; $limit = " LIMIT $offset, $count ";
} else { } else {
$limit = ""; $limit = "";
@ -343,9 +342,9 @@ ORDER BY
} }
} }
/* ----------------------------------------------------------------- */
/** Function used to insert a new mail into the db /**
* Function used to insert a new mail into the db
* should be used by the web interface, not by third-party programs. * should be used by the web interface, not by third-party programs.
* *
* This function calls the hook "hooks_mail_cancreate" * This function calls the hook "hooks_mail_cancreate"
@ -387,10 +386,10 @@ ORDER BY
// Already exists? // Already exists?
$db->query("SELECT * FROM address WHERE domain_id= ? AND address= ? ;", array($dom_id, $mail)); $db->query("SELECT * FROM address WHERE domain_id= ? AND address= ? ;", array($dom_id, $mail));
if ($db->next_record()) { if ($db->next_record()) {
if ($db->f("type") == "mailman") if ($db->f("type") == "mailman")
$msg->raise("ERROR", "mail", _("This email address already exists in mailman")); $msg->raise("ERROR", "mail", _("This email address already exists in mailman"));
else else
$msg->raise("ERROR", "mail", _("This email address already exists")); $msg->raise("ERROR", "mail", _("This email address already exists"));
return false; return false;
} }
@ -403,9 +402,9 @@ ORDER BY
return $id; return $id;
} }
/* ----------------------------------------------------------------- */
/** function used to get every information we can on a mail /**
* function used to get every information we can on a mail
* @param $mail_id integer * @param $mail_id integer
* @return array a hashtable with all the informations for that email * @return array a hashtable with all the informations for that email
*/ */
@ -435,9 +434,9 @@ ORDER BY
private $isitmy_cache = array(); private $isitmy_cache = array();
/* ----------------------------------------------------------------- */
/** Check if an email is mine ... /**
* Check if an email is mine ...
* *
* @param $mail_id integer the number of the email to check * @param $mail_id integer the number of the email to check
* @return string the complete email address if that's mine, false if not * @return string the complete email address if that's mine, false if not
@ -459,9 +458,9 @@ ORDER BY
} }
} }
/* ----------------------------------------------------------------- */
/** Hook called when the DOMAIN class will delete a domain. /**
* Hook called when the DOMAIN class will delete a domain.
* OR when the DOMAIN class tells us we don't host the emails of this domain anymore. * OR when the DOMAIN class tells us we don't host the emails of this domain anymore.
* @param $dom the ID of the domain to delete * @param $dom the ID of the domain to delete
* @return boolean if the email has been properly deleted * @return boolean if the email has been properly deleted
@ -485,7 +484,10 @@ ORDER BY
return true; return true;
} }
// return the alternc account's ID of the mail_id
/**
* return the alternc account's ID of the mail_id
*/
function get_account_by_mail_id($mail_id) { function get_account_by_mail_id($mail_id) {
global $db; global $db;
$db->query("select compte as uid from domaines d, address a where a.domain_id = d.id and a.id = ? ;", array($mail_id)); $db->query("select compte as uid from domaines d, address a where a.domain_id = d.id and a.id = ? ;", array($mail_id));
@ -495,9 +497,9 @@ ORDER BY
return $db->f('uid'); return $db->f('uid');
} }
/* ----------------------------------------------------------------- */
/** Function used to delete a mail from the db /**
* Function used to delete a mail from the db
* should be used by the web interface, not by third-party programs. * should be used by the web interface, not by third-party programs.
* *
* @param $mail_id integer the number of the email to delete * @param $mail_id integer the number of the email to delete
@ -547,9 +549,9 @@ ORDER BY
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Function used to undelete a pending deletion mail from the db /**
* Function used to undelete a pending deletion mail from the db
* should be used by the web interface, not by third-party programs. * should be used by the web interface, not by third-party programs.
* *
* @param $mail_id integer the email id * @param $mail_id integer the email id
@ -598,9 +600,9 @@ ORDER BY
} }
} }
/* ----------------------------------------------------------------- */
/** set the password of an email address. /**
* set the password of an email address.
* @param $mail_id integer email ID * @param $mail_id integer email ID
* @param $pass string the new password. * @param $pass string the new password.
* @return boolean true if the password has been set, false else, raise an error. * @return boolean true if the password has been set, false else, raise an error.
@ -616,16 +618,16 @@ ORDER BY
return false; return false;
} }
if ($canbeempty && empty($pass)) { if ($canbeempty && empty($pass)) {
return $db->query("UPDATE address SET password= ? where id = ? ;", array(null, $mail_id )); return $db->query("UPDATE address SET password= ? where id = ? ;", array(null, $mail_id ));
} else if (!$db->query("UPDATE address SET password= ? where id = ? ;", array(_md5cr($pass), $mail_id ))) { } else if (!$db->query("UPDATE address SET password= ? where id = ? ;", array(_md5cr($pass), $mail_id ))) {
return false; return false;
} }
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Enables an email address. /**
* Enables an email address.
* @param $mail_id integer Email ID * @param $mail_id integer Email ID
* @return boolean true if the email has been enabled. * @return boolean true if the email has been enabled.
*/ */
@ -641,9 +643,9 @@ ORDER BY
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Disables an email address. /**
* Disables an email address.
* @param $mail_id integer Email ID * @param $mail_id integer Email ID
* @return boolean true if the email has been enabled. * @return boolean true if the email has been enabled.
*/ */
@ -659,9 +661,9 @@ ORDER BY
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Function used to update an email settings /**
* Function used to update an email settings
* should be used by the web interface, not by third-party programs. * should be used by the web interface, not by third-party programs.
* *
* @param $mail_id integer the number of the email to delete * @param $mail_id integer the number of the email to delete
@ -719,7 +721,7 @@ ORDER BY
foreach ($r as $m) { foreach ($r as $m) {
$m = trim($m); $m = trim($m);
if ($m && ( filter_var($m, FILTER_VALIDATE_EMAIL) || $dontcheck) // Recipient Email is valid if ($m && ( filter_var($m, FILTER_VALIDATE_EMAIL) || $dontcheck) // Recipient Email is valid
&& $m != ($me["address"] . "@" . $me["domain"])) { // And not myself (no loop allowed easily ;) ) && $m != ($me["address"] . "@" . $me["domain"])) { // And not myself (no loop allowed easily ;) )
$red.=$m . "\n"; $red.=$m . "\n";
} }
} }
@ -727,15 +729,15 @@ ORDER BY
if (isset($red) && $red) { if (isset($red) && $red) {
$db->query("INSERT INTO recipient SET address_id= ?, recipients= ? ;", array($mail_id, $red)); $db->query("INSERT INTO recipient SET address_id= ?, recipients= ? ;", array($mail_id, $red));
} }
if (!$islocal && !$red) { if (!$islocal && !$red) {
$msg->raise("ALERT", "mail", _("Warning: you created an email which is not an alias, and not a POP/IMAP mailbox. This is certainly NOT what you want to do. To fix this, edit the email address and check 'Yes' in POP/IMAP account, or set some recipients in the redirection field.")); $msg->raise("ALERT", "mail", _("Warning: you created an email which is not an alias, and not a POP/IMAP mailbox. This is certainly NOT what you want to do. To fix this, edit the email address and check 'Yes' in POP/IMAP account, or set some recipients in the redirection field."));
} }
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** A wrapper used by mailman class to create it's needed addresses /**
* A wrapper used by mailman class to create it's needed addresses
* @ param : $dom_id , the domain id associated to a given address * @ param : $dom_id , the domain id associated to a given address
* @ param : $m , the left part of the mail address being created * @ param : $m , the left part of the mail address being created
* @ param : $delivery , the delivery used to deliver the mail * @ param : $delivery , the delivery used to deliver the mail
@ -749,9 +751,9 @@ ORDER BY
// FIXME return error code // FIXME return error code
} }
/* ----------------------------------------------------------------- */
/** A function used to create an alias for a specific address /**
* A function used to create an alias for a specific address
* @ param : $dom_id , the domain sql identifier * @ param : $dom_id , the domain sql identifier
* @ param : $m , the alias we want to create * @ param : $m , the alias we want to create
* @ param : $alias , the already existing aliased address * @ param : $alias , the already existing aliased address
@ -772,9 +774,9 @@ ORDER BY
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** A wrapper used by mailman class to create it's needed addresses /**
* A wrapper used by mailman class to create it's needed addresses
* @ param : $mail_id , the mysql id of the mail address we want to delete * @ param : $mail_id , the mysql id of the mail address we want to delete
* of the email for the current acccount. * of the email for the current acccount.
*/ */
@ -784,9 +786,9 @@ ORDER BY
$this->delete($mail_id); $this->delete($mail_id);
} }
/* ----------------------------------------------------------------- */
/** Export the mail information of an account /**
* Export the mail information of an account
* @return: str, string containing the complete configuration * @return: str, string containing the complete configuration
* of the email for the current acccount. * of the email for the current acccount.
*/ */
@ -825,7 +827,6 @@ ORDER BY
return $str; return $str;
} }
/* ----------------------------------------------------------------- */
/** /**
* Return the list of allowed slave accounts (secondary-mx) * Return the list of allowed slave accounts (secondary-mx)
@ -844,7 +845,6 @@ ORDER BY
return $res; return $res;
} }
/* ----------------------------------------------------------------- */
/** /**
* Check for a slave account (secondary mx) * Check for a slave account (secondary mx)
@ -861,9 +861,9 @@ ORDER BY
return false; return false;
} }
/* ----------------------------------------------------------------- */
/** Out (echo) the complete hosted domain list : /**
* Out (echo) the complete hosted domain list :
*/ */
function echo_domain_list($format = null) { function echo_domain_list($format = null) {
global $db; global $db;
@ -875,21 +875,20 @@ ORDER BY
$tt.=$db->f("domaine"); $tt.=$db->f("domaine");
} }
# Generate an integrity check // Generate an integrity check
$obj = array('integrity' => md5($tt), 'items' => $lst); $obj = array('integrity' => md5($tt), 'items' => $lst);
switch ($format) { switch ($format) {
case "json": case "json":
return json_encode($obj); return json_encode($obj);
default: default:
foreach ($lst as $l) { foreach ($lst as $l) {
echo $l . "\n"; echo $l . "\n";
} }
return true; return true;
} // switch } // switch
} }
/* ----------------------------------------------------------------- */
/** /**
* Add a slave account that will be allowed to access the mxdomain list * Add a slave account that will be allowed to access the mxdomain list
@ -908,7 +907,6 @@ ORDER BY
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** /**
* Remove a slave account * Remove a slave account
@ -920,9 +918,9 @@ ORDER BY
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** hook function called by AlternC when a domain is created for /**
* hook function called by AlternC when a domain is created for
* the current user account using the SLAVE DOMAIN feature * the current user account using the SLAVE DOMAIN feature
* This function create a CATCHALL to the master domain * This function create a CATCHALL to the master domain
* @param string $domain_id Domain that has just been created * @param string $domain_id Domain that has just been created
@ -936,9 +934,9 @@ ORDER BY
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** hook function called by AlternC when a domain is created for /**
* hook function called by AlternC when a domain is created for
* the current user account * the current user account
* This function create a postmaster mail which is an alias to LOGIN @ FQDN * This function create a postmaster mail which is an alias to LOGIN @ FQDN
* wich is a dynamic alias to the alternc's account mail * wich is a dynamic alias to the alternc's account mail
@ -968,9 +966,9 @@ ORDER BY
return $this->create_alias($domain_id, 'postmaster', $mem->user['login'] . '@' . $mailname); return $this->create_alias($domain_id, 'postmaster', $mem->user['login'] . '@' . $mailname);
} }
/* ----------------------------------------------------------------- */
/** hook function called by variables when a variable is changed /**
* hook function called by variables when a variable is changed
* @access private * @access private
*/ */
function hook_variable_set($name, $old, $new) { function hook_variable_set($name, $old, $new) {
@ -1000,9 +998,9 @@ ORDER BY
} }
} }
/* ----------------------------------------------------------------- */
/** Set or UPDATE the DNS record for the domain $dom(str) to be $spf /**
* Set or UPDATE the DNS record for the domain $dom(str) to be $spf
* account's login is current and if not it's $login. * account's login is current and if not it's $login.
* don't change spf if current value is not $old * don't change spf if current value is not $old
* @access private * @access private
@ -1030,9 +1028,9 @@ ORDER BY
$db->query("UPDATE domaines SET dns_action='UPDATE' WHERE domaine= ?;", array($domain)); $db->query("UPDATE domaines SET dns_action='UPDATE' WHERE domaine= ?;", array($domain));
} }
/* ----------------------------------------------------------------- */
/** Set or UPDATE the DNS record for the domain $dom(str) to be $dmarc /**
* Set or UPDATE the DNS record for the domain $dom(str) to be $dmarc
* account's login is current and if not it's $login. * account's login is current and if not it's $login.
* don't change dmarc if current value is not $old * don't change dmarc if current value is not $old
* @access private * @access private
@ -1063,9 +1061,9 @@ ORDER BY
$db->query("UPDATE domaines SET dns_action='UPDATE' WHERE domaine= ?;", array($domain)); $db->query("UPDATE domaines SET dns_action='UPDATE' WHERE domaine= ?;", array($domain));
} }
/* ----------------------------------------------------------------- */
/** hook function called by AlternC-upnp to know which open /**
* hook function called by AlternC-upnp to know which open
* tcp or udp ports this class requires or suggests * tcp or udp ports this class requires or suggests
* @return array a key => value list of port protocol name mandatory values * @return array a key => value list of port protocol name mandatory values
* @access private * @access private
@ -1082,6 +1080,5 @@ ORDER BY
); );
} }
}
/* Class m_mail */ } /* Class m_mail */

View File

@ -1,7 +1,6 @@
<?php <?php
/* /*
$Id: m_mem.php,v 1.19 2006/01/12 08:04:43 anarcat Exp $
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
@ -17,11 +16,7 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Original Author of file: Benjamin Sonntag */
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 in the web desktop.
@ -35,27 +30,17 @@ class m_mem {
/** Original uid for the temporary uid swapping (for administrators) */ /** 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. * This array contains the Tableau contenant les champs de la table "membres" du membre courant
*/ */
var $user; var $user;
/** Tableau contenant les champs de la table "local" du membre courant /**
* Ce tableau est utilisable globalement par toutes les classes filles. * contains all the fields of the "local" table for an account in AlternC.
* Note : les champs de "local" sont specifiques a l'hebergeur. * they are specific to the hosting provider
*/ */
var $local; var $local;
/* ----------------------------------------------------------------- */
/**
* Constructeur
*/
function m_mem() {
}
/* ----------------------------------------------------------------- */
/** /**
* Password kind used in this class (hook for admin class) * Password kind used in this class (hook for admin class)
@ -64,29 +49,33 @@ class m_mem {
return array("mem" => "AlternC's account password"); return array("mem" => "AlternC's account password");
} }
/**
* hook called by the m_menu class to add menu to the left of the panel
*/
function hook_menu() { function hook_menu() {
$obj = array( $obj = array(
'title' => _("Settings"), 'title' => _("Settings"),
'ico' => 'images/settings.png', 'ico' => 'images/settings.png',
'link' => 'mem_param.php', 'link' => 'mem_param.php',
'pos' => 160, 'pos' => 160,
); );
return $obj; return $obj;
} }
/* ----------------------------------------------------------------- */
/** Check that the current user is an admnistrator. /**
* Check that the current user is an admnistrator.
* @return boolean TRUE if we are super user, or FALSE if we are not. * @return boolean TRUE if we are super user, or FALSE if we are not.
*/ */
function checkright() { function checkright() {
return ($this->user["su"] == "1"); return ($this->user["su"] == "1");
} }
/* ----------------------------------------------------------------- */
/** Start a session in the web desktop. Check username and password. /**
* 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 * <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. * and told to the corresponding user on next successfull login.
* @param $username string Username that want to get connected. * @param $username string Username that want to get connected.
@ -96,8 +85,7 @@ class m_mem {
function login($username, $password, $restrictip = 0, $authip_token = false) { function login($username, $password, $restrictip = 0, $authip_token = false) {
global $db, $msg, $cuid, $authip; global $db, $msg, $cuid, $authip;
$msg->log("mem", "login", $username); $msg->log("mem", "login", $username);
// $username=addslashes($username);
// $password=addslashes($password);
$db->query("select * from membres where login= ? ;", array($username)); $db->query("select * from membres where login= ? ;", array($username));
if ($db->num_rows() == 0) { if ($db->num_rows() == 0) {
$msg->raise("ERROR", "mem", _("User or password incorrect")); $msg->raise("ERROR", "mem", _("User or password incorrect"));
@ -168,9 +156,9 @@ class m_mem {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Start a session as another user from an administrator account. /**
* 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 * 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. * account (for good), and su allow any user to become another account for some commands only.
* (del_user, add_user ...) and allow to bring back admin rights with unsu * (del_user, add_user ...) and allow to bring back admin rights with unsu
@ -208,9 +196,9 @@ class m_mem {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Suite <EFBFBD> la connexion de l'utilisateur, r<EFBFBD>initialise ses param<EFBFBD>tres de derni<EFBFBD>re connexion /**
* After a successful connection, reset the user's last connection date
*/ */
function resetlast() { function resetlast() {
global $db, $cuid; global $db, $cuid;
@ -221,6 +209,7 @@ class m_mem {
$db->query("UPDATE membres SET lastlogin=NOW(), lastfail=0, lastip= ? WHERE uid= ?;", array($ip, $cuid)); $db->query("UPDATE membres SET lastlogin=NOW(), lastfail=0, lastip= ? WHERE uid= ?;", array($ip, $cuid));
} }
function authip_token($bis = false) { function authip_token($bis = false) {
global $db, $cuid; global $db, $cuid;
$db->query("select pass from membres where uid= ?;", array($cuid)); $db->query("select pass from membres where uid= ?;", array($cuid));
@ -232,6 +221,7 @@ class m_mem {
return md5("$i--" . $db->f('pass')); return md5("$i--" . $db->f('pass'));
} }
/** /**
* @param boolean $t * @param boolean $t
*/ */
@ -240,27 +230,27 @@ class m_mem {
} }
/* Faut finir de l'implementer :) * / /* Faut finir de l'implementer :) * /
function authip_class() { function authip_class() {
global $cuid; global $cuid;
$c = Array(); $c = Array();
$c['name']="Panel access"; $c['name']="Panel access";
$c['protocol']="mem"; $c['protocol']="mem";
$c['values']=Array($cuid=>''); $c['values']=Array($cuid=>'');
return $c; return $c;
} }
/* */ /* */
/* ----------------------------------------------------------------- */
/** Verifie que la session courante est correcte (cookie ok et ip valide). /**
* Si besoin, et si reception des champs username & password, cree une nouvelle * Check that the current session is correct (valid cookie)
* session pour l'utilisateur annonce. * If necessary, and if we received username & password fields,
* Cette fonction doit etre appellee a chaque page devant etre authentifiee. * create a new session for the user.
* et AVANT d'emettre des donnees. (un cookie peut etre envoye) * This function MUST be called by each page to authenticate the user.
* @global string $session Le cookie de session eventuel * and BEFORE sending any data (since a cookie can be sent)
* @global string $username/password le login/pass de l'utilisateur * @global string $session the session cookie
* @return boolean TRUE si la session est correcte, FALSE sinon. * @global string $username & $password the login / pass of the user
* @return boolean TRUE if the session is OK, FALSE if it is not.
*/ */
function checkid($show_msg = true) { function checkid($show_msg = true) {
global $db, $msg, $cuid; global $db, $msg, $cuid;
@ -273,16 +263,19 @@ class m_mem {
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 } // end isset
$_COOKIE["session"] = isset($_COOKIE["session"]) ? $_COOKIE["session"] : ""; $_COOKIE["session"] = isset($_COOKIE["session"]) ? $_COOKIE["session"] : "";
if (strlen($_COOKIE["session"]) != 32) { if (strlen($_COOKIE["session"]) != 32) {
if ($show_msg) if ($show_msg)
$msg->raise("ERROR", "mem", _("Identity lost or unknown, please login")); $msg->raise("ERROR", "mem", _("Identity lost or unknown, please login"));
return false; return false;
} }
$ip = get_remote_ip(); $ip = get_remote_ip();
$db->query("select uid, ? as me,ip from sessions where sid= ?;", array($ip, $_COOKIE["session"])); $db->query("select uid, ? as me,ip from sessions where sid= ?;", array($ip, $_COOKIE["session"]));
if ($db->num_rows() == 0) { if ($db->num_rows() == 0) {
if ($show_msg) if ($show_msg)
$msg->raise("ERROR", "mem", _("Identity lost or unknown, please login")); $msg->raise("ERROR", "mem", _("Identity lost or unknown, please login"));
return false; return false;
} }
@ -298,7 +291,8 @@ class m_mem {
$db->next_record(); $db->next_record();
$this->user = $db->Record; $this->user = $db->Record;
$msg->init_msgs(); $msg->init_msgs();
/* Remplissage de $local */
/* Fills $local */
$db->query("SELECT * FROM local WHERE uid= ? ;", array($cuid)); $db->query("SELECT * FROM local WHERE uid= ? ;", array($cuid));
if ($db->num_rows()) { if ($db->num_rows()) {
$db->next_record(); $db->next_record();
@ -307,11 +301,11 @@ class m_mem {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Change l'identite d'un utilisateur temporairement. /**
* @global string $uid Utilisateur dont on prends l'identite * Change the identity of the user temporarily (SUDO)
* @return TRUE si la session est correcte, FALSE sinon. * @global string $uid User that we want to impersonate
* @return boolean TRUE if it's okay, FALSE if it's not.
*/ */
function su($uid) { function su($uid) {
global $cuid, $db, $msg, $mysql; global $cuid, $db, $msg, $mysql;
@ -332,10 +326,10 @@ class m_mem {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Retourne a l'identite d'origine de l'utilisateur apres su. /**
* @return boolean TRUE si la session est correcte, FALSE sinon. * Goes back to the original identity (of an admin, usually)
* @return boolean TRUE if it's okay, FALSE if it's not.
*/ */
function unsu() { function unsu() {
global $mysql; global $mysql;
@ -349,10 +343,10 @@ class m_mem {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Termine une session du bureau virtuel (logout) /**
* @return boolean TRUE si la session a bien ete detruite, FALSE sinon. * Ends a session on the panel (logout)
* @return boolean TRUE if it's okay, FALSE if it's not.
*/ */
function del_session() { function del_session() {
global $db, $user, $msg, $cuid, $hooks; global $db, $user, $msg, $cuid, $hooks;
@ -382,14 +376,6 @@ class m_mem {
$db->query("delete from sessions where sid= ? ;", array($_COOKIE["session"])); $db->query("delete from sessions where sid= ? ;", array($_COOKIE["session"]));
$msg->init_msgs(); $msg->init_msgs();
# Invoker le logout dans toutes les autres classes
/*
foreach($classes as $c) {
if (method_exists($GLOBALS[$c],"alternc_del_session")) {
$GLOBALS[$c]->alternc_del_session();
}
}
*/
$hooks->invoke("alternc_del_session"); $hooks->invoke("alternc_del_session");
session_unset(); session_unset();
@ -397,13 +383,13 @@ class m_mem {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Change le mot de passe de l'utilisateur courant. /**
* @param string $oldpass Ancien mot de passe. * Change the password of the current user
* @param string $newpass Nouveau mot de passe * @param string $oldpass Old password
* @param string $newpass2 Nouveau mot de passe (a nouveau) * @param string $newpass New password
* @return boolean TRUE si le mot de passe a ete change, FALSE sinon. * @param string $newpass2 New password (again)
* @return boolean TRUE if the password has been change, FALSE if not.
*/ */
function passwd($oldpass, $newpass, $newpass2) { function passwd($oldpass, $newpass, $newpass2) {
global $db, $msg, $cuid, $admin; global $db, $msg, $cuid, $admin;
@ -432,11 +418,11 @@ class m_mem {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Change les preferences administrateur d'un compte /**
* @param integer $admlist Mode de visualisation des membres (0=large 1=courte) * Change the administrator preferences of an admin account
* @return boolean TRUE si les preferences ont ete changees, FALSE sinon. * @param integer $admlist visualisation mode of the account list (0=large 1=short)
* @return boolean TRUE if the preferences has been changed, FALSE if not.
*/ */
function adminpref($admlist) { function adminpref($admlist) {
global $db, $msg, $cuid; global $db, $msg, $cuid;
@ -450,13 +436,13 @@ class m_mem {
return true; 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. * Send a mail with a password to an account
* <b>Note : </b>We can ask for a password only once a day
* TODO : Translate this mail into the localization program. * TODO : Translate this mail into the localization program.
* TODO : Check this function's ! * TODO : Check this function's !
* @return boolean TRUE si le mot de passe a ete envoye avec succes, FALSE sinon. * @return boolean TRUE if the password has been sent, FALSE if not.
*/ */
function send_pass($login) { function send_pass($login) {
global $msg, $db, $L_HOSTING, $L_FQDN; global $msg, $db, $L_HOSTING, $L_FQDN;
@ -495,12 +481,12 @@ Cordially.
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Change le mail d'un membre (premiere etape, envoi du CookiE) /**
* Change the email of an account (first step: sending of a Cookie)
* TODO : insert this mail string into the localization system * TODO : insert this mail string into the localization system
* @param string $newmail Nouveau mail souhaite pour le membre. * @param string $newmail New mail we want to set for this account
* @return string le cookie si le mail a bien ete envoye, FALSE sinon * @return boolean TRUE if the email with a link has been sent, FALSE if not
*/ */
function ChangeMail1($newmail) { function ChangeMail1($newmail) {
global $msg, $db, $L_HOSTING, $L_FQDN, $cuid; global $msg, $db, $L_HOSTING, $L_FQDN, $cuid;
@ -537,22 +523,22 @@ again, please contact your server's administrator.
Cordially. Cordially.
"), $db->f("login"), $L_HOSTING, $link); "), $db->f("login"), $L_HOSTING, $link);
mail($newmail, "Email modification request on $L_HOSTING", $txt, "From: postmaster@$L_FQDN\nReply-to: postmaster@$L_FQDN"); 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= ? ;", array($cuid)); $db->query("DELETE FROM chgmail WHERE uid= ? ;", array($cuid));
$db->query("INSERT INTO chgmail (cookie,ckey,uid,mail,ts) VALUES ( ?, ?, ?, ?, ?);", array($COOKIE, $KEY, $cuid, $newmail, time())); $db->query("INSERT INTO chgmail (cookie,ckey,uid,mail,ts) VALUES ( ?, ?, ?, ?, ?);", array($COOKIE, $KEY, $cuid, $newmail, time()));
// Supprime les cookies de la veille :)
$lts = time() - 86400; $lts = time() - 86400;
$db->query("DELETE FROM chgmail WHERE ts< ? ;", array($lts)); $db->query("DELETE FROM chgmail WHERE ts< ? ;", array($lts));
return $KEY; return $KEY;
} }
/* ----------------------------------------------------------------- */
/** Change le mail d'un membre (seconde etape, CookiE+cle = application) /**
* @param string $COOKIE Cookie envoye par mail * Change the email of a member (second step, Cookie + key change)
* @param string $KEY cle affichee a l'ecran * @param string $COOKIE Cookie sent by mail
* @param integer $uid Utilisateur concerne (on est hors session) * @param string $KEY cle shown on the screen
* @return boolean TRUE si le mail a bien ete modifie, FALSE sinon * @param integer $uid User id (we may not be connected)
* @return boolean TRUE if the email has been changed, FALSE if not.
*/ */
function ChangeMail2($COOKIE, $KEY, $uid) { function ChangeMail2($COOKIE, $KEY, $uid) {
global $msg, $db; global $msg, $db;
@ -574,10 +560,10 @@ Cordially.
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Modifie le parametre d'aide en ligne (1/0) /**
* @param integer $show Faut-il (1) ou non (0) afficher l'aide en ligne * Change the help parameter
* @param integer $show Shall we (1) or not (0) show the online help
*/ */
function set_help_param($show) { function set_help_param($show) {
global $db, $msg, $cuid; global $db, $msg, $cuid;
@ -585,27 +571,27 @@ Cordially.
$db->query("UPDATE membres SET show_help= ? WHERE uid= ? ;", array($show, $cuid)); $db->query("UPDATE membres SET show_help= ? WHERE uid= ? ;", array($show, $cuid));
} }
/* ----------------------------------------------------------------- */
/** Dit si l'aide en ligne est demandee /**
* @return boolean TRUE si l'aide en ligne est demandee, FALSE sinon. * tell if the help parameter is set
* @return boolean TRUE if the account want online help, FALSE if not.
*/ */
function get_help_param() { function get_help_param() {
return $this->user["show_help"]; return $this->user["show_help"];
} }
/* ----------------------------------------------------------------- */
/** Affiche (echo) l'aide contextuelle /**
* @param integer $file Numero de fichier d'aide a afficher. * show (echo) a contextual help
* @return boolean TRUE si l'aide contextuelle a ete trouvee, FALSE sinon * @param integer $file File number in the help system to show
* @return boolean TRUE if the help has been shown, FALSE if not.
*/ */
function show_help($file, $force = false) { function show_help($file, $force = false) {
if ($this->user["show_help"] || $force) { if ($this->user["show_help"] || $force) {
$hlp = _("hlp_$file"); $hlp = _("hlp_$file");
if ($hlp != "hlp_$file") { if ($hlp != "hlp_$file") {
$hlp = preg_replace( $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); "#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>"; echo "<p class=\"hlp\">" . $hlp . "</p>";
return true; return true;
} }
@ -615,6 +601,7 @@ Cordially.
} }
} }
/** /**
* @param integer $uid * @param integer $uid
*/ */
@ -628,7 +615,6 @@ Cordially.
return intval($db->f('creator')); return intval($db->f('creator'));
} }
/* ----------------------------------------------------------------- */
/** /**
* Exports all the personal user related information for an account. * Exports all the personal user related information for an account.
@ -689,6 +675,4 @@ Cordially.
return true; return true;
} }
} } /* Class m_mem */
/* Classe Membre */

View File

@ -1,10 +1,6 @@
<?php <?php
/* /*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
@ -20,25 +16,19 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Purpose of file: Manage hook system. */
----------------------------------------------------------------------
*/
/** /**
* This class manage menu. * This class manage the left menu of AlternC
* *
* @copyright AlternC-Team 2002-2005 http://alternc.org/ * @copyright AlternC-Team 2002-2005 http://alternc.org/
*/ */
class m_menu { class m_menu {
/* --------------------------------------------------------------------------- */
/** Constructor /**
* menu([$mid]) Constructeur de la classe menu, ne fait rien pour le moment * get all menus to display,
* uses hooks
*/ */
function m_menu() {
}
function getmenu() { function getmenu() {
global $hooks, $quota, $mem; global $hooks, $quota, $mem;
@ -102,13 +92,17 @@ class m_menu {
return $lst; return $lst;
} }
/**
* utilitary function used by usort() to order menus
*/
function order_menu($a, $b) { function order_menu($a, $b) {
// Use to order the menu with a usort
return $a['pos'] > $b['pos']; return $a['pos'] > $b['pos'];
} }
/**
* some menus that don't have an attached class
*/
function system_menu() { function system_menu() {
// Here some needed menu who don't have a class
global $help_baseurl, $lang_translation, $locales; global $help_baseurl, $lang_translation, $locales;
$m = array( $m = array(
@ -150,6 +144,4 @@ class m_menu {
return $m; return $m;
} }
} } /* Class m_menu */
/* Class menu */

View File

@ -52,6 +52,7 @@ class m_messages {
$this->init_msgs(); $this->init_msgs();
} }
/** /**
* Record a message, insert it into the logfile. * Record a message, insert it into the logfile.
* *
@ -83,6 +84,7 @@ class m_messages {
return true; return true;
} }
/** /**
* Reset the stored messages array * Reset the stored messages array
*/ */
@ -92,6 +94,7 @@ class m_messages {
} }
} }
/** /**
* Tell if there are stored messages for a specific level * Tell if there are stored messages for a specific level
* or for all levels (if level is empty) * or for all levels (if level is empty)
@ -113,6 +116,7 @@ class m_messages {
} }
} }
/** /**
* Return a string of concateneted messages of all recorded messages * Return a string of concateneted messages of all recorded messages
* or only the last message * or only the last message
@ -162,6 +166,7 @@ class m_messages {
return $str; return $str;
} }
/** /**
* Return a message in HTML form with associated CSS * Return a message in HTML form with associated CSS
* *
@ -186,6 +191,7 @@ class m_messages {
return $str; return $str;
} }
/** /**
* Return all the messages of all levels in HTML form with associated CSS * Return all the messages of all levels in HTML form with associated CSS
* *
@ -207,6 +213,7 @@ class m_messages {
return $msg; return $msg;
} }
/** /**
* Log a message into /var/log/alternc/bureau.log * Log a message into /var/log/alternc/bureau.log
* *
@ -235,6 +242,7 @@ class m_messages {
); );
} }
/** /**
* Log an API function call into /var/log/alternc/bureau.log * Log an API function call into /var/log/alternc/bureau.log
* *
@ -255,6 +263,4 @@ class m_messages {
); );
} }
} } /* Class m_messages */
/* Class m_messages */

View File

@ -1,14 +1,6 @@
<?php <?php
/* /*
$Id: m_mysql.php,v 1.35 2005/12/18 09:51:32 benjamin Exp $
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2002 by the AlternC Development Team.
http://alternc.org/
----------------------------------------------------------------------
Based on:
Valentin Lacambre's web hosting softwares: http://altern.org/
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
@ -24,16 +16,13 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Original Author of file: Benjamin Sonntag */
Purpose of file: Manage mysql database for users.
----------------------------------------------------------------------
*/
/** /**
* MySQL user database management for AlternC. * MySQL user database management for AlternC.
* This class manage user's databases in MySQL, and user's MySQL accounts. * This class manage user's databases in MySQL, and user's MySQL accounts.
* *
* @copyright AlternC-Team 2002-2005 http://alternc.org/ * @copyright AlternC-Team 2000-2017 https://alternc.com/
*/ */
class DB_users extends DB_Sql { class DB_users extends DB_Sql {
@ -42,24 +31,25 @@ class DB_users extends DB_Sql {
/** /**
* Creator * Creator
*/ */
function __construct() { // Sometimes we need to create this object with empty parameters, but by default we fill them with those of the current user's DB function __construct() {
global $cuid, $db, $msg; // Sometimes we need to create this object with empty parameters, but by default we fill them with those of the current user's DB
global $cuid, $db, $msg;
$db->query("select db_servers.* from db_servers, membres where membres.uid= ? and membres.db_server_id=db_servers.id;", array($cuid)); $db->query("select db_servers.* from db_servers, membres where membres.uid= ? and membres.db_server_id=db_servers.id;", array($cuid));
if (!$db->next_record()) { if (!$db->next_record()) {
$msg->raise("ERROR", 'db_user', _("There are no databases in db_servers for this user. Please contact your administrator.")); $msg->raise("ERROR", 'db_user', _("There are no databases in db_servers for this user. Please contact your administrator."));
die(); die();
} }
# Create the object // Create the object
$this->HumanHostname = $db->f('name'); $this->HumanHostname = $db->f('name');
$this->Host = $db->f('host'); $this->Host = $db->f('host');
$this->User = $db->f('login'); $this->User = $db->f('login');
$this->Password = $db->f('password'); $this->Password = $db->f('password');
$this->Client = $db->f('client'); $this->Client = $db->f('client');
$this->Database = "mysql"; $this->Database = "mysql";
parent::__construct("mysql", $db->f('host'), $db->f('login'), $db->f('password') ); parent::__construct("mysql", $db->f('host'), $db->f('login'), $db->f('password') );
} }
@ -69,12 +59,12 @@ class m_mysql {
var $dbus; var $dbus;
/* --------------------------------------------------------------------------- */
/** Constructor /**
* Constructor
* m_mysql([$mid]) Constructeur de la classe m_mysql, initialise le membre concerne * m_mysql([$mid]) Constructeur de la classe m_mysql, initialise le membre concerne
*/ */
function m_mysql() { function __construct() {
global $cuid; global $cuid;
if (!empty($cuid)) { if (!empty($cuid)) {
$this->dbus = new DB_users(); $this->dbus = new DB_users();
@ -82,10 +72,12 @@ class m_mysql {
variable_get('sql_allow_users_backups', 1, 'Set 1 to allow users to configure backup of their databases, 0 if you want do disable this feature. Warning: it will not stop configured backup made by sqlbackup.sh'); variable_get('sql_allow_users_backups', 1, 'Set 1 to allow users to configure backup of their databases, 0 if you want do disable this feature. Warning: it will not stop configured backup made by sqlbackup.sh');
} }
function reload_dbus() { function reload_dbus() {
$this->dbus = new DB_users(); $this->dbus = new DB_users();
} }
function list_db_servers() { function list_db_servers() {
global $db; global $db;
$db->query("select d.*, IFNULL(count(m.uid),0) as nb_users from db_servers d left join membres m on d.id = m.db_server_id group by d.id,m.db_server_id order by d.name,d.id;"); $db->query("select d.*, IFNULL(count(m.uid),0) as nb_users from db_servers d left join membres m on d.id = m.db_server_id group by d.id,m.db_server_id order by d.name,d.id;");
@ -96,6 +88,7 @@ class m_mysql {
return $c; return $c;
} }
function hook_menu() { function hook_menu() {
global $quota; global $quota;
$q = $quota->getquota("mysql"); $q = $quota->getquota("mysql");
@ -126,7 +119,6 @@ class m_mysql {
return $obj; return $obj;
} }
/* ----------------------------------------------------------------- */
/** /**
* Password kind used in this class (hook for admin class) * Password kind used in this class (hook for admin class)
@ -135,9 +127,9 @@ class m_mysql {
return array("mysql" => "MySQL users"); return array("mysql" => "MySQL users");
} }
/* --------------------------------------------------------------------------- */
/** Get the list of the database for the current user. /**
* Get the list of the database for the current user.
* @return array returns an associative array as follow : <br> * @return array returns an associative array as follow : <br>
* "db" => database name "bck" => backup mode for this db * "db" => database name "bck" => backup mode for this db
* "dir" => Backup folder. * "dir" => Backup folder.
@ -156,9 +148,9 @@ class m_mysql {
return $c; return $c;
} }
/* --------------------------------------------------------------------------- */
/** Get the login and password of the special user able to connect to phpmyadmin /**
* Get the login and password of the special user able to connect to phpmyadmin
* @return array returns an associative array with login and password * @return array returns an associative array with login and password
* Returns FALSE if error * Returns FALSE if error
*/ */
@ -179,9 +171,9 @@ class m_mysql {
return $info; return $info;
} }
/* --------------------------------------------------------------------------- */
/** Returns the details of a user's database. /**
* Returns the details of a user's database.
* $dbn is the name of the database (after the _) or nothing for the database "$user" * $dbn is the name of the database (after the _) or nothing for the database "$user"
* @return string returns an associative array as follow : * @return string returns an associative array as follow :
* "db" => Name of the database * "db" => Name of the database
@ -216,9 +208,9 @@ class m_mysql {
return array("enabled" => true, "login" => $db->f("login"), "db" => $db->f("db"), "name" => $dbn, "bck" => $db->f("bck_mode"), "dir" => substr($db->f("bck_dir"), strlen($root)), "size" => $size, "pass" => $db->f("pass"), "history" => $db->f("bck_history"), "gzip" => $db->f("bck_gzip")); return array("enabled" => true, "login" => $db->f("login"), "db" => $db->f("db"), "name" => $dbn, "bck" => $db->f("bck_mode"), "dir" => substr($db->f("bck_dir"), strlen($root)), "size" => $size, "pass" => $db->f("pass"), "history" => $db->f("bck_history"), "gzip" => $db->f("bck_gzip"));
} }
/* --------------------------------------------------------------------------- */
/** Create a new database for the current user. /**
* Create a new database for the current user.
* @param $dbn string Database name ($user_$dbn is the mysql db name) * @param $dbn string Database name ($user_$dbn is the mysql db name)
* @return boolean if the database $user_$db has been successfully created, or FALSE if * @return boolean if the database $user_$db has been successfully created, or FALSE if
* an error occured, such as over quota user. * an error occured, such as over quota user.
@ -248,7 +240,7 @@ class m_mysql {
return false; return false;
} }
$len=variable_get("sql_max_database_length", 64); $len=variable_get("sql_max_database_length", 64);
if (strlen($dbname) > $len) { if (strlen($dbname) > $len) {
$msg->raise("ERROR", "mysql", _("Database name cannot exceed %d characters"), $len); $msg->raise("ERROR", "mysql", _("Database name cannot exceed %d characters"), $len);
return false; return false;
@ -310,9 +302,9 @@ class m_mysql {
} }
} }
/* --------------------------------------------------------------------------- */
/** Delete a database for the current user. /**
* Delete a database for the current user.
* @param $dbname string Name of the database to delete. The db name is $user_$dbn * @param $dbname string Name of the database to delete. The db name is $user_$dbn
* @return boolean if the database $user_$db has been successfully deleted, or FALSE if * @return boolean if the database $user_$db has been successfully deleted, or FALSE if
* an error occured, such as db does not exist. * an error occured, such as db does not exist.
@ -331,7 +323,7 @@ class m_mysql {
$db->query("DELETE FROM db WHERE uid= ? AND db= ? ;", array($cuid, $dbname)); $db->query("DELETE FROM db WHERE uid= ? AND db= ? ;", array($cuid, $dbname));
$this->dbus->query("DROP DATABASE $dbname;"); $this->dbus->query("DROP DATABASE $dbname;");
$db_esc = str_replace('_', '\_', $dbname); $db_esc = str_replace('_', '\_', $dbname);
$this->dbus->query("DELETE FROM mysql.db WHERE Db= ? ;", array($db_esc)); $this->dbus->query("DELETE FROM mysql.db WHERE Db= ? ;", array($db_esc));
// We test if the user created with the database is associated with more than 1 database. // We test if the user created with the database is associated with more than 1 database.
@ -343,9 +335,9 @@ class m_mysql {
return true; return true;
} }
/* --------------------------------------------------------------------------- */
/** Set the backup parameters for the database $db /**
* Set the backup parameters for the database $db
* @param $dbn string database name * @param $dbn string database name
* @param $bck_mode integer Backup mode (0 = none 1 = daily 2 = weekly) * @param $bck_mode integer Backup mode (0 = none 1 = daily 2 = weekly)
* @param $bck_history integer How many backup should we keep ? * @param $bck_history integer How many backup should we keep ?
@ -402,9 +394,9 @@ class m_mysql {
return true; return true;
} }
/* --------------------------------------------------------------------------- */
/** Change the password of the user in MySQL /**
* Change the password of the user in MySQL
* @param $password string new password (cleartext) * @param $password string new password (cleartext)
* @return boolean TRUE if the password has been successfully changed, FALSE else. * @return boolean TRUE if the password has been successfully changed, FALSE else.
*/ */
@ -424,7 +416,7 @@ class m_mysql {
return false; return false;
} }
$len=variable_get("sql_max_username_length", 16); $len=variable_get("sql_max_username_length", 16);
if (strlen($password) > $len) { if (strlen($password) > $len) {
$msg->raise("ERROR", "mysql", _("MySQL password cannot exceed %d characters"), $len); $msg->raise("ERROR", "mysql", _("MySQL password cannot exceed %d characters"), $len);
return false; return false;
@ -443,6 +435,7 @@ class m_mysql {
return true; return true;
} }
/** /**
* Function used to grant SQL rights to users: * Function used to grant SQL rights to users:
* @base :database * @base :database
@ -496,9 +489,9 @@ class m_mysql {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Restore a sql database. /**
* Restore a sql database.
* @param $file string The filename, relative to the user root dir, which contains a sql dump * @param $file string The filename, relative to the user root dir, which contains a sql dump
* @param $stdout boolean shall-we dump the error to stdout ? * @param $stdout boolean shall-we dump the error to stdout ?
* @param $id integer The ID of the database to dump to. * @param $id integer The ID of the database to dump to.
@ -546,9 +539,9 @@ class m_mysql {
} }
} }
/* ----------------------------------------------------------------- */
/** Get the size of a database /**
* Get the size of a database
* @param $dbname name of the database * @param $dbname name of the database
* @return integer database size * @return integer database size
* @access private * @access private
@ -565,11 +558,10 @@ class m_mysql {
return $size; return $size;
} }
/* ------------------------------------------------------------ */
/** /**
* Returns the list of database users of an account * Returns the list of database users of an account
* */ */
function get_userslist($all = null) { function get_userslist($all = null) {
global $db, $msg, $cuid; global $db, $msg, $cuid;
$msg->log("mysql", "get_userslist"); $msg->log("mysql", "get_userslist");
@ -592,13 +584,14 @@ class m_mysql {
return $c; return $c;
} }
function get_defaultsparam($dbn) { function get_defaultsparam($dbn) {
global $db, $msg, $cuid; global $db, $msg, $cuid;
$msg->log("mysql", "getdefaults"); $msg->log("mysql", "getdefaults");
$dbu = $dbn; $dbu = $dbn;
$r = array(); $r = array();
$dbn = str_replace('_', '\_', $dbn); $dbn = str_replace('_', '\_', $dbn);
$this->dbus->query("Select * from mysql.db where Db= ? and User!= ? ;", array($dbn, $cuid."_myadm")); $this->dbus->query("Select * from mysql.db where Db= ? and User!= ? ;", array($dbn, $cuid."_myadm"));
if (!$this->dbus->num_rows()) { if (!$this->dbus->num_rows()) {
@ -645,7 +638,6 @@ class m_mysql {
return $r; return $r;
} }
/* ------------------------------------------------------------ */
/** /**
* Create a new user in MySQL rights tables * Create a new user in MySQL rights tables
@ -653,7 +645,7 @@ class m_mysql {
* @param string $password The password for this username * @param string $password The password for this username
* @param string $passconf The password confirmation * @param string $passconf The password confirmation
* @return boolean if the user has been created in MySQL or FALSE if an error occurred * @return boolean if the user has been created in MySQL or FALSE if an error occurred
* */ */
function add_user($usern, $password, $passconf) { function add_user($usern, $password, $passconf) {
global $db, $msg, $mem, $cuid, $admin; global $db, $msg, $mem, $cuid, $admin;
$msg->log("mysql", "add_user", $usern); $msg->log("mysql", "add_user", $usern);
@ -708,7 +700,6 @@ class m_mysql {
return true; return true;
} }
/* ------------------------------------------------------------ */
/** /**
* Change a user's MySQL password * Change a user's MySQL password
@ -716,7 +707,7 @@ class m_mysql {
* @param $password The password for this username * @param $password The password for this username
* @param $passconf The password confirmation * @param $passconf The password confirmation
* @return boolean if the password has been changed in MySQL or FALSE if an error occurred * @return boolean if the password has been changed in MySQL or FALSE if an error occurred
* */ */
function change_user_password($usern, $password, $passconf) { function change_user_password($usern, $password, $passconf) {
global $db, $msg, $cuid, $admin; global $db, $msg, $cuid, $admin;
$msg->log("mysql", "change_user_pass", $usern); $msg->log("mysql", "change_user_pass", $usern);
@ -738,14 +729,13 @@ class m_mysql {
return true; return true;
} }
/* ------------------------------------------------------------ */
/** /**
* Delete a user in MySQL rights tables * Delete a user in MySQL rights tables
* @param $user the username (we will add "[alternc-account]_" to it) to delete * @param $user the username (we will add "[alternc-account]_" to it) to delete
* @param integer $all * @param integer $all
* @return boolean if the user has been deleted in MySQL or FALSE if an error occurred * @return boolean if the user has been deleted in MySQL or FALSE if an error occurred
* */ */
function del_user($user, $all = false, $caller_is_deldb = false) { function del_user($user, $all = false, $caller_is_deldb = false) {
global $db, $msg, $cuid; global $db, $msg, $cuid;
$msg->log("mysql", "del_user", $user); $msg->log("mysql", "del_user", $user);
@ -760,10 +750,10 @@ class m_mysql {
} }
if (!$db->num_rows()) { if (!$db->num_rows()) {
if (! $caller_is_deldb ) if (! $caller_is_deldb )
$msg->raise("ERROR", "mysql", _("The username was not found")); $msg->raise("ERROR", "mysql", _("The username was not found"));
return false; return false;
} }
$db->next_record(); $db->next_record();
$login = $db->f("name"); $login = $db->f("name");
@ -782,13 +772,12 @@ class m_mysql {
return true; return true;
} }
/* ------------------------------------------------------------ */
/** /**
* Return the list of the database rights of user $user * Return the list of the database rights of user $user
* @param $user the username * @param $user the username
* @return array An array of database name and rights * @return array An array of database name and rights
* */ */
function get_user_dblist($user) { function get_user_dblist($user) {
global $db, $msg; global $db, $msg;
@ -801,18 +790,18 @@ class m_mysql {
$r = array(); $r = array();
$db->free(); $db->free();
$dblist = $this->get_dblist(); $dblist = $this->get_dblist();
foreach ($dblist as $tab) { foreach ($dblist as $tab) {
$dbname = str_replace('_', '\_', $tab["db"]); $dbname = str_replace('_', '\_', $tab["db"]);
$this->dbus->query("SELECT * FROM mysql.db WHERE User= ? AND Host= ? AND Db= ? ;", array($user, $this->dbus->Client, $dbname)); $this->dbus->query("SELECT * FROM mysql.db WHERE User= ? AND Host= ? AND Db= ? ;", array($user, $this->dbus->Client, $dbname));
if ($this->dbus->next_record()) { if ($this->dbus->next_record()) {
$r[] = array("db" => $tab["db"], "select" => $this->dbus->f("Select_priv"), "insert" => $this->dbus->f("Insert_priv"), "update" => $this->dbus->f("Update_priv"), "delete" => $this->dbus->f("Delete_priv"), "create" => $this->dbus->f("Create_priv"), "drop" => $this->dbus->f("Drop_priv"), "references" => $this->dbus->f("References_priv"), "index" => $this->dbus->f("Index_priv"), "alter" => $this->dbus->f("Alter_priv"), "create_tmp" => $this->dbus->f("Create_tmp_table_priv"), "lock" => $this->dbus->f("Lock_tables_priv"), $r[] = array("db" => $tab["db"], "select" => $this->dbus->f("Select_priv"), "insert" => $this->dbus->f("Insert_priv"), "update" => $this->dbus->f("Update_priv"), "delete" => $this->dbus->f("Delete_priv"), "create" => $this->dbus->f("Create_priv"), "drop" => $this->dbus->f("Drop_priv"), "references" => $this->dbus->f("References_priv"), "index" => $this->dbus->f("Index_priv"), "alter" => $this->dbus->f("Alter_priv"), "create_tmp" => $this->dbus->f("Create_tmp_table_priv"), "lock" => $this->dbus->f("Lock_tables_priv"),
"create_view" => $this->dbus->f("Create_view_priv"), "create_view" => $this->dbus->f("Create_view_priv"),
"show_view" => $this->dbus->f("Show_view_priv"), "show_view" => $this->dbus->f("Show_view_priv"),
"create_routine" => $this->dbus->f("Create_routine_priv"), "create_routine" => $this->dbus->f("Create_routine_priv"),
"alter_routine" => $this->dbus->f("Alter_routine_priv"), "alter_routine" => $this->dbus->f("Alter_routine_priv"),
"execute" => $this->dbus->f("Execute_priv"), "execute" => $this->dbus->f("Execute_priv"),
"event" => $this->dbus->f("Event_priv"), "event" => $this->dbus->f("Event_priv"),
"trigger" => $this->dbus->f("Trigger_priv") "trigger" => $this->dbus->f("Trigger_priv")
); );
} else { } else {
$r[] = array("db" => $tab['db'], "select" => "N", "insert" => "N", "update" => "N", "delete" => "N", "create" => "N", "drop" => "N", "references" => "N", "index" => "N", "alter" => "N", "create_tmp" => "N", "lock" => "N", "create_view" => "N", "show_view" => "N", "create_routine" => "N", "alter_routine" => "N", "execute" => "N", "event" => "N", "trigger" => "N"); $r[] = array("db" => $tab['db'], "select" => "N", "insert" => "N", "update" => "N", "delete" => "N", "create" => "N", "drop" => "N", "references" => "N", "index" => "N", "alter" => "N", "create_tmp" => "N", "lock" => "N", "create_view" => "N", "show_view" => "N", "create_routine" => "N", "alter_routine" => "N", "execute" => "N", "event" => "N", "trigger" => "N");
@ -821,7 +810,6 @@ class m_mysql {
return $r; return $r;
} }
/* ------------------------------------------------------------ */
/** /**
* Set the access rights of user $user to database $dbn to be rights $rights * Set the access rights of user $user to database $dbn to be rights $rights
@ -829,75 +817,74 @@ class m_mysql {
* @param $dbn The database to give rights to * @param $dbn The database to give rights to
* @param $rights The rights as an array of MySQL keywords (insert, select ...) * @param $rights The rights as an array of MySQL keywords (insert, select ...)
* @return boolean TRUE if the rights has been applied or FALSE if an error occurred * @return boolean TRUE if the rights has been applied or FALSE if an error occurred
* */
* */
function set_user_rights($user, $dbn, $rights) { function set_user_rights($user, $dbn, $rights) {
global $msg; global $msg;
$msg->log("mysql", "set_user_rights"); $msg->log("mysql", "set_user_rights");
// On genere les droits en fonction du tableau de droits // We generate the rights array depending on the rights list:
$strrights = ""; $strrights = "";
for ($i = 0; $i < count($rights); $i++) { for ($i = 0; $i < count($rights); $i++) {
switch ($rights[$i]) { switch ($rights[$i]) {
case "select": case "select":
$strrights.="SELECT,"; $strrights.="SELECT,";
break; break;
case "insert": case "insert":
$strrights.="INSERT,"; $strrights.="INSERT,";
break; break;
case "update": case "update":
$strrights.="UPDATE,"; $strrights.="UPDATE,";
break; break;
case "delete": case "delete":
$strrights.="DELETE,"; $strrights.="DELETE,";
break; break;
case "create": case "create":
$strrights.="CREATE,"; $strrights.="CREATE,";
break; break;
case "drop": case "drop":
$strrights.="DROP,"; $strrights.="DROP,";
break; break;
case "references": case "references":
$strrights.="REFERENCES,"; $strrights.="REFERENCES,";
break; break;
case "index": case "index":
$strrights.="INDEX,"; $strrights.="INDEX,";
break; break;
case "alter": case "alter":
$strrights.="ALTER,"; $strrights.="ALTER,";
break; break;
case "create_tmp": case "create_tmp":
$strrights.="CREATE TEMPORARY TABLES,"; $strrights.="CREATE TEMPORARY TABLES,";
break; break;
case "lock": case "lock":
$strrights.="LOCK TABLES,"; $strrights.="LOCK TABLES,";
break; break;
case "create_view": case "create_view":
$strrights.="CREATE VIEW,"; $strrights.="CREATE VIEW,";
break; break;
case "show_view": case "show_view":
$strrights.="SHOW VIEW,"; $strrights.="SHOW VIEW,";
break; break;
case "create_routine": case "create_routine":
$strrights.="CREATE ROUTINE,"; $strrights.="CREATE ROUTINE,";
break; break;
case "alter_routine": case "alter_routine":
$strrights.="ALTER ROUTINE,"; $strrights.="ALTER ROUTINE,";
break; break;
case "execute": case "execute":
$strrights.="EXECUTE,"; $strrights.="EXECUTE,";
break; break;
case "event": case "event":
$strrights.="EVENT,"; $strrights.="EVENT,";
break; break;
case "trigger": case "trigger":
$strrights.="TRIGGER,"; $strrights.="TRIGGER,";
break; break;
} }
} }
// We reset all user rights on this DB : // We reset all user rights on this DB :
$dbname = str_replace('_', '\_', $dbn); $dbname = str_replace('_', '\_', $dbn);
$this->dbus->query("SELECT * FROM mysql.db WHERE User = ? AND Db = ?;", array($user, $dbname)); $this->dbus->query("SELECT * FROM mysql.db WHERE User = ? AND Db = ?;", array($user, $dbname));
if ($this->dbus->num_rows()) { if ($this->dbus->num_rows()) {
@ -911,13 +898,16 @@ class m_mysql {
return TRUE; return TRUE;
} }
/**
* list of all possible SQL rights
*/
function available_sql_rights() { function available_sql_rights() {
return Array('select', 'insert', 'update', 'delete', 'create', 'drop', 'references', 'index', 'alter', 'create_tmp', 'lock', 'create_view', 'show_view', 'create_routine', 'alter_routine', 'execute', 'event', 'trigger'); return Array('select', 'insert', 'update', 'delete', 'create', 'drop', 'references', 'index', 'alter', 'create_tmp', 'lock', 'create_view', 'show_view', 'create_routine', 'alter_routine', 'execute', 'event', 'trigger');
} }
/* ----------------------------------------------------------------- */
/** Hook function called by the lxc class to set mysql_host and port /**
* Hook function called by the lxc class to set mysql_host and port
* parameters * parameters
* @access private * @access private
*/ */
@ -932,9 +922,9 @@ class m_mysql {
return $p; return $p;
} }
/* ----------------------------------------------------------------- */
/** Hook function called by the quota class to compute user used quota /**
* Hook function called by the quota class to compute user used quota
* Returns the used quota for the $name service for the current user. * Returns the used quota for the $name service for the current user.
* @param $name string name of the quota * @param $name string name of the quota
* @return integer the number of service used or false if an error occured * @return integer the number of service used or false if an error occured
@ -952,16 +942,16 @@ class m_mysql {
return $q; return $q;
} }
/* ----------------------------------------------------------------- */
/** Hook function called when a user is created. /**
* Hook function called when a user is created.
* AlternC's standard function that create a member * AlternC's standard function that create a member
* @access private * @access private
*/ */
function alternc_add_member() { function alternc_add_member() {
global $db, $msg, $cuid, $mem; global $db, $msg, $cuid, $mem;
$msg->log("mysql", "alternc_add_member"); $msg->log("mysql", "alternc_add_member");
//checking for the phpmyadmin user // checking for the phpmyadmin user
$db->query("SELECT name,password FROM dbusers WHERE uid= ? AND Type='ADMIN';", array($cuid)); $db->query("SELECT name,password FROM dbusers WHERE uid= ? AND Type='ADMIN';", array($cuid));
if ($db->num_rows()) { if ($db->num_rows()) {
$myadm = $db->f("name"); $myadm = $db->f("name");
@ -976,9 +966,9 @@ class m_mysql {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Hook function called when a user is deleted. /**
* Hook function called when a user is deleted.
* AlternC's standard function that delete a member * AlternC's standard function that delete a member
* @access private * @access private
*/ */
@ -1000,27 +990,26 @@ class m_mysql {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Hook function called when a user is logged out. /**
* Hook function called when a user is logged out.
* We just remove the cookie created in admin/sql_admin.php * We just remove the cookie created in admin/sql_admin.php
a @access private * a @access private
*/ */
function alternc_del_session() { function alternc_del_session() {
$_SESSION['PMA_single_signon_user'] = ''; $_SESSION['PMA_single_signon_user'] = '';
$_SESSION['PMA_single_signon_password'] = ''; $_SESSION['PMA_single_signon_password'] = '';
$_SESSION['PMA_single_signon_host'] = ''; $_SESSION['PMA_single_signon_host'] = '';
} }
/* ----------------------------------------------------------------- */
/** /**
* Exporte all the mysql information of an account * Exports all the mysql information of an account
* @access private * @access private
* EXPERIMENTAL 'sid' function ;) * EXPERIMENTAL 'sid' function ;)
*/ */
function alternc_export_conf() { function alternc_export_conf() {
//TODO don't work with separated sql server for dbusers // TODO don't work with separated sql server for dbusers
global $db, $msg, $cuid; global $db, $msg, $cuid;
$msg->log("mysql", "export"); $msg->log("mysql", "export");
$db->query("SELECT login, pass, db, bck_mode, bck_dir, bck_history, bck_gzip FROM db WHERE uid= ? ;", array($cuid)); $db->query("SELECT login, pass, db, bck_mode, bck_dir, bck_history, bck_gzip FROM db WHERE uid= ? ;", array($cuid));
@ -1045,10 +1034,9 @@ class m_mysql {
return $str; return $str;
} }
/* ----------------------------------------------------------------- */
/** /**
* Exporte all the mysql databases a of give account to $dir directory * Exports all the mysql databases a of give account to $dir directory
* @access private * @access private
* EXPERIMENTAL 'sid' function ;) * EXPERIMENTAL 'sid' function ;)
*/ */
@ -1069,7 +1057,6 @@ class m_mysql {
} }
} }
/* ----------------------------------------------------------------- */
/** /**
* Return the size of each databases in a SQL Host given in parameter * Return the size of each databases in a SQL Host given in parameter
@ -1084,26 +1071,24 @@ class m_mysql {
global $msg; global $msg;
$msg->log("mysql", "get_dbus_size", $db_host); $msg->log("mysql", "get_dbus_size", $db_host);
$this->dbus = new DB_Sql("mysql",$db_host,$db_login,$db_password); $this->dbus = new DB_Sql("mysql",$db_host,$db_login,$db_password);
$this->dbus->query("SHOW DATABASES;"); $this->dbus->query("SHOW DATABASES;");
$alldb=array(); $alldb=array();
while ($this->dbus->next_record()) { while ($this->dbus->next_record()) {
$alldb[] = $this->dbus->f("Database"); $alldb[] = $this->dbus->f("Database");
} }
$res = array(); $res = array();
foreach($alldb as $dbname) { foreach($alldb as $dbname) {
$c = $this->dbus->query("SHOW TABLE STATUS FROM $dbname;"); $c = $this->dbus->query("SHOW TABLE STATUS FROM $dbname;");
$size = 0; $size = 0;
while ($this->dbus->next_record()) { while ($this->dbus->next_record()) {
$size+=$this->dbus->f("Data_length") + $this->dbus->f("Index_length"); $size+=$this->dbus->f("Data_length") + $this->dbus->f("Index_length");
} }
$res["$dbname"] = "$size"; $res["$dbname"] = "$size";
} }
return $res; return $res;
} }
} } /* Class m_mysql */
/* Class m_mysql */

View File

@ -1,9 +1,6 @@
<?php <?php
/* /*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
@ -19,493 +16,502 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Purpose of file: Manage piwik Statistics set
----------------------------------------------------------------------
*/ */
/** /**
* This class manage piwik statistics management through AlternC, using piwik's "API". * This class manage piwik statistics management through AlternC, using piwik's "API".
*/ */
class m_piwik { class m_piwik {
var $piwik_server_uri; var $piwik_server_uri;
var $piwik_admin_token; var $piwik_admin_token;
var $alternc_users; var $alternc_users;
var $alternc_sites; var $alternc_sites;
function hook_menu() { function hook_menu() {
global $quota; global $quota;
if ( empty($this->piwik_server_uri) || empty($this->piwik_admin_token)) return false; if ( empty($this->piwik_server_uri) || empty($this->piwik_admin_token)) return false;
$obj = array( $obj = array(
'title' => _("Piwik statistics"), 'title' => _("Piwik statistics"),
'ico' => 'images/piwik.png', 'ico' => 'images/piwik.png',
'link' => 'toggle', 'link' => 'toggle',
'pos' => 115, 'pos' => 115,
'links' => array( 'links' => array(
array( 'txt' => _("Piwik Users"), 'url' => 'piwik_userlist.php'), array( 'txt' => _("Piwik Users"), 'url' => 'piwik_userlist.php'),
array( 'txt' => _("Piwik Sites"), 'url' => 'piwik_sitelist.php'), array( 'txt' => _("Piwik Sites"), 'url' => 'piwik_sitelist.php'),
), ),
) ; ) ;
return $obj; return $obj;
}
/*---------------------------------------------------------------------------*/
/** Constructor
*/
function m_piwik() {
$this->piwik_server_uri=variable_get('piwik_server_uri',null,'Remote Piwik server uri');
$this->piwik_admin_token=variable_get('piwik_admin_token',null,'Remote Piwik super-admin token');
$this->alternc_users = $this->get_alternc_users();
$this->alternc_sites = $this->get_alternc_sites();
}
/* ----------------------------------------------------------------- */
/** hook called when an AlternC account is deleted
*/
function hook_admin_del_member() {
//FIXME : implement the hook_admin_del_member for piwik
return true;
}
/* ----------------------------------------------------------------- */
/** Returns the used quota for the $name service for the current user.
* @param $name string name of the quota
* @return integer the number of service used or false if an error occured
* @access private
*/
function hook_quota_get() {
global $db, $cuid;
$db->query("SELECT COUNT(id) AS nb FROM piwik_sites WHERE uid= ? ;", array($cuid));
$q=Array("name"=>"piwik", "description"=>_("Statistics through Piwik accounts"), "used"=>0);
if ($db->next_record()) {
$q['used']=$db->f('nb');
} }
return $q;
}
function url() { /**
return $this->piwik_server_uri; * Constructor
} */
function m_piwik() {
$this->piwik_server_uri=variable_get('piwik_server_uri',null,'Remote Piwik server uri');
$this->piwik_admin_token=variable_get('piwik_admin_token',null,'Remote Piwik super-admin token');
$this->alternc_users = $this->get_alternc_users();
$this->alternc_sites = $this->get_alternc_sites();
}
/***********************/ /**
/* User-related tasks */ * hook called when an AlternC account is deleted
/***********************/ */
function hook_admin_del_member() {
//FIXME : implement the hook_admin_del_member for piwik
return true;
}
function user_add($user_login, $user_mail) { /**
* Returns the used quota for the $name service for the current user.
* @param $name string name of the quota
* @return integer the number of service used or false if an error occured
* @access private
*/
function hook_quota_get() {
global $db, $cuid;
$db->query("SELECT COUNT(id) AS nb FROM piwik_sites WHERE uid= ? ;", array($cuid));
$q=Array("name"=>"piwik", "description"=>_("Statistics through Piwik accounts"), "used"=>0);
if ($db->next_record()) {
$q['used']=$db->f('nb');
}
return $q;
}
function url() {
return $this->piwik_server_uri;
}
/***********************/
/* User-related tasks */
/***********************/
function user_add($user_login, $user_mail) {
global $db, $mem, $cuid, $msg; global $db, $mem, $cuid, $msg;
$msg->log("piwik","user_add"); $msg->log("piwik","user_add");
if (empty($user_login) || is_null($user_login) || empty($user_mail) || is_null($user_mail)) { if (empty($user_login) || is_null($user_login) || empty($user_mail) || is_null($user_mail)) {
$msg->raise("ERROR", "piwik", _("All fields are mandatory")); $msg->raise("ERROR", "piwik", _("All fields are mandatory"));
return false; return false;
} }
// Validate the email syntax: // Validate the email syntax:
if (!filter_var($user_mail, FILTER_VALIDATE_EMAIL)) { if (!filter_var($user_mail, FILTER_VALIDATE_EMAIL)) {
$msg->raise("ERROR", "piwik", _("The email you entered is syntaxically incorrect")); $msg->raise("ERROR", "piwik", _("The email you entered is syntaxically incorrect"));
return false; return false;
} }
$user_login = $this->clean_user_name($user_login); $user_login = $this->clean_user_name($user_login);
$user_pass = create_pass(); $user_pass = create_pass();
$user_alias = $user_login; $user_alias = $user_login;
$api_data = $this->call_privileged_page('API', 'UsersManager.addUser', array('userLogin' => $user_login, 'password' => $user_pass, 'email' => $user_mail, 'alias' => $user_alias), 'JSON'); $api_data = $this->call_privileged_page('API', 'UsersManager.addUser', array('userLogin' => $user_login, 'password' => $user_pass, 'email' => $user_mail, 'alias' => $user_alias), 'JSON');
if ($api_data) { if ($api_data) {
if ($api_data->result === 'success') { if ($api_data->result === 'success') {
$user = $this->get_user($user_login); $user = $this->get_user($user_login);
$user_creation_date = $user->date_registered; $user_creation_date = $user->date_registered;
$ret_value = $db->query("INSERT INTO piwik_users (uid, passwd, login, created_date) VALUES ( ?, ?, ?, ?);", array($cuid, md5('$user_pass'), $user_login, $user_creation_date)); $ret_value = $db->query("INSERT INTO piwik_users (uid, passwd, login, created_date) VALUES ( ?, ?, ?, ?);", array($cuid, md5('$user_pass'), $user_login, $user_creation_date));
return $ret_value; return $ret_value;
} else { } else {
$msg->raise("ERROR", "piwik", $api_data->message); $msg->raise("ERROR", "piwik", $api_data->message);
return FALSE; return FALSE;
} }
} else { // api_data = false -> error is already filled } else { // api_data = false -> error is already filled
return FALSE; return FALSE;
} }
}
// Edite un user
function user_edit() {
//FIXME
return true;
}
function get_site_access($user_login) {
return $this->call_privileged_page('API', 'UsersManager.getSitesAccessFromUser', array('userLogin' => $user_login));
}
function get_users_access_from_site($site_id) {
global $msg, $cuid;
$msg->log("piwik","get_users_access_from_site");
if (!is_numeric($site_id)) {
$msg->raise("ERROR", 'piwik', 'site_id must be numeric');
return FALSE;
}
if (!in_array($site_id, $this->alternc_sites)) {
$msg->raise("ERROR", 'piwik', "you don't own this piwik website");
return FALSE;
}
$api_data = $this->call_privileged_page('API', 'UsersManager.getUsersAccessFromSite', array('idSite' => $site_id));
if ($api_data !== FALSE) {
$api_data = $api_data[0]; // Data is in the first column
foreach ($this->alternc_users AS $key=>$user) {
if (!array_key_exists($user, $api_data)) {
$api_data->$user = 'noaccess';
}
}
return $api_data;
}
else return FALSE;
}
/**
* @param string $user_login
*/
function get_user($user_login) {
$api_data = $this->call_privileged_page('API', 'UsersManager.getUser', array('userLogin' => $user_login));
if ($api_data)
return $api_data[0];
else
return FALSE;
}
function get_alternc_users() {
global $db, $cuid, $msg;
$msg->log("piwik","get_alternc_users");
static $alternc_users = array();
$db->query("SELECT login FROM piwik_users WHERE uid= ?;", array($cuid));
while ($db->next_record())
array_push($alternc_users, $db->f('login'));
return $alternc_users;
}
function get_users_url_infos() {
global $db,$cuid, $msg;
$infos_user = array();
$api_calls = array();
$db->query("SELECT login, passwd, s.piwik_id as id FROM piwik_users as u INNER JOIN piwik_sites as s on u.uid = s.uid WHERE u.uid = $cuid");
while ($db->next_record()) {
$id = $db->f('id');
$login = $db->f('login');
if (!isset($infos_user[$id]))
$infos_user[$id] = array();
if (!isset($api_calls[$id]))
$api_calls[$id] = $this->get_users_access_from_site($id);
foreach ($api_calls[$id] as $l => $cred) {
if ($l == $login)
$infos_user[$id][] = array('login' => $login, 'password' => $db->f('passwd'), 'cred' => $cred);
}
} }
return $infos_user;
}
/** /**
* does this user has piwik websites configured in AlternC ? * Change a user @TODO: code this
*/ */
function user_has_sites() { function user_edit() {
global $db, $cuid, $msg;
$msg->log("piwik","user_has_sites");
$db->query("SELECT id FROM piwik_users WHERE uid='$cuid'");
if ($db->num_rows() <= 1) {
$db->query("SELECT id FROM piwik_sites WHERE uid='$cuid'");
if ($db->num_rows() > 0)
return true; return true;
} }
return false; function get_site_access($user_login) {
} return $this->call_privileged_page('API', 'UsersManager.getSitesAccessFromUser', array('userLogin' => $user_login));
/** Delete a piwik user
* don't delete it locally unless it has been remotely deleted.
*/
function user_delete($piwik_user_login) {
global $db, $cuid, $msg;
$msg->log("piwik","user_delete");
$db->query("SELECT created_date, COUNT(id) AS cnt FROM piwik_users WHERE uid= ? AND login= ? ", array($cuid, $piwik_user_login));
$db->next_record();
if ($db->f('cnt') == 1) {
$api_data = $this->call_privileged_page('API', 'UsersManager.deleteUser', array('userLogin' => $piwik_user_login));
if ($api_data->result == 'success') {
return $db->query("DELETE FROM piwik_users WHERE uid= ? AND login= ? ;", array($cuid, $piwik_user_login));
}
else {
return FALSE;
}
} else {
$msg->raise("ERROR", "piwik", _("You are not allowed to delete the statistics of this website"));
return FALSE;
} }
}
function users_list() { function get_users_access_from_site($site_id) {
global $db, $cuid, $msg; global $msg, $cuid;
$msg->log("piwik","users_list"); $msg->log("piwik","get_users_access_from_site");
$db->query("SELECT login FROM piwik_users WHERE uid = ?;", array($cuid)); if (!is_numeric($site_id)) {
if ($db->num_rows() == 0) $msg->raise("ERROR", 'piwik', 'site_id must be numeric');
return array(); return FALSE;
$users = ''; }
while ($db->next_record()) if (!in_array($site_id, $this->alternc_sites)) {
$users .= ($users !== '') ? ',' . $db->f('login') : $db->f('login'); $msg->raise("ERROR", 'piwik', "you don't own this piwik website");
return $this->call_privileged_page('API', 'UsersManager.getUsers', array('userLogins' => $users)); return FALSE;
} }
$api_data = $this->call_privileged_page('API', 'UsersManager.getUsersAccessFromSite', array('idSite' => $site_id));
if ($api_data !== FALSE) {
$api_data = $api_data[0]; // Data is in the first column
foreach ($this->alternc_users AS $key=>$user) {
if (!array_key_exists($user, $api_data)) {
$api_data->$user = 'noaccess';
}
}
return $api_data;
}
else return FALSE;
}
// Verifie que l'utilisateur existe bien dans piwik /**
function user_checkremote($puser_id) { * @param string $user_login
//FIXME */
return true; function get_user($user_login) {
} $api_data = $this->call_privileged_page('API', 'UsersManager.getUser', array('userLogin' => $user_login));
if ($api_data)
return $api_data[0];
else
return FALSE;
}
// Récupére un token pour le SSO avec piwik pour l'user function get_alternc_users() {
function user_remoteauth() {
//FIXME
return true;
}
// Montre la liste des site pour lesques un user à accés
function user_access() {
// FIXME
return true;
}
/***********************/
/* Site-related tasks */
/***********************/
function site_list() {
global $msg;
$msg->log("piwik","site_list");
$api_data = $this->call_privileged_page('API', 'SitesManager.getAllSites');
$data = array();
if($api_data) {
foreach ($api_data AS $site) {
if (!in_array($site->idsite, $this->alternc_sites))
continue;
$item = new stdClass();
$item->id = $site->idsite;
$item->name = $site->name;
$item->main_url = $site->main_url;
$user_data = $this->call_privileged_page('API', 'UsersManager.getUsersAccessFromSite', array('idSite' => $site->idsite));
//if (is_array($user_data)) {
// printvar($user_data);
//} else if(is_object($user_data)) {
$item->rights = $user_data[0];
//}
$data[] = $item;
}
return $data;
} else
return FALSE;
}
function site_js_tag($site_id) {
return $this->call_privileged_page('API', 'SitesManager.getJavascriptTag', array('idSite' => $site_id, 'piwikUrl' => $this->piwik_server_uri))->value;
}
function get_alternc_sites() {
global $db, $cuid, $msg; global $db, $cuid, $msg;
$msg->log("piwik","get_alternc_sites"); $msg->log("piwik","get_alternc_users");
static $alternc_users = array();
$db->query("SELECT login FROM piwik_users WHERE uid= ?;", array($cuid));
while ($db->next_record())
array_push($alternc_users, $db->f('login'));
return $alternc_users;
}
function get_users_url_infos() {
global $db,$cuid, $msg;
$infos_user = array();
$api_calls = array();
$db->query("SELECT login, passwd, s.piwik_id as id FROM piwik_users as u INNER JOIN piwik_sites as s on u.uid = s.uid WHERE u.uid = $cuid");
while ($db->next_record()) {
$id = $db->f('id');
$login = $db->f('login');
if (!isset($infos_user[$id]))
$infos_user[$id] = array();
if (!isset($api_calls[$id]))
$api_calls[$id] = $this->get_users_access_from_site($id);
foreach ($api_calls[$id] as $l => $cred) {
if ($l == $login)
$infos_user[$id][] = array('login' => $login, 'password' => $db->f('passwd'), 'cred' => $cred);
}
}
return $infos_user;
}
/**
* does this user has piwik websites configured in AlternC ?
*/
function user_has_sites() {
global $db, $cuid, $msg;
$msg->log("piwik","user_has_sites");
$db->query("SELECT id FROM piwik_users WHERE uid='$cuid'");
if ($db->num_rows() <= 1) {
$db->query("SELECT id FROM piwik_sites WHERE uid='$cuid'");
if ($db->num_rows() > 0)
return true;
}
return false;
}
/**
* Delete a piwik user
* don't delete it locally unless it has been remotely deleted.
*/
function user_delete($piwik_user_login) {
global $db, $cuid, $msg;
$msg->log("piwik","user_delete");
$db->query("SELECT created_date, COUNT(id) AS cnt FROM piwik_users WHERE uid= ? AND login= ? ", array($cuid, $piwik_user_login));
$db->next_record();
if ($db->f('cnt') == 1) {
$api_data = $this->call_privileged_page('API', 'UsersManager.deleteUser', array('userLogin' => $piwik_user_login));
if ($api_data->result == 'success') {
return $db->query("DELETE FROM piwik_users WHERE uid= ? AND login= ? ;", array($cuid, $piwik_user_login));
}
else {
return FALSE;
}
} else {
$msg->raise("ERROR", "piwik", _("You are not allowed to delete the statistics of this website"));
return FALSE;
}
}
function users_list() {
global $db, $cuid, $msg;
$msg->log("piwik","users_list");
$db->query("SELECT login FROM piwik_users WHERE uid = ?;", array($cuid));
if ($db->num_rows() == 0)
return array();
$users = '';
while ($db->next_record())
$users .= ($users !== '') ? ',' . $db->f('login') : $db->f('login');
return $this->call_privileged_page('API', 'UsersManager.getUsers', array('userLogins' => $users));
}
// Verifie que l'utilisateur existe bien dans piwik
function user_checkremote($puser_id) {
//FIXME
return true;
}
// Récupére un token pour le SSO avec piwik pour l'user
function user_remoteauth() {
//FIXME
return true;
}
// Montre la liste des site pour lesques un user à accés
function user_access() {
// FIXME
return true;
}
/***********************/
/* Site-related tasks */
/***********************/
function site_list() {
global $msg;
$msg->log("piwik","site_list");
$api_data = $this->call_privileged_page('API', 'SitesManager.getAllSites');
$data = array();
if($api_data) {
foreach ($api_data AS $site) {
if (!in_array($site->idsite, $this->alternc_sites))
continue;
$item = new stdClass();
$item->id = $site->idsite;
$item->name = $site->name;
$item->main_url = $site->main_url;
$user_data = $this->call_privileged_page('API', 'UsersManager.getUsersAccessFromSite', array('idSite' => $site->idsite));
//if (is_array($user_data)) {
// printvar($user_data);
//} else if(is_object($user_data)) {
$item->rights = $user_data[0];
//}
$data[] = $item;
}
return $data;
} else
return FALSE;
}
function site_js_tag($site_id) {
return $this->call_privileged_page('API', 'SitesManager.getJavascriptTag', array('idSite' => $site_id, 'piwikUrl' => $this->piwik_server_uri))->value;
}
function get_alternc_sites() {
global $db, $cuid, $msg;
$msg->log("piwik","get_alternc_sites");
static $alternc_sites = array(); static $alternc_sites = array();
$db->query("SELECT piwik_id AS site_id FROM piwik_sites WHERE uid= ? ;", array($cuid)); $db->query("SELECT piwik_id AS site_id FROM piwik_sites WHERE uid= ? ;", array($cuid));
while ($db->next_record()) while ($db->next_record())
array_push($alternc_sites, $db->f('site_id')); array_push($alternc_sites, $db->f('site_id'));
return $alternc_sites; return $alternc_sites;
}
function get_site_list()
{
return $this->call_privileged_page('API', 'SitesManager.getAllSites');
}
// Ajoute un site à Piwik
// can't figure out how to pass multiple url through the API
function site_add($siteName, $urls, $ecommerce = FALSE) {
global $db, $cuid, $piwik, $msg;
$msg->log("piwik","site_add");
$urls = is_array($urls) ? implode(',', $urls) : $urls;
$api_data = $this->call_privileged_page('API', 'SitesManager.addSite', array('siteName' => $siteName, 'urls' => $urls));
if ($api_data->value) {
$id_site = $api_data->value;
// Ajout de donner auto les droits de lecture à ce nouvel utilisateur pour le site qu'il a ajouté
$userslist = $piwik->users_list();
$api_data = $this->call_privileged_page('API', 'UsersManager.setUserAccess', array('userLogin' => $userslist[0]->login, 'idSites' => $id_site, 'access' => 'view'));
if ($api_data->result == 'success') {
// On enregistre le site dans alternC
$db->query("INSERT INTO piwik_sites set uid= ? , piwik_id= ? ", array($cuid, $id_site));
// Permet de prendre en compte le site qu'on vient de créer dans la page quis'affiche
$this->alternc_sites = $this->get_alternc_sites();
return TRUE;
}
return TRUE;
} else
return FALSE;
}
//SitesManager.deleteSite (idSite)
// Supprime un site de Piwik
function site_delete($site_id) {
global $db, $cuid, $msg;
$msg->log("piwik","site_delete");
$db->query("SELECT COUNT(id) AS cnt FROM piwik_sites WHERE uid= ? AND piwik_id= ? ;", array($cuid, $site_id));
$db->next_record();
if ($db->f('cnt') == 1) {
$api_data = $this->call_privileged_page('API', 'SitesManager.deleteSite', array('idSite' => $site_id));
if ($api_data->result == 'success') {
return $db->query("DELETE FROM piwik_sites where uid= ? AND piwik_id= ? LIMIT 1", array($cuid, $site_id));
} else {
return FALSE;
}
} else {
$msg->raise("ERROR", "piwik", _("You are not allowed to delete the statistics of this website"));
return FALSE;
} }
return true;
} function get_site_list()
{
return $this->call_privileged_page('API', 'SitesManager.getAllSites');
}
// Ajoute un site à Piwik
// can't figure out how to pass multiple url through the API
function site_add($siteName, $urls, $ecommerce = FALSE) {
global $db, $cuid, $piwik, $msg;
$msg->log("piwik","site_add");
$urls = is_array($urls) ? implode(',', $urls) : $urls;
$api_data = $this->call_privileged_page('API', 'SitesManager.addSite', array('siteName' => $siteName, 'urls' => $urls));
if ($api_data->value) {
$id_site = $api_data->value;
// Ajout de donner auto les droits de lecture à ce nouvel utilisateur pour le site qu'il a ajouté
$userslist = $piwik->users_list();
$api_data = $this->call_privileged_page('API', 'UsersManager.setUserAccess', array('userLogin' => $userslist[0]->login, 'idSites' => $id_site, 'access' => 'view'));
if ($api_data->result == 'success') {
// On enregistre le site dans alternC
$db->query("INSERT INTO piwik_sites set uid= ? , piwik_id= ? ", array($cuid, $id_site));
// Permet de prendre en compte le site qu'on vient de créer dans la page quis'affiche
$this->alternc_sites = $this->get_alternc_sites();
return TRUE;
}
return TRUE;
} else
return FALSE;
}
//SitesManager.deleteSite (idSite)
// Supprime un site de Piwik
function site_delete($site_id) {
global $db, $cuid, $msg;
$msg->log("piwik","site_delete");
$db->query("SELECT COUNT(id) AS cnt FROM piwik_sites WHERE uid= ? AND piwik_id= ? ;", array($cuid, $site_id));
$db->next_record();
if ($db->f('cnt') == 1) {
$api_data = $this->call_privileged_page('API', 'SitesManager.deleteSite', array('idSite' => $site_id));
if ($api_data->result == 'success') {
return $db->query("DELETE FROM piwik_sites where uid= ? AND piwik_id= ? LIMIT 1", array($cuid, $site_id));
} else {
return FALSE;
}
} else {
$msg->raise("ERROR", "piwik", _("You are not allowed to delete the statistics of this website"));
return FALSE;
}
return true;
}
function site_set_user_right($site_id, $login, $right) function site_set_user_right($site_id, $login, $right)
{ {
global $msg; global $msg;
$msg->log("piwik","site_set_user_right"); $msg->log("piwik","site_set_user_right");
if (!in_array($right, array('noaccess', 'view', 'admin'))) if (!in_array($right, array('noaccess', 'view', 'admin')))
return FALSE; return FALSE;
$api_data = $this->call_privileged_page('API', 'UsersManager.setUserAccess', array('userLogin' => $login, 'access' => $right, 'idSites' => $site_id)); $api_data = $this->call_privileged_page('API', 'UsersManager.setUserAccess', array('userLogin' => $login, 'access' => $right, 'idSites' => $site_id));
if ($api_data->result == 'success') { if ($api_data->result == 'success') {
return TRUE; return TRUE;
} else { } else {
$msg->raise("ERROR", 'piwik', $api_data->messsage); $msg->raise("ERROR", 'piwik', $api_data->messsage);
return FALSE; return FALSE;
} }
} }
// Ajoute un alias sur un site existant
function site_alias_add() {
// FIXME
return true;
}
// Ajoute un alias sur un site existant
/* return a clean username with a unique prefix per account */ function site_alias_add() {
function clean_user_name($username) { // FIXME
global $admin, $cuid, $db; return true;
$escaped_name=$db->quote(trim($username)); }
$escaped_name=preg_replace("/^'(.*)'/", "\\1", $escaped_name);
return 'alternc_' . $admin->get_login_by_uid($cuid) . '_' . $escaped_name;
}
function dev() { /**
// $this->call_page('module', 'method', array('user' => 'fser', 'pass' => 'toto')); * return a clean username with a unique prefix per account
// return $this->users_list(); */
} function clean_user_name($username) {
global $admin, $cuid, $db;
$escaped_name=$db->quote(trim($username));
$escaped_name=preg_replace("/^'(.*)'/", "\\1", $escaped_name);
return 'alternc_' . $admin->get_login_by_uid($cuid) . '_' . $escaped_name;
}
/** function dev() {
* @param string $module // $this->call_page('module', 'method', array('user' => 'fser', 'pass' => 'toto'));
* @param string $method // return $this->users_list();
*/ }
function call_page($module, $method, $arguments=array(), $output = 'JSON') {
global $msg;
$msg->log("piwik","call_page");
$url = sprintf('%s/?module=%s&method=%s&format=%s', $this->piwik_server_uri, $module, $method, $output);
foreach ($arguments AS $k=>$v)
$url .= sprintf('&%s=%s', urlencode($k), $v); // urlencode($v));
$page_content = file_get_contents($url);
if ($page_content === FALSE) {
$msg->raise("ERROR", "piwik", _("Unable to reach the API"));
return FALSE;
}
if ($output == 'JSON') {
$api_data = json_decode($page_content);
if ($api_data === FALSE) {
$msg->raise("ERROR", "piwik", _("Error while decoding response from the API"));
return FALSE;
}
return $api_data;
} else {
$msg->raise("ERROR", "piwik", _("Other format than JSON is not implemented yet"));
return FALSE;
}
}
/** /**
* @param string $module * @param string $module
* @param string $method * @param string $method
*/ */
function call_privileged_page($module, $method, $arguments=array(), $output = 'JSON') { function call_page($module, $method, $arguments=array(), $output = 'JSON') {
global $msg; global $msg;
$msg->log("piwik","call_privileged_page"); $msg->log("piwik","call_page");
$arguments['token_auth'] = $this->piwik_admin_token; $url = sprintf('%s/?module=%s&method=%s&format=%s', $this->piwik_server_uri, $module, $method, $output);
return $this->call_page($module, $method, $arguments, $output); foreach ($arguments AS $k=>$v)
} $url .= sprintf('&%s=%s', urlencode($k), $v); // urlencode($v));
$page_content = file_get_contents($url);
if ($page_content === FALSE) {
$msg->raise("ERROR", "piwik", _("Unable to reach the API"));
return FALSE;
}
if ($output == 'JSON') {
$api_data = json_decode($page_content);
if ($api_data === FALSE) {
$msg->raise("ERROR", "piwik", _("Error while decoding response from the API"));
return FALSE;
}
return $api_data;
} else {
$msg->raise("ERROR", "piwik", _("Other format than JSON is not implemented yet"));
return FALSE;
}
}
/**
* @param string $module
* @param string $method
*/
function call_privileged_page($module, $method, $arguments=array(), $output = 'JSON') {
global $msg;
$msg->log("piwik","call_privileged_page");
$arguments['token_auth'] = $this->piwik_admin_token;
return $this->call_page($module, $method, $arguments, $output);
}
} /* Class piwik */ } /* Class piwik */

View File

@ -1,10 +1,6 @@
<?php <?php
/* /*
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2000-2012 by the AlternC Development Team.
https://alternc.org/
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
@ -20,9 +16,7 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Purpose of file: Manage user quota */
----------------------------------------------------------------------
*/
/** /**
* Class for hosting quotas management * Class for hosting quotas management
@ -44,7 +38,6 @@ class m_quota {
var $quotas; var $quotas;
var $clquota; // Which class manage which quota. var $clquota; // Which class manage which quota.
/* ----------------------------------------------------------------- */
/** /**
* Constructor * Constructor
@ -54,14 +47,16 @@ class m_quota {
if ($this->disk_quota_enable) { if ($this->disk_quota_enable) {
$this->disk = Array("web" => "web"); $this->disk = Array("web" => "web");
$this->disk_quota_not_blocking = variable_get('disk_quota_not_blocking', 1, "0 - Block data when quota are exceeded (you need a working quota system) | 1 - Just show quota but don't block anything", array('desc' => 'Enabled', 'type' => 'boolean')); $this->disk_quota_not_blocking = variable_get('disk_quota_not_blocking', 1, "0 - Block data when quota are exceeded (you need a working quota system) | 1 - Just show quota but don't block anything", array('desc' => 'Enabled', 'type' => 'boolean'));
} }
} }
private function dummy_for_translation() { private function dummy_for_translation() {
_("quota_web"); _("quota_web");
} }
function hook_menu() { function hook_menu() {
global $cuid, $mem, $quota; global $cuid, $mem, $quota;
@ -76,34 +71,34 @@ class m_quota {
$q = $this->getquota(); $q = $this->getquota();
foreach ($q as $key=>$value) foreach ($q as $key=>$value)
if (($key=="web")||(isset($value['in_menu'])&&$value['in_menu'])) { if (($key=="web")||(isset($value['in_menu'])&&$value['in_menu'])) {
if (!isset($q[$key]["u"]) || empty($q[$key]["t"])) { if (!isset($q[$key]["u"]) || empty($q[$key]["t"])) {
continue; continue;
} }
$totalsize_used = $quota->get_size_web_sum_user($cuid) + $quota->get_size_mailman_sum_user($cuid) + ($quota->get_size_db_sum_user($mem->user["login"]) + $quota->get_size_mail_sum_user($cuid))/1024; $totalsize_used = $quota->get_size_web_sum_user($cuid) + $quota->get_size_mailman_sum_user($cuid) + ($quota->get_size_db_sum_user($mem->user["login"]) + $quota->get_size_mail_sum_user($cuid))/1024;
$usage_percent = (int) ($totalsize_used / $q[$key]["t"] * 100); $usage_percent = (int) ($totalsize_used / $q[$key]["t"] * 100);
$obj['links'][] = array('txt' => _("quota_" . $key) . " " . sprintf(_("%s%% of %s"), $usage_percent, format_size($q[$key]["t"] * 1024)), 'url' => 'quota_show.php'); $obj['links'][] = array('txt' => _("quota_" . $key) . " " . sprintf(_("%s%% of %s"), $usage_percent, format_size($q[$key]["t"] * 1024)), 'url' => 'quota_show.php');
$obj['links'][] = array('txt' => 'progressbar', 'total' => $q[$key]["t"], 'used' => $totalsize_used); $obj['links'][] = array('txt' => 'progressbar', 'total' => $q[$key]["t"], 'used' => $totalsize_used);
} }
// do not return menu item if there is no quota // do not return menu item if there is no quota
if (!count($obj['links'])) return false; if (!count($obj['links'])) return false;
return $obj; return $obj;
} }
function hook_homepageblock() { function hook_homepageblock() {
return (object)Array( return (object)Array(
'pos' => 20, 'pos' => 20,
'call'=> function() { 'call'=> function() {
define("QUOTASONE","1"); define("QUOTASONE","1");
}, },
'include' => "quotas_oneuser.php" 'include' => "quotas_oneuser.php"
); );
} }
/* ----------------------------------------------------------------- */
/** Check if a user can use a ressource. /** Check if a user can use a ressource.
* @param string $ressource the ressource name (a named quota) * @param string $ressource the ressource name (a named quota)
@ -115,7 +110,6 @@ class m_quota {
return $t["u"] < $t["t"]; return $t["u"] < $t["t"];
} }
/* ----------------------------------------------------------------- */
/** List the quota-managed services in the server /** List the quota-managed services in the server
* @Return array the quota names and description (translated) * @Return array the quota names and description (translated)
@ -135,6 +129,7 @@ class m_quota {
return $qlist; return $qlist;
} }
/** /**
* Synchronise the quotas of the users with the quota of the * Synchronise the quotas of the users with the quota of the
* user's profile. * user's profile.
@ -152,12 +147,11 @@ class m_quota {
return true; return true;
} }
/* /*
* Create default quota in the profile * Create default quota in the profile
* when a new quota appear * when a new quota appear
*
*/ */
function create_missing_quota_profile() { function create_missing_quota_profile() {
global $db, $quota, $msg; global $db, $quota, $msg;
$msg->log("quota", "create_missing_quota_profile"); $msg->log("quota", "create_missing_quota_profile");
@ -171,7 +165,6 @@ class m_quota {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Return a ressource usage (u) and total quota (t) /** Return a ressource usage (u) and total quota (t)
* @param string $ressource ressource to get quota of * @param string $ressource ressource to get quota of
@ -191,7 +184,7 @@ class m_quota {
$res = $hooks->invoke("hook_quota_get"); $res = $hooks->invoke("hook_quota_get");
foreach ($res as $r) { foreach ($res as $r) {
$this->quotas[$r['name']] = $r; $this->quotas[$r['name']] = $r;
$this->quotas[$r['name']]['u'] = $r['used']; // retrocompatibilité $this->quotas[$r['name']]['u'] = $r['used']; // retrocompatibility
if (isset($r['sizeondisk'])) if (isset($r['sizeondisk']))
$this->quotas[$r['name']]['s'] = $r['sizeondisk']; $this->quotas[$r['name']]['s'] = $r['sizeondisk'];
$this->quotas[$r['name']]['t'] = 0; // Default quota = 0 $this->quotas[$r['name']]['t'] = 0; // Default quota = 0
@ -205,7 +198,7 @@ class m_quota {
while (list($key, $val) = each($this->disk)) { while (list($key, $val) = each($this->disk)) {
$a = array(); $a = array();
if ( 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 // If there is a cached value
$a = $disk_cached[$val]; $a = $disk_cached[$val];
@ -218,12 +211,12 @@ class m_quota {
$a['u'] = intval($ak[0]); $a['u'] = intval($ak[0]);
$a['t'] = @intval($ak[1]); $a['t'] = @intval($ak[1]);
} }
$a['sizeondisk'] = $a['u']; $a['sizeondisk'] = $a['u'];
$a['timestamp'] = time(); $a['timestamp'] = time();
$a['uid'] = $cuid; $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' => _("Web disk space"), "s" => $a['sizeondisk'], "t" => $a['t'], "u" => $a['u']); $this->quotas[$val] = array("name" => "$val", 'description' => _("Web disk space"), "s" => $a['sizeondisk'], "t" => $a['t'], "u" => $a['u']);
} }
} }
@ -247,7 +240,6 @@ class m_quota {
} }
} }
/* ----------------------------------------------------------------- */
/** Set the quota for a user (and for a ressource) /** Set the quota for a user (and for a ressource)
* @param string $ressource ressource to set quota of * @param string $ressource ressource to set quota of
@ -280,7 +272,6 @@ class m_quota {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** /**
* Erase all quota information about the user. * Erase all quota information about the user.
@ -292,9 +283,9 @@ class m_quota {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Get the default quotas as an associative array /**
* Get the default quotas as an associative array
* @return array the array of the default quotas * @return array the array of the default quotas
*/ */
function getdefaults() { function getdefaults() {
@ -313,9 +304,9 @@ class m_quota {
return $c; return $c;
} }
/* ----------------------------------------------------------------- */
/** Set the default quotas /**
* Set the default quotas
* @param array associative array of quota (key=>val) * @param array associative array of quota (key=>val)
*/ */
function setdefaults($newq) { function setdefaults($newq) {
@ -334,9 +325,9 @@ class m_quota {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Add an account type for quotas /**
* Add an account type for quotas
* @param string $type account type to be added * @param string $type account type to be added
* @return boolean true if all went ok * @return boolean true if all went ok
*/ */
@ -359,9 +350,9 @@ class m_quota {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** List for quotas /**
* List types of quotas
* @return array * @return array
*/ */
function listtype() { function listtype() {
@ -374,7 +365,6 @@ class m_quota {
return $t; return $t;
} }
/* ----------------------------------------------------------------- */
/** Delete an account type for quotas /** Delete an account type for quotas
* @param string $type account type to be deleted * @param string $type account type to be deleted
@ -384,14 +374,13 @@ class m_quota {
global $db; global $db;
if ($db->query("UPDATE membres SET type='default' WHERE type= ? ;", array($type)) && if ($db->query("UPDATE membres SET type='default' WHERE type= ? ;", array($type)) &&
$db->query("DELETE FROM defquotas WHERE type= ?;", array($type))) { $db->query("DELETE FROM defquotas WHERE type= ?;", array($type))) {
return true; return true;
} else { } else {
return false; return false;
} }
} }
/* ----------------------------------------------------------------- */
/** Create default quotas entries for a new user. /** Create default quotas entries for a new user.
* The user we are talking about is in the global $cuid. * The user we are talking about is in the global $cuid.
@ -418,7 +407,6 @@ class m_quota {
return true; return true;
} }
/* ----------------------------------------------------------------- */
/** Return a quota value with its unit (when it is a space quota) /** Return a quota value with its unit (when it is a space quota)
* in MB, GB, TB ... * in MB, GB, TB ...
@ -428,17 +416,17 @@ class m_quota {
*/ */
function display_val($type, $value) { function display_val($type, $value) {
switch ($type) { switch ($type) {
case 'bw_web': case 'bw_web':
return format_size($value); return format_size($value);
case 'web': case 'web':
return format_size($value * 1024); return format_size($value * 1024);
default: default:
return $value; return $value;
} }
} }
/* get size_xx function (filled by spoolsize.php) */
/* get size_xx function (filled by spoolsize.php) */
function _get_sum_sql($sql) { function _get_sum_sql($sql) {
global $db; global $db;
$db->query($sql); $db->query($sql);
@ -451,6 +439,7 @@ class m_quota {
} }
} }
function _get_count_sql($sql) { function _get_count_sql($sql) {
global $db; global $db;
$db->query($sql); $db->query($sql);
@ -463,6 +452,7 @@ class m_quota {
} }
} }
function _get_size_and_record_sql($sql) { function _get_size_and_record_sql($sql) {
global $db; global $db;
$db->query($sql); $db->query($sql);
@ -477,129 +467,129 @@ class m_quota {
} }
} }
/* get the quota from one user for a cat */
/* get the quota from one user for a cat */
function get_quota_user_cat($uid, $name) { function get_quota_user_cat($uid, $name) {
return $this->_get_sum_sql("SELECT SUM(total) AS sum FROM quotas WHERE uid='$uid' AND name='$name';"); return $this->_get_sum_sql("SELECT SUM(total) AS sum FROM quotas WHERE uid='$uid' AND name='$name';");
} }
/* sum of websites sizes from all users */
/* sum of websites sizes from all users */
function get_size_web_sum_all() { function get_size_web_sum_all() {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_web;"); return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_web;");
} }
/* sum of websites sizes from one user */
/* sum of websites sizes from one user */
function get_size_web_sum_user($u) { function get_size_web_sum_user($u) {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_web WHERE uid='$u';"); return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_web WHERE uid='$u';");
} }
/* sum of mailbox sizes from all domains */
/* sum of mailbox sizes from all domains */
function get_size_mail_sum_all() { function get_size_mail_sum_all() {
return $this->_get_sum_sql("SELECT SUM(quota_dovecot) AS sum FROM dovecot_quota ;"); return $this->_get_sum_sql("SELECT SUM(quota_dovecot) AS sum FROM dovecot_quota ;");
} }
/* sum of mailbox sizes for one domain */
/* sum of mailbox sizes for one domain */
function get_size_mail_sum_domain($dom) { function get_size_mail_sum_domain($dom) {
global $mail; global $mail;
return $mail->get_total_size_for_domain($dom); return $mail->get_total_size_for_domain($dom);
} }
/* sum of mailbox size for ine user */
/* sum of mailbox size for ine user */
function get_size_mail_sum_user($u) { function get_size_mail_sum_user($u) {
return $this->_get_sum_sql("SELECT SUM(quota_dovecot) as sum FROM dovecot_quota WHERE user IN (SELECT CONCAT(a.address, '@', d.domaine) as mail FROM `address` as a INNER JOIN domaines as d ON a.domain_id = d.id WHERE d.compte = '$u' AND a.type ='')"); return $this->_get_sum_sql("SELECT SUM(quota_dovecot) as sum FROM dovecot_quota WHERE user IN (SELECT CONCAT(a.address, '@', d.domaine) as mail FROM `address` as a INNER JOIN domaines as d ON a.domain_id = d.id WHERE d.compte = '$u' AND a.type ='')");
} }
/* count of mailbox sizes from all domains */
/* count of mailbox sizes from all domains */
function get_size_mail_count_all() { function get_size_mail_count_all() {
return $this->_get_count_sql("SELECT COUNT(*) AS count FROM dovecot_quota;"); return $this->_get_count_sql("SELECT COUNT(*) AS count FROM dovecot_quota;");
} }
/* count of mailbox for one domain */
/* count of mailbox for one domain */
function get_size_mail_count_domain($dom) { function get_size_mail_count_domain($dom) {
return $this->_get_count_sql("SELECT COUNT(*) AS count FROM dovecot_quota WHERE user LIKE '%@{$dom}'"); return $this->_get_count_sql("SELECT COUNT(*) AS count FROM dovecot_quota WHERE user LIKE '%@{$dom}'");
} }
/* get list of mailbox alias and size for one domain */
/* get list of mailbox alias and size for one domain */
function get_size_mail_details_domain($dom) { function get_size_mail_details_domain($dom) {
return $this->_get_size_and_record_sql("SELECT user as alias,quota_dovecot as size FROM dovecot_quota WHERE user LIKE '%@{$dom}' ORDER BY alias;"); return $this->_get_size_and_record_sql("SELECT user as alias,quota_dovecot as size FROM dovecot_quota WHERE user LIKE '%@{$dom}' ORDER BY alias;");
} }
/* sum of mailman lists sizes from all domains */
/* sum of mailman lists sizes from all domains */
function get_size_mailman_sum_all() { function get_size_mailman_sum_all() {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman;"); return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman;");
} }
/* sum of mailman lists sizes for one domain */
/* sum of mailman lists sizes for one domain */
function get_size_mailman_sum_domain($dom) { function get_size_mailman_sum_domain($dom) {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman s INNER JOIN mailman m ON s.list = m.list AND s.uid = m.uid WHERE m.domain = '$dom'"); return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman s INNER JOIN mailman m ON s.list = m.list AND s.uid = m.uid WHERE m.domain = '$dom'");
} }
/* sum of mailman lists for one user */
/* sum of mailman lists for one user */
function get_size_mailman_sum_user($u) { function get_size_mailman_sum_user($u) {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_mailman WHERE uid = '{$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 */
/* count of mailman lists sizes from all domains */
function get_size_mailman_count_all() { function get_size_mailman_count_all() {
return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_mailman;"); return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_mailman;");
} }
/* count of mailman lists for one user */
/* count of mailman lists for one user */
function get_size_mailman_count_user($u) { function get_size_mailman_count_user($u) {
return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_mailman WHERE uid = '{$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 */
/* get list of mailman list and size for one user */
function get_size_mailman_details_user($u) { 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"); 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 */
/* sum of databases sizes from all users */
function get_size_db_sum_all() { function get_size_db_sum_all() {
return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_db;"); return $this->_get_sum_sql("SELECT SUM(size) AS sum FROM size_db;");
} }
/* sum of databases sizes for one user */
/* sum of databases sizes for one user */
function get_size_db_sum_user($u) { 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}\_%'"); 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 */
/* count of databases from all users */
function get_size_db_count_all() { function get_size_db_count_all() {
return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_db;"); return $this->_get_count_sql("SELECT COUNT(*) AS count FROM size_db;");
} }
/* count of databases for one user */
/* count of databases for one user */
function get_size_db_count_user($u) { 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}\_%'"); 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 */
/* get list of databases name and size for one user */
function get_size_db_details_user($u) { 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 $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) */
/* Return appropriate value and unit of a size given in Bytes (e.g. 1024 Bytes -> return 1 KB) */
function get_size_unit($size) { function get_size_unit($size) {
$units = array(1073741824 => _("GB"), 1048576 => _("MB"), 1024 => _("KB"), 0 => _("B")); $units = array(1073741824 => _("GB"), 1048576 => _("MB"), 1024 => _("KB"), 0 => _("B"));
foreach ($units as $value => $unit) { foreach ($units as $value => $unit) {
@ -610,11 +600,13 @@ class m_quota {
} }
} }
// Affiche des barres de progression /**
// color_type : * show a progress-bar
// 0 = Pas de changement de couleur * color_type :
// 1 = Progression du vert vers le rouge en fonction du porcentage * 0 = No colo change
// 2 = Progression du rouge vers le vert en fonction du porcentage * 1 = Progress from green to red depending on percentage
* 2 = Progress from red to green depending on percentage
*/
function quota_displaybar($usage, $color_type = 1) { function quota_displaybar($usage, $color_type = 1) {
if ($color_type == 1) { if ($color_type == 1) {
$csscolor = " background-color:" . PercentToColor($usage); $csscolor = " background-color:" . PercentToColor($usage);
@ -624,16 +616,15 @@ class m_quota {
$csscolor = ""; $csscolor = "";
} }
echo '<div class="progress-bar">'; echo '<div class="progress-bar">';
echo '<div class="barre" style="width:' . $usage . '%;' . $csscolor . '" ></div>'; echo '<div class="barre" style="width:' . $usage . '%;' . $csscolor . '" ></div>';
echo '<div class="txt">' . $usage . '%</div>'; echo '<div class="txt">' . $usage . '%</div>';
echo '</div>'; echo '</div>';
} }
/* ==== Hook functions ==== */ /* ==== Hook functions ==== */
/* ----------------------------------------------------------------- */
/** Hook function call when a user is deleted /** Hook function call when a user is deleted
* AlternC's standard function called when a user is deleted * AlternC's standard function called when a user is deleted
@ -643,7 +634,6 @@ class m_quota {
$this->delquotas(); $this->delquotas();
} }
/* ----------------------------------------------------------------- */
/** Hook function called when a user is created /** Hook function called when a user is created
* This function initialize the user's quotas. * This function initialize the user's quotas.
@ -656,7 +646,6 @@ class m_quota {
$this->getquota('', true); // actualise quota $this->getquota('', true); // actualise quota
} }
/* ----------------------------------------------------------------- */
/** Exports all the quota related information for an account. /** Exports all the quota related information for an account.
* @access private * @access private

View File

@ -1,14 +1,6 @@
<?php <?php
/* /*
$Id: mime.php,v 1.3 2004/06/03 14:32:20 anonymous Exp $
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2002 by the AlternC Development Team.
http://alternc.org/
----------------------------------------------------------------------
Based on:
Valentin Lacambre's web hosting softwares: http://altern.org/
---------------------------------------------------------------------- ----------------------------------------------------------------------
LICENSE LICENSE
@ -24,21 +16,10 @@
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
Original Author of file: Benjamin Sonntag 23/12/2001 */
Purpose of file: Brouteur php3 pour AlternC
----------------------------------------------------------------------
*/
/*
Brouteur php3 pour AlternC (voir http://www.alternc.org)
Version 0.1
Notes :
Benjamin Sonntag 23/12/2001 Version initiale
Fichier :
mime.php3 : gestion de la liste des types mime des fichiers.
/**
* Browser mime function to detect mime types and show icons or type names
*/ */
if (!IsSet($MIME_H)) { if (!IsSet($MIME_H)) {
$MIME_H = 1; $MIME_H = 1;

View File

@ -1,30 +1,22 @@
<?php <?php
/* /*
* $Id: variables.php,v 1.8 2005/04/02 00:26:36 anarcat Exp $ ----------------------------------------------------------------------
---------------------------------------------------------------------- LICENSE
AlternC - Web Hosting System
Copyright (C) 2002 by the AlternC Development Team.
http://alternc.org/
----------------------------------------------------------------------
Based on:
Valentin Lacambre's web hosting softwares: http://altern.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL) modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2 as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version. of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html To read the license please visit http://www.gnu.org/copyleft/gpl.html
---------------------------------------------------------------------- ----------------------------------------------------------------------
*/ */
/** /**
* Persistent variable table * Persistent variable table
@ -33,6 +25,7 @@
* @link http://cvs.drupal.org/viewcvs/drupal/drupal/includes/bootstrap.inc?rev=1.38&view=auto * @link http://cvs.drupal.org/viewcvs/drupal/drupal/includes/bootstrap.inc?rev=1.38&view=auto
*/ */
/** /**
* Load the persistent variable table. * Load the persistent variable table.
* *
@ -59,6 +52,7 @@ function variable_init($conf = array()) {
return $variables; return $variables;
} }
/** /**
* Initialize the global $conf array if necessary * Initialize the global $conf array if necessary
* *
@ -72,6 +66,7 @@ function variable_init_maybe() {
} }
} }
/** /**
* Return a persistent variable. * Return a persistent variable.
* *
@ -100,6 +95,7 @@ function variable_get($name, $default = null, $createit_comment = null) {
return $default; return $default;
} }
/** /**
* Set a persistent variable. * Set a persistent variable.
* *
@ -140,6 +136,7 @@ function variable_set($name, $value, $comment = null) {
} }
} }
/** /**
* Unset a persistent variable. * Unset a persistent variable.
* *
@ -152,6 +149,10 @@ function variable_del($name) {
unset($conf[$name]); unset($conf[$name]);
} }
/**
* List all variables
*/
function variables_list() { function variables_list() {
global $db; global $db;
$t = array(); $t = array();
@ -161,3 +162,4 @@ function variables_list() {
} }
return $t; return $t;
} }