diff --git a/bureau/class/class_system_bind.php b/bureau/class/class_system_bind.php index d488e1ab..7d2cb9c0 100644 --- a/bureau/class/class_system_bind.php +++ b/bureau/class/class_system_bind.php @@ -2,40 +2,40 @@ class system_bind { - var $ZONE_TEMPLATE ="/etc/alternc/templates/bind/templates/zone.template"; - var $NAMED_TEMPLATE ="/etc/alternc/templates/bind/templates/named.template"; - var $NAMED_CONF ="/var/lib/alternc/bind/automatic.conf"; - var $RNDC ="/usr/sbin/rndc"; + var $ZONE_TEMPLATE ="/etc/alternc/templates/bind/templates/zone.template"; + var $NAMED_TEMPLATE ="/etc/alternc/templates/bind/templates/named.template"; + var $NAMED_CONF ="/var/lib/alternc/bind/automatic.conf"; + var $RNDC ="/usr/sbin/rndc"; - var $dkim_trusted_host_file = "/etc/opendkim/TrustedHosts"; - var $dkim_keytable_file = "/etc/opendkim/KeyTable"; - var $dkim_signingtable_file = "/etc/opendkim/SigningTable"; + var $dkim_trusted_host_file = "/etc/opendkim/TrustedHosts"; + var $dkim_keytable_file = "/etc/opendkim/KeyTable"; + var $dkim_signingtable_file = "/etc/opendkim/SigningTable"; - var $cache_conf_db = array(); - var $cache_get_persistent = array(); - var $cache_zone_file = array(); - var $cache_domain_summary = array(); - var $zone_file_directory = '/var/lib/alternc/bind/zones/'; + var $cache_conf_db = array(); + var $cache_get_persistent = array(); + var $cache_zone_file = array(); + var $cache_domain_summary = array(); + var $zone_file_directory = '/var/lib/alternc/bind/zones/'; - /** - * - */ - function system_bind() { - // Constructeur - } + /** + * + */ + function system_bind() { + // Constructeur + } - /** - * Return the part of the conf we got from the database - * - * @global m_mysql $db - * @param string $domain - * @return array $this->cache_conf_db - */ - function conf_from_db($domain=false) { - global $db; - // Use cache, fill cache if empty - if (empty($this->cache_conf_db)) { - $db->query(" + /** + * Return the part of the conf we got from the database + * + * @global m_mysql $db + * @param string $domain + * @return array $this->cache_conf_db + */ + function conf_from_db($domain=false) { + global $db; + // Use cache, fill cache if empty + if (empty($this->cache_conf_db)) { + $db->query(" select sd.domaine, 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 and sd.enable in ('ENABLE', 'ENABLED') order by entry ;"); - $t=array(); - while ($db->next_record()) { - $t[$db->f('domaine')][] = $db->f('entry'); - } - $this->cache_conf_db = $t; + $t=array(); + while ($db->next_record()) { + $t[$db->f('domaine')][] = $db->f('entry'); + } + $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 - * - * @param string $domain - * @return string - */ - function get_zone_file_uri($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 full path of the zone configuration file + * + * @param string $domain + * @return string + */ + function get_zone_file_uri($domain) { + return $this->zone_file_directory.$domain; } - 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. + /** + * + * @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 + * @return string + */ + function get_serial($domain) { + // Return the next serial the domain must have. + // Choose between a generated and an incremented. - // Calculated : - $calc = date('Ymd').'00'."\n"; + // Calculated : + $calc = date('Ymd').'00'."\n"; - // Old one : - $old=$calc; // default value - $file = $this->get_zone_file($domain); - preg_match_all("/\s*(\d{10})\s+\;\sserial\s?/", $file, $output_array); - if (isset($output_array[1][0]) && !empty($output_array[1][0])) { - $old = $output_array[1][0]; + // Old one : + $old=$calc; // default value + $file = $this->get_zone_file($domain); + preg_match_all("/\s*(\d{10})\s+\;\sserial\s?/", $file, $output_array); + if (isset($output_array[1][0]) && !empty($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 - */ - function get_persistent($domain) { - if ( ! isset($this->cache_get_persistent[$domain] )) { - 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])) { - $this->cache_get_persistent[$domain] = $output_array[1][0]; - } else { - $this->cache_get_persistent[$domain] = false; - } - } // isset - return $this->cache_get_persistent[$domain]; - } + /** + * Return lines that are after ;;; END ALTERNC AUTOGENERATE CONFIGURATION + * + * @param string $domain + * @return string + */ + function get_persistent($domain) { + if ( ! isset($this->cache_get_persistent[$domain] )) { + 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])) { + $this->cache_get_persistent[$domain] = $output_array[1][0]; + } else { + $this->cache_get_persistent[$domain] = false; + } + } // isset + return $this->cache_get_persistent[$domain]; + } - /** - * - * @return string - */ - function get_zone_header() { - return file_get_contents($this->ZONE_TEMPLATE); - } + /** + * + * @return string + */ + function get_zone_header() { + return file_get_contents($this->ZONE_TEMPLATE); + } - /** - * - * @global m_dom $dom - * @param string $domain - * @return array Retourne un tableau - */ - function get_domain_summary($domain=false) { - global $dom; + /** + * + * @global m_dom $dom + * @param string $domain + * @return array Retourne un tableau + */ + function get_domain_summary($domain=false) { + global $dom; - // Use cache if is filled, if not, fill it - if (empty($this->cache_domain_summary)) { - $this->cache_domain_summary = $dom->get_domain_all_summary(); + // Use cache if is filled, if not, fill it + if (empty($this->cache_domain_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) { - $target_dir = "/etc/opendkim/keys/$domain"; - if (file_exists($target_dir)) { - @unlink("$target_dir/alternc_private"); - @unlink("$target_dir/alternc.txt"); - @rmdir($target_dir); + /** + * + * @param string $domain + * @return boolean + */ + function dkim_delete($domain) { + $target_dir = "/etc/opendkim/keys/$domain"; + if (file_exists($target_dir)) { + @unlink("$target_dir/alternc_private"); + @unlink("$target_dir/alternc.txt"); + @rmdir($target_dir); + } + return true; } - return true; - } - /** - * Generate the domain DKIM key - * - * @param string $domain - * @return null|boolean - */ - function dkim_generate_key($domain) { - // Stop here if we do not manage the mail - $domainInfo = $this->get_domain_summary($domain); - if ( ! $domainInfo['gesmx'] ) return; + /** + * Generate the domain DKIM key + * + * @param string $domain + * @return null|boolean + */ + function dkim_generate_key($domain) { + // Stop here if we do not manage the mail + $domainInfo = $this->get_domain_summary($domain); + 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 - $old_dir=getcwd(); - chdir($target_dir); - exec('opendkim-genkey -r -d '.escapeshellarg($domain).' -s "alternc" '); - chdir($old_dir); + // Generate the key + $old_dir=getcwd(); + chdir($target_dir); + exec('opendkim-genkey -r -d '.escapeshellarg($domain).' -s "alternc" '); + chdir($old_dir); - // opendkim must be owner of the key - chown("$target_dir/alternc.private", 'opendkim'); - chgrp("$target_dir/alternc.private", 'opendkim'); + // opendkim must be owner of the key + chown("$target_dir/alternc.private", 'opendkim'); + chgrp("$target_dir/alternc.private", 'opendkim'); - 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"; + return true; // FIXME handle error } - $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); + /** + * 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); + $keytable_old =@file_get_contents($this->dkim_keytable_file); + $signingtable_old=@file_get_contents($this->dkim_signingtable_file); - # Keep manuel entry - 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])) { - $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); - if (isset($output_array[1][0]) && !empty($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); - if (isset($output_array[1][0]) && !empty($output_array[1][0])) { - $signingtable_new.=$output_array[1][0]; - } + # Keep manuel entry + 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])) { + $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); + if (isset($output_array[1][0]) && !empty($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); + if (isset($output_array[1][0]) && !empty($output_array[1][0])) { + $signingtable_new.=$output_array[1][0]; + } - // Save if there are some diff - if ( $trusted_host_new != $trusted_host_old ) { - file_put_contents($this->dkim_trusted_host_file, $trusted_host_new); + // Save if there are some diff + if ( $trusted_host_new != $trusted_host_old ) { + 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); - } - if ( $signingtable_new != $signingtable_old ) { - file_put_contents($this->dkim_signingtable_file, $signingtable_new); + /** + * + * @param string $domain + * @return string + */ + 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); } - } - /** - * - * @param string $domain - * @return string - */ - 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); + /** + * 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 @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 - * - * @global string $L_FQDN - * @global string $L_NS1_HOSTNAME - * @global string $L_NS2_HOSTNAME - * @global string $L_DEFAULT_MX - * @global string $L_DEFAULT_SECONDARY_MX - * @global string $L_PUBLIC_IP - * @param string $domain - * @return string - */ - function get_zone($domain) { - global $L_FQDN, $L_NS1_HOSTNAME, $L_NS2_HOSTNAME, $L_DEFAULT_MX, $L_DEFAULT_SECONDARY_MX, $L_PUBLIC_IP; + /** + * + * Return a fully generated zone + * + * @global string $L_FQDN + * @global string $L_NS1_HOSTNAME + * @global string $L_NS2_HOSTNAME + * @global string $L_DEFAULT_MX + * @global string $L_DEFAULT_SECONDARY_MX + * @global string $L_PUBLIC_IP + * @param string $domain + * @return string + */ + function get_zone($domain) { + 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.=implode("\n",$this->conf_from_db($domain)); - $zone.="\n;;;HOOKED ENTRY\n"; + $zone =$this->get_zone_header(); + $zone.=implode("\n",$this->conf_from_db($domain)); + $zone.="\n;;;HOOKED ENTRY\n"; - $zone.= $this->dkim_entry($domain); - $zone.= $this->mail_autoconfig_entry($domain); + $zone.= $this->dkim_entry($domain); + $zone.= $this->mail_autoconfig_entry($domain); - $zone.="\n;;; END ALTERNC AUTOGENERATE CONFIGURATION\n"; - $zone.=$this->get_persistent($domain); - $domainInfo = $this->get_domain_summary($domain); + $zone.="\n;;; END ALTERNC AUTOGENERATE CONFIGURATION\n"; + $zone.=$this->get_persistent($domain); + $domainInfo = $this->get_domain_summary($domain); - // FIXME check those vars - $zone = strtr($zone, array( + // FIXME check those vars + $zone = strtr($zone, array( "%%fqdn%%"=>"$L_FQDN", "%%ns1%%"=>"$L_NS1_HOSTNAME", "%%ns2%%"=>"$L_NS2_HOSTNAME", @@ -344,146 +344,146 @@ class system_bind { "@@SERIAL@@"=>$this->get_serial($domain), "@@PUBLIC_IP@@"=>"$L_PUBLIC_IP", "@@ZONETTL@@"=> $domainInfo['zonettl'], - )); + )); - 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 $zone; } - } - /** - * return true if zone is locked - * - * @param string $domain - * @return boolean - */ - function is_locked($domain) { - preg_match_all("/(\;\s*LOCKED:YES)/i", $this->get_zone_file($domain), $output_array); - if (isset($output_array[1][0]) && !empty($output_array[1][0])) { - return true; + /** + * + * @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 false; - } - /** - * - * @global m_mysql $db - * @global m_dom $dom - * @param string $domain - * @return boolean - */ - function save_zone($domain) { - global $db, $dom; + /** + * return true if zone is locked + * + * @param string $domain + * @return boolean + */ + function is_locked($domain) { + preg_match_all("/(\;\s*LOCKED:YES)/i", $this->get_zone_file($domain), $output_array); + 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 - $dom->set_dns_action($domain, 'OK'); - return false; - } + /** + * + * @global m_mysql $db + * @global m_dom $dom + * @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 - $file=$this->get_zone_file_uri($domain); - file_put_contents($file, $this->get_zone($domain)); - chown($file, 'bind'); - chmod($file, 0640); + // Save file, and apply chmod/chown + $file=$this->get_zone_file_uri($domain); + file_put_contents($file, $this->get_zone($domain)); + chown($file, 'bind'); + chmod($file, 0640); - $dom->set_dns_action($domain, 'OK'); - 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))); + $dom->set_dns_action($domain, 'OK'); + return true; // fixme add tests } - // Get the actual conf file - $old_named_conf = @file_get_contents($this->NAMED_CONF); - - // Apply new configuration only if there are some differences - 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') ); + /** + * 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; } - 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))); + } - /** - * Regenerate bind configuration and load it - * - * @global m_hooks $hooks - * @param boolean $all - * @return boolean - */ - function regenerate_conf($all=false) { - global $hooks; + // Get the actual conf file + $old_named_conf = @file_get_contents($this->NAMED_CONF); - foreach ($this->get_domain_summary() as $domain => $ds ) { - if ( ! $ds['gesdns'] && strtoupper($ds['dns_action']) == 'OK' ) continue; // Skip if we do not manage DNS and is up-to-date for this domain + // Apply new configuration only if there are some differences + 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' ) || - (strtoupper($ds['dns_action']) == 'UPDATE' && $ds['gesdns']==false ) // in case we update the zone to disable DNS management - ) { - $this->delete_zone($domain); - continue; - } + return true; + } - 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 + /** + * Regenerate bind configuration and load it + * + * @global m_hooks $hooks + * @param boolean $all + * @return boolean + */ + function regenerate_conf($all=false) { + global $hooks; - $this->dkim_refresh_list(); - $this->reload_named(); - return true; - } + foreach ($this->get_domain_summary() as $domain => $ds ) { + if ( ! $ds['gesdns'] && strtoupper($ds['dns_action']) == 'OK' ) continue; // Skip if we do not manage DNS and is up-to-date for this domain - /** - * - */ - private function dummy_for_translation() { - _("The zone file of this domain is locked. Contact your administrator."); - } + if ( (strtoupper($ds['dns_action']) == 'DELETE' ) || + (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); + $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 diff --git a/bureau/class/config.php b/bureau/class/config.php index 1d937dd6..220da71e 100755 --- a/bureau/class/config.php +++ b/bureau/class/config.php @@ -27,7 +27,7 @@ Original Author of file: Benjamin Sonntag Purpose of file: General configuration file for AlternC Desktop ---------------------------------------------------------------------- - */ +*/ define('DO_XHPROF_STATS', FALSE); if (DO_XHPROF_STATS) { @@ -45,15 +45,15 @@ session_start(); /* 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 : - */ +*/ /* * / - if (getenv("REMOTE_ADDR")!="127.0.0.1") { - echo "Le bureau AlternC est en vacances jusqu'a minuit pour maintenance.
- Merci de revenir plus tard."; - exit(); - } - /* */ + if (getenv("REMOTE_ADDR")!="127.0.0.1") { + echo "Le bureau AlternC est en vacances jusqu'a minuit pour maintenance.
+ Merci de revenir plus tard."; + exit(); + } + /* */ 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 !!"); @@ -125,10 +125,10 @@ require_once($root . "/class/variables.php"); */ class DB_system extends DB_Sql { - function __construct() { - 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); - } + function __construct() { + 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); + } } $db = new DB_system(); @@ -147,8 +147,8 @@ foreach (glob($root . "class/m_*.php") as $di) { } } /* 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. // 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")))) { // do not redirect if access is not by HTTP(s) if (isset($_SERVER['REQUEST_URI'])) { - header("Location: https://".$_SERVER["HTTP_HOST"].$_SERVER['REQUEST_URI']); - exit; + header("Location: https://".$_SERVER["HTTP_HOST"].$_SERVER['REQUEST_URI']); + exit; } } @@ -186,10 +186,10 @@ if ((variable_get('force_https', '0', "This variable is set to 0 (default) if us $fatalcsrf=false; if (count($_POST) && !defined("NOCSRF")) { - if (csrf_check()<=0) { - // We will trigger the error LATER in the code => need initialization of classes - $fatalcsrf=true; - } + if (csrf_check()<=0) { + // We will trigger the error LATER in the code => need initialization of classes + $fatalcsrf=true; + } } /* 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`"); if ($db->next_record($result)) { $variable = $db->Record; - $variable['username']=min(128, $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_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['username']=min(128, $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_database_length', $variable['database'], 'Maximum length allowed for SQL database names by your SQL server (do not modify unless you know what you do)'); } } diff --git a/bureau/class/config_nochk.php b/bureau/class/config_nochk.php index ec8208bf..5d2da96f 100644 --- a/bureau/class/config_nochk.php +++ b/bureau/class/config_nochk.php @@ -27,7 +27,7 @@ Original Author of file: Benjamin Sonntag Purpose of file: General configuration file for AlternC Desktop ---------------------------------------------------------------------- - */ +*/ define('NOCHECK', 1); require_once("config.php"); diff --git a/bureau/class/db_mysql.php b/bureau/class/db_mysql.php index a54f8f2f..37ec6614 100644 --- a/bureau/class/db_mysql.php +++ b/bureau/class/db_mysql.php @@ -10,287 +10,287 @@ class DB_Sql { - /* public: connection parameters */ - private $Host; - private $Database; - private $User; - private $Password; + /* public: connection parameters */ + private $Host; + private $Database; + private $User; + private $Password; - /* public: configuration parameters */ - private $Auto_Free = False; // Set to True for automatic mysql_free_result() - 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 $Seq_Table = "db_sequence"; + /* public: configuration parameters */ + private $Auto_Free = False; // Set to True for automatic mysql_free_result() + 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 $Seq_Table = "db_sequence"; - /* public: result array and current row number */ - public /* FIXME */ $Record = array(); - private $Row = 0; - private $num_rows; + /* public: result array and current row number */ + public /* FIXME */ $Record = array(); + private $Row = 0; + private $num_rows; - /* public: current error number and error text */ - private $Errno; - private $Error; + /* public: current error number and error text */ + private $Errno; + private $Error; - /* private: link and query handles */ - private $Query_String; + /* private: link and query handles */ + private $Query_String; - /* PDO related variables */ - private $pdo_instance = NULL; - private $pdo_query = NULL; + /* PDO related variables */ + private $pdo_instance = NULL; + private $pdo_query = NULL; - /** - * Constructor - */ - function __construct($db, $host, $user, $passwd) { + /** + * Constructor + */ + function __construct($db, $host, $user, $passwd) { $dsn = sprintf('mysql:dbname=%s;host=%s', $db, $host); try { - $this->pdo_instance = new PDO($dsn, $user, $passwd); + $this->pdo_instance = new PDO($dsn, $user, $passwd); } catch (PDOException $e) { - echo "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; + echo "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 - * - * This function discards the last query result. - */ - function free() { - $this->pdo_query->closeCursor(); - } + /** + * Discard the query result + * + * This function discards the last query result. + */ + function free() { + $this->pdo_query->closeCursor(); + } - function is_connected() { - return $this->pdo_instance != FALSE; - } + function is_connected() { + return $this->pdo_instance != FALSE; + } - function last_error() { - return $this->Error; - } - /** - * Perform a query - * - * This function performs the MySQL query described in the string parameter - * - * @param a string describing the MySQL query - * @param arguments is an optionnal array for future use with PDO parametrized requests - * @return the $Query_ID class variable (null if fails) - */ - function query($Query_String, $arguments = false) { - global $debug_alternc; + function last_error() { + return $this->Error; + } + /** + * Perform a query + * + * This function performs the MySQL query described in the string parameter + * + * @param a string describing the MySQL query + * @param arguments is an optionnal array for future use with PDO parametrized requests + * @return the $Query_ID class variable (null if fails) + */ + function query($Query_String, $arguments = false) { + global $debug_alternc; - if (empty($Query_String) || !$this->is_connected()) - return FALSE; + if (empty($Query_String) || !$this->is_connected()) + return FALSE; - $this->Query_String = $Query_String; - if ($this->Debug) - printf("Debug: query = %s
\n", $Query_String); + $this->Query_String = $Query_String; + if ($this->Debug) + printf("Debug: query = %s
\n", $Query_String); - $debug_chrono_start = microtime(true); + $debug_chrono_start = microtime(true); - if ($arguments===false) { - $this->pdo_query = $this->pdo_instance->query($Query_String); - $exec_state = is_object($this->pdo_query); + if ($arguments===false) { + $this->pdo_query = $this->pdo_instance->query($Query_String); + $exec_state = is_object($this->pdo_query); - } else { + } else { - $this->pdo_query = $this->pdo_instance->prepare($this->Query_String); - $exec_state = ($arguments) ? $this->pdo_query->execute($arguments) - : $this->pdo_query->execute(); - // WARNING: this ternary is when we pass array() as $arguments - } + $this->pdo_query = $this->pdo_instance->prepare($this->Query_String); + $exec_state = ($arguments) ? $this->pdo_query->execute($arguments) + : $this->pdo_query->execute(); + // WARNING: this ternary is when we pass array() as $arguments + } - $debug_chrono_start = (microtime(true) - $debug_chrono_start)*1000; - $this->Row = 0; + $debug_chrono_start = (microtime(true) - $debug_chrono_start)*1000; + $this->Row = 0; - if ($exec_state == FALSE) { - if (is_object($this->pdo_query)) { + if ($exec_state == FALSE) { + 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->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"); + if ($this->Record == FALSE) { + 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; - } - - /** - * 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; } - return TRUE; - } - - /* public: table locking */ - function lock($table, $mode="write") { - if (!$this->is_connected()) - return FALSE; + /* public: table locking */ + function lock($table, $mode="write") { + if (!$this->is_connected()) + return FALSE; - $query="lock tables "; - if (is_array($table)) { - while (list($key,$value)=each($table)) { - if ($key=="read" && $key!=0) { - $query.="$value read, "; - } else { - $query.="$value $mode, "; - } + $query="lock tables "; + if (is_array($table)) { + while (list($key,$value)=each($table)) { + if ($key=="read" && $key!=0) { + $query.="$value read, "; + } else { + $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)) { - $this->halt("lock($table, $mode) failed."); - return FALSE; - } + if (!$this->query($query)) { + $this->halt("lock($table, $mode) failed."); + return FALSE; + } - return TRUE; + return TRUE; - } + } - function unlock() { - if (!$this->is_connected()) - return FALSE; + function unlock() { + if (!$this->is_connected()) + return FALSE; - if (!$this->query('unlock tables')) { - $this->halt("unlock() failed."); - return FALSE; - } - } + if (!$this->query('unlock tables')) { + $this->halt("unlock() failed."); + return FALSE; + } + } - /* public: evaluate the result (size, width) */ - function affected_rows() { - return $this->pdo_query->rowCount(); - } + /* public: evaluate the result (size, width) */ + function affected_rows() { + return $this->pdo_query->rowCount(); + } - function num_rows() { - return $this->pdo_query->rowCount(); - } + function num_rows() { + return $this->pdo_query->rowCount(); + } - function num_fields() { - return $this->pdo_query->columnCount(); - } + function num_fields() { + return $this->pdo_query->columnCount(); + } - /* public: shorthand notation */ - function nf() { - return $this->num_rows(); - } + /* public: shorthand notation */ + function nf() { + return $this->num_rows(); + } - function np() { - print $this->num_rows(); - } + function np() { + print $this->num_rows(); + } - /** - * @param string $Name - * @return integer - */ - function f($Name) { - if (isset($this->Record[$Name])) - return $this->Record[$Name]; - else - return false; - } + /** + * @param string $Name + * @return integer + */ + function f($Name) { + if (isset($this->Record[$Name])) + return $this->Record[$Name]; + else + return false; + } - function current_record() { - return $this->Record; - } + function current_record() { + return $this->Record; + } - function p($Name) { - print $this->Record[$Name]; - } + function p($Name) { + print $this->Record[$Name]; + } - function lastid() { - return $this->pdo_instance->lastInsertId(); - } + function lastid() { + return $this->pdo_instance->lastInsertId(); + } /** * Escape a string to use it into a SQL PDO query * @param string string to escape * @return string escaped string */ - function quote($string) { - return $this->pdo_instance->quote($string); - } + function quote($string) { + return $this->pdo_instance->quote($string); + } /** @@ -298,85 +298,85 @@ class DB_Sql { * @param query string query to execute * @return integer the number of affected rows */ - function exec($query) { - return $this->pdo_instance->exec($query); - } + function exec($query) { + return $this->pdo_instance->exec($query); + } - /* public: sequence numbers */ - function nextid($seq_name) { - if (!$this->is_connected()) - return FALSE; + /* public: sequence numbers */ + function nextid($seq_name) { + if (!$this->is_connected()) + return FALSE; - if ($this->lock($this->Seq_Table)) { - /* get sequence number (locked) and increment */ - $q = sprintf("select nextid from %s where seq_name = '%s'", - $this->Seq_Table, - $seq_name); - $this->query($q); - $this->next_record(); + if ($this->lock($this->Seq_Table)) { + /* get sequence number (locked) and increment */ + $q = sprintf("select nextid from %s where seq_name = '%s'", + $this->Seq_Table, + $seq_name); + $this->query($q); + $this->next_record(); - $id = $this->f('nextid'); + $id = $this->f('nextid'); - /* No current value, make one */ - if (!$id) { - $currentid = 0; - $q = sprintf("insert into %s values('%s', %s)", - $this->Seq_Table, - $seq_name, - $currentid); - $this->query($q); - } else { - $currentid = $id; - } + /* No current value, make one */ + if (!$id) { + $currentid = 0; + $q = sprintf("insert into %s values('%s', %s)", + $this->Seq_Table, + $seq_name, + $currentid); + $this->query($q); + } else { + $currentid = $id; + } - $nextid = $currentid + 1; - $q = sprintf("update %s set nextid = '%s' where seq_name = '%s'", - $this->Seq_Table, - $nextid, - $seq_name); - $this->query($q); - $this->unlock(); - } else { - $this->halt("cannot lock ".$this->Seq_Table." - has it been created?"); - return FALSE; - } + $nextid = $currentid + 1; + $q = sprintf("update %s set nextid = '%s' where seq_name = '%s'", + $this->Seq_Table, + $nextid, + $seq_name); + $this->query($q); + $this->unlock(); + } else { + $this->halt("cannot lock ".$this->Seq_Table." - has it been created?"); + return FALSE; + } - return $nextid; - } + return $nextid; + } - /* public: return table metadata */ - function metadata($table='',$full=false) { - global $msg; - $msg->raise("ERROR", 'Mysql', 'function is no longer implemented (metadata())'); - return FALSE; - } + /* public: return table metadata */ + function metadata($table='',$full=false) { + global $msg; + $msg->raise("ERROR", 'Mysql', 'function is no longer implemented (metadata())'); + return FALSE; + } - /* private: error handling */ - function halt($msg) { - if ($this->Halt_On_Error == "no") - return; + /* private: error handling */ + function halt($msg) { + if ($this->Halt_On_Error == "no") + return; - $this->haltmsg($msg); + $this->haltmsg($msg); - if ($this->Halt_On_Error != "report") - die("Session halted."); - } + if ($this->Halt_On_Error != "report") + die("Session halted."); + } - function haltmsg($msg) { - printf("Database error: %s
\n", $msg); - printf("MySQL Error: %s (%s)
\n", - $this->Errno, - implode("\n", $this->Error)); - } + function haltmsg($msg) { + printf("Database error: %s
\n", $msg); + printf("MySQL Error: %s (%s)
\n", + $this->Errno, + implode("\n", $this->Error)); + } - function table_names() { - $this->query("SHOW TABLES"); - $return = array(); - while ($this->next_record()) - $return[] = array('table_name' => $this->p(0), 'tablespace_name' => $this->Database, 'database' => $this->Database); + function table_names() { + $this->query("SHOW TABLES"); + $return = array(); + while ($this->next_record()) + $return[] = array('table_name' => $this->p(0), 'tablespace_name' => $this->Database, 'database' => $this->Database); - return $return; - } + return $return; + } } ?> diff --git a/bureau/class/functions.php b/bureau/class/functions.php index 1f9679d9..bba64034 100755 --- a/bureau/class/functions.php +++ b/bureau/class/functions.php @@ -22,7 +22,7 @@ ---------------------------------------------------------------------- Purpose of file: Miscellaneous functions globally used ---------------------------------------------------------------------- - */ +*/ /** * Format a field value for input or textarea : @@ -528,7 +528,7 @@ function _md5cr($pass, $salt = "") { function split_mysql_database_name($dbname) { $db_exploded_name = explode("_", $dbname); 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. - * Must be called when pre-filling fields values in forms such as : - * - * Use the charset of the current language for transcription - * - * @global string $charset - * @param string $str - * @param boolean $affiche - * @return string - */ + /* Echo the HTMLSpecialChars version of a value. + * Must be called when pre-filling fields values in forms such as : + * + * Use the charset of the current language for transcription + * + * @global string $charset + * @param string $str + * @param boolean $affiche + * @return string + */ function ehe($str, $affiche = TRUE) { global $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. - * Must be called when pre-filling fields values in URLS such as : - * document.location='logs_tail.php?file= - * Use the charset of the current language for transcription - * - * @global string $charset - * @param string $str - * @param boolean $affiche - * @return string - */ + /* Echo the URLENCODED version of a value. + * Must be called when pre-filling fields values in URLS such as : + * document.location='logs_tail.php?file= + * Use the charset of the current language for transcription + * + * @global string $charset + * @param string $str + * @param boolean $affiche + * @return string + */ function eue($str, $affiche = TRUE) { global $charset; $retour = urlencode($str); @@ -677,26 +677,26 @@ function getFields($fields, $requestOnly = false) { $method = "_" . strtoupper($options[0]); } switch ($options[1]) { - case "integer": - $vars[$name] = (isset($GLOBALS[$method][$name]) && is_numeric($GLOBALS[$method][$name]) ? intval($GLOBALS[$method][$name]) : $options[2]); - break; - case "float": - $vars[$name] = (isset($GLOBALS[$method][$name]) && is_numeric($GLOBALS[$method][$name]) ? floatval($GLOBALS[$method][$name]) : $options[2]); - break; - case "string": - $vars[$name] = (isset($GLOBALS[$method][$name]) ? trim($GLOBALS[$method][$name]) : $options[2]); - break; - case "array": - $vars[$name] = (isset($GLOBALS[$method][$name]) && is_array($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]); - break; - case "boolean": - $vars[$name] = (isset($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]); - break; - case "file": - $vars[$name] = (isset($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]); - break; - default: - die("Illegal method type used for field " . $name . " : " . $options[1]); + case "integer": + $vars[$name] = (isset($GLOBALS[$method][$name]) && is_numeric($GLOBALS[$method][$name]) ? intval($GLOBALS[$method][$name]) : $options[2]); + break; + case "float": + $vars[$name] = (isset($GLOBALS[$method][$name]) && is_numeric($GLOBALS[$method][$name]) ? floatval($GLOBALS[$method][$name]) : $options[2]); + break; + case "string": + $vars[$name] = (isset($GLOBALS[$method][$name]) ? trim($GLOBALS[$method][$name]) : $options[2]); + break; + case "array": + $vars[$name] = (isset($GLOBALS[$method][$name]) && is_array($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]); + break; + case "boolean": + $vars[$name] = (isset($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]); + break; + case "file": + $vars[$name] = (isset($GLOBALS[$method][$name]) ? $GLOBALS[$method][$name] : $options[2]); + break; + default: + 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 switch ($dH) { - case($dH >= 0.0 && $dH < 1.0): - $dR = $dC; - $dG = $dX; - $dB = 0.0; - break; - case($dH >= 1.0 && $dH < 2.0): - $dR = $dX; - $dG = $dC; - $dB = 0.0; - break; - case($dH >= 2.0 && $dH < 3.0): - $dR = 0.0; - $dG = $dC; - $dB = $dX; - break; - case($dH >= 3.0 && $dH < 4.0): - $dR = 0.0; - $dG = $dX; - $dB = $dC; - break; - case($dH >= 4.0 && $dH < 5.0): - $dR = $dX; - $dG = 0.0; - $dB = $dC; - break; - case($dH >= 5.0 && $dH < 6.0): - $dR = $dC; - $dG = 0.0; - $dB = $dX; - break; - default: - $dR = 0.0; - $dG = 0.0; - $dB = 0.0; - break; + case($dH >= 0.0 && $dH < 1.0): + $dR = $dC; + $dG = $dX; + $dB = 0.0; + break; + case($dH >= 1.0 && $dH < 2.0): + $dR = $dX; + $dG = $dC; + $dB = 0.0; + break; + case($dH >= 2.0 && $dH < 3.0): + $dR = 0.0; + $dG = $dC; + $dB = $dX; + break; + case($dH >= 3.0 && $dH < 4.0): + $dR = 0.0; + $dG = $dX; + $dB = $dC; + break; + case($dH >= 4.0 && $dH < 5.0): + $dR = $dX; + $dG = 0.0; + $dB = $dC; + break; + case($dH >= 5.0 && $dH < 6.0): + $dR = $dC; + $dG = 0.0; + $dB = $dX; + break; + default: + $dR = 0.0; + $dG = 0.0; + $dB = 0.0; + break; } $dM = $dV - $dC; @@ -1130,8 +1130,8 @@ function csrf_get($return=false) { $_SESSION["csrf"]=md5(mt_rand().mt_rand().mt_rand()); } if ($token=="") { - $token=md5(mt_rand().mt_rand().mt_rand()); - $db->query("INSERT INTO csrf SET cookie=?, token=?, created=NOW(), used=0;",array($_SESSION["csrf"],$token)); + $token=md5(mt_rand().mt_rand().mt_rand()); + $db->query("INSERT INTO csrf SET cookie=?, token=?, created=NOW(), used=0;",array($_SESSION["csrf"],$token)); } if ($return) return $token; diff --git a/bureau/class/lang_env.php b/bureau/class/lang_env.php index 4c171b20..a76aab2d 100644 --- a/bureau/class/lang_env.php +++ b/bureau/class/lang_env.php @@ -3,11 +3,11 @@ $lang_translation = array(# If you comment lang here, it won't be displayed. "fr_FR" => "Français", "en_US" => "English", - "es_ES" => "Español", -# "it_IT" => "Italiano", -# "de_DE" => "Deutsch", -# "pt_BR" => "Portuguese", -# "nl_NL" => "Dutch", + "es_ES" => "Español", + # "it_IT" => "Italiano", + # "de_DE" => "Deutsch", + # "pt_BR" => "Portuguese", + # "nl_NL" => "Dutch", ); global $arr_lang_translation; diff --git a/bureau/class/local.php b/bureau/class/local.php index b3e6dabd..0f355091 100755 --- a/bureau/class/local.php +++ b/bureau/class/local.php @@ -9,10 +9,10 @@ $L_VERSION_HELP = "3.0"; /* To ease the transition, we define a lookup table for old names */ $compat = array('DEFAULT_MX' => 'MX', - 'MYSQL_USER' => 'MYSQL_LOGIN', - 'MYSQL_PASS' => 'MYSQL_PWD', - 'NS1_HOSTNAME' => 'NS1', - 'NS2_HOSTNAME' => 'NS2'); +'MYSQL_USER' => 'MYSQL_LOGIN', +'MYSQL_PASS' => 'MYSQL_PWD', +'NS1_HOSTNAME' => 'NS1', +'NS2_HOSTNAME' => 'NS2'); $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))) { if (preg_match('/^([A-Za-z0-9_]*) *= *"?(.*?)"?$/', trim($line), $regs)) { switch ($regs[1]) { - case "user": - $GLOBALS['L_MYSQL_LOGIN'] = $regs[2]; - break; - case "password": - $GLOBALS['L_MYSQL_PWD'] = $regs[2]; - break; - case "host": - $GLOBALS['L_MYSQL_HOST'] = $regs[2]; - break; - case "database": - $GLOBALS['L_MYSQL_DATABASE'] = $regs[2]; - break; + case "user": + $GLOBALS['L_MYSQL_LOGIN'] = $regs[2]; + break; + case "password": + $GLOBALS['L_MYSQL_PWD'] = $regs[2]; + break; + case "host": + $GLOBALS['L_MYSQL_HOST'] = $regs[2]; + break; + case "database": + $GLOBALS['L_MYSQL_DATABASE'] = $regs[2]; + break; } } } diff --git a/bureau/class/m_action.php b/bureau/class/m_action.php index 6052d9c7..caf88d5d 100644 --- a/bureau/class/m_action.php +++ b/bureau/class/m_action.php @@ -18,7 +18,7 @@ Original Author of file: Lerider Steven Purpose of file: Manage generic actions. ---------------------------------------------------------------------- - */ +*/ /** * 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; $msg->log("action", "set", $type); $serialized = serialize($parameters); - $type = strtoupper($type); - if (in_array($type, array('CHMOD', - 'CREATE_FILE', - 'CREATE_DIR', - 'MOVE', - 'FIX_USER', - 'FIX_FILE', - 'FIX_DIR', - 'DELETE'))) { - $query = "INSERT INTO `actions` (type, parameters, creation, user) VALUES('$type', '$serialized', now(), '$user');"; - } else { - return False; - } + $type = strtoupper($type); + if (in_array($type, array('CHMOD', + 'CREATE_FILE', + 'CREATE_DIR', + 'MOVE', + 'FIX_USER', + 'FIX_FILE', + 'FIX_DIR', + 'DELETE'))) { + $query = "INSERT INTO `actions` (type, parameters, creation, user) VALUES('$type', '$serialized', now(), '$user');"; + } else { + return False; + } if (!$db->query($query)) { $msg->raise("ERROR", "action", _("Error setting actions")); diff --git a/bureau/class/m_admin.php b/bureau/class/m_admin.php index a0326687..c44b0ace 100644 --- a/bureau/class/m_admin.php +++ b/bureau/class/m_admin.php @@ -22,7 +22,7 @@ ---------------------------------------------------------------------- Purpose of file: Administrate members and rights. ---------------------------------------------------------------------- - */ +*/ /* ----------------------------------------------------------------- */ @@ -692,27 +692,27 @@ class m_admin { if ($db->next_record()) { // TODO: put that string into gettext ! $mail = << $L_FQDN, - '%creator' => $db->Record['parentlogin'], - '%uid' => $db->Record['uid'], - '%login' => $db->Record['login'], - '%mail' => $db->Record['mail'], - '%cuid' => $db->Record['creator'], - '%canpass' => $db->Record['canpass'], - '%type' => $db->Record['type'], - '%notes' => $db->Record['notes'])); + '%creator' => $db->Record['parentlogin'], + '%uid' => $db->Record['uid'], + '%login' => $db->Record['login'], + '%mail' => $db->Record['mail'], + '%cuid' => $db->Record['creator'], + '%canpass' => $db->Record['canpass'], + '%type' => $db->Record['type'], + '%notes' => $db->Record['notes'])); $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")) { //sprintf(_("Email successfully sent to %s"), $dest); @@ -884,7 +884,7 @@ EOF; $hooks->invoke("hook_admin_del_member"); 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(); // 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)); @@ -940,7 +940,7 @@ EOF; } } else { 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; } } @@ -995,12 +995,12 @@ EOF; global $db; if (!$db->query("SELECT *, m.renewed + INTERVAL duration MONTH 'expiry'," . - " CASE WHEN m.duration IS NULL THEN 0" . - " WHEN m.renewed + INTERVAL m.duration MONTH <= NOW() THEN 3" . - " WHEN m.renewed <= NOW() THEN 2" . - " ELSE 1 END 'status' FROM membres m, local l" . - " WHERE m.uid = l.uid" . - " HAVING status=2 or status=3 ORDER BY status DESC, expiry;")) { + " CASE WHEN m.duration IS NULL THEN 0" . + " WHEN m.renewed + INTERVAL m.duration MONTH <= NOW() THEN 3" . + " WHEN m.renewed <= NOW() THEN 2" . + " ELSE 1 END 'status' FROM membres m, local l" . + " WHERE m.uid = l.uid" . + " HAVING status=2 or status=3 ORDER BY status DESC, expiry;")) { return false; } else { $res = array(); @@ -1171,7 +1171,7 @@ EOF; if (!in_array($L_NS1 . ".", $out) || !in_array($L_NS2 . ".", $out)) { $errno = 1; $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"; } } } diff --git a/bureau/class/m_authip.php b/bureau/class/m_authip.php index 76bec299..fdffb35e 100644 --- a/bureau/class/m_authip.php +++ b/bureau/class/m_authip.php @@ -1,25 +1,25 @@ next_record()) { $r[$db->f('id')] = $db->Record; if ((checkip($db->f('ip')) && $db->f('subnet') == 32) || - (checkipv6($db->f('ip')) && $db->f('subnet') == 128)) { + (checkipv6($db->f('ip')) && $db->f('subnet') == 128)) { $r[$db->f('id')]['ip_human'] = $db->f('ip'); } else { $r[$db->f('id')]['ip_human'] = $db->f('ip') . "/" . $db->f('subnet'); @@ -216,7 +216,7 @@ class m_authip { } $id = intval($id); - $infos = $db->quote(trim($infos)); + $infos = $db->quote(trim($infos)); // Extract subnet from ipsub $tmp = explode('/', $ipsub); diff --git a/bureau/class/m_bro.php b/bureau/class/m_bro.php index 343f0d7e..d6968922 100644 --- a/bureau/class/m_bro.php +++ b/bureau/class/m_bro.php @@ -22,7 +22,7 @@ ---------------------------------------------------------------------- Purpose of file: file browser class. ---------------------------------------------------------------------- - */ +*/ /* Add the mime type list */ @include("mime.php"); @@ -213,8 +213,8 @@ class m_bro { if ($file != "." && $file != "..") { $stat=stat($absolute . "/" . $file); $c[] = array("name" => $file, "size" => $this->fsize($absolute . "/" . $file, $showdirsize), - "date" => filemtime($absolute . "/" . $file), "type" => (!is_dir($absolute . "/" . $file)), - "permissions" => $stat[2] ); + "date" => filemtime($absolute . "/" . $file), "type" => (!is_dir($absolute . "/" . $file)), + "permissions" => $stat[2] ); } } closedir($dir); @@ -245,22 +245,22 @@ class m_bro { } /** - Modifie les prfrences de l'utilisateur courant. - * - * @global m_mysql $db - * @global int $cuid - * @param integer $editsizex Taille de l'diteur (nombre de colonnes) - * @param integer $editsizey Taille de l'diteur (nombre de lignes) - * @param integer $listmode Mode d'affichage de la liste 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 $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 $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 $golastdir Faut-il revenir la racine ou au dernier dossier visit ? - * @return boolean - */ + Modifie les prfrences de l'utilisateur courant. + * + * @global m_mysql $db + * @global int $cuid + * @param integer $editsizex Taille de l'diteur (nombre de colonnes) + * @param integer $editsizey Taille de l'diteur (nombre de lignes) + * @param integer $listmode Mode d'affichage de la liste 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 $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 $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 $golastdir Faut-il revenir la racine ou au dernier dossier visit ? + * @return boolean + */ function SetPrefs($editsizex, $editsizey, $listmode, $showicons, $downfmt, $createfile, $showtype, $editor_font, $editor_size, $golastdir) { global $db, $cuid; $editsizex = intval($editsizex); @@ -612,18 +612,18 @@ class m_bro { // there was an error, raise it $msg->log("bro", "uploadfile", "Problem when uploading a file"); switch ($_FILES['userfile']['error']) { - case UPLOAD_ERR_INI_SIZE: - $erstr = _("The uploaded file exceeds the max file size allowed"); - break; - case UPLOAD_ERR_FORM_SIZE: - case UPLOAD_ERR_PARTIAL: - case UPLOAD_ERR_NO_FILE: - case UPLOAD_ERR_NO_TMP_DIR: - case UPLOAD_ERR_CANT_WRITE: - case UPLOAD_ERR_EXTENSION: - default: - $erstr = _("Undefined error ") . $_FILES['userfile']['error']; - break; + case UPLOAD_ERR_INI_SIZE: + $erstr = _("The uploaded file exceeds the max file size allowed"); + break; + case UPLOAD_ERR_FORM_SIZE: + case UPLOAD_ERR_PARTIAL: + case UPLOAD_ERR_NO_FILE: + case UPLOAD_ERR_NO_TMP_DIR: + case UPLOAD_ERR_CANT_WRITE: + case UPLOAD_ERR_EXTENSION: + default: + $erstr = _("Undefined error ") . $_FILES['userfile']['error']; + break; } $msg->raise("ERROR", "bro", _("Error during the upload of the file: ") . $erstr); return false; @@ -686,7 +686,7 @@ class m_bro { if ($ret) { $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; } @@ -904,21 +904,21 @@ class m_bro { if (($parts = explode(".", $name))) { $ext = array_pop($parts); switch ($ext) { - case "gz": - case "bz": - case "bz2": - $ext = array_pop($parts) . $ext; - /* FALLTHROUGH */ - case "tar.gz": - case "tar.bz": - case "tar.bz2": - case "tgz": - case "tbz": - case "tbz2": - case "tar": - case "Z": - case "zip": - return true; + case "gz": + case "bz": + case "bz2": + $ext = array_pop($parts) . $ext; + /* FALLTHROUGH */ + case "tar.gz": + case "tar.bz": + case "tar.bz2": + case "tgz": + case "tbz": + case "tbz2": + case "tar": + case "Z": + case "zip": + return true; } } return false; @@ -1006,7 +1006,7 @@ class m_bro { $msg->raise("ERROR", "bro", _("File or folder name is incorrect")); return false; } - return true; + return true; } /** @@ -1074,7 +1074,7 @@ class m_bro { header("Content-Transfer-Encoding: binary"); $d = $this->convertabsolute($dir, false); set_time_limit(0); - chdir(dirname($d)); + chdir(dirname($d)); passthru("/usr/bin/zip -r - ".escapeshellarg(basename($d))); } diff --git a/bureau/class/m_cron.php b/bureau/class/m_cron.php index 721581f2..6a6e2944 100644 --- a/bureau/class/m_cron.php +++ b/bureau/class/m_cron.php @@ -22,7 +22,7 @@ ---------------------------------------------------------------------- Purpose of file: Manage hook system. ---------------------------------------------------------------------- - */ +*/ /** * This class manage web-cron tasks @@ -78,7 +78,7 @@ class m_cron { 'ico' => 'images/schedule.png', 'link' => 'cron.php', 'pos' => 120, - ); + ); return $obj; } @@ -163,8 +163,8 @@ class m_cron { if (!$db->next_record()) { return "false"; } // return false if pb - if ($db->f('uid') != $cuid) { - $msg->raise("ERROR", "cron", _("Identity problem")); + if ($db->f('uid') != $cuid) { + $msg->raise("ERROR", "cron", _("Identity problem")); return false; } } @@ -304,11 +304,11 @@ class m_cron { // add additional curl options here $std_options = array(CURLOPT_RETURNTRANSFER => true, - CURLOPT_FOLLOWLOCATION => false, - CURLOPT_CONNECTTIMEOUT => 5, - CURLOPT_TIMEOUT => 240, // 4 minutes timeout for a page - CURLOPT_USERAGENT => "AlternC (Cron Daemon)", - CURLOPT_MAXREDIRS => 0); + CURLOPT_FOLLOWLOCATION => false, + CURLOPT_CONNECTTIMEOUT => 5, + CURLOPT_TIMEOUT => 240, // 4 minutes timeout for a page + CURLOPT_USERAGENT => "AlternC (Cron Daemon)", + CURLOPT_MAXREDIRS => 0); if ($GLOBALS["DEBUG"]) { $std_options[CURLOPT_VERBOSE] = true; diff --git a/bureau/class/m_crypto.php b/bureau/class/m_crypto.php index de8d15fb..a14e63c0 100644 --- a/bureau/class/m_crypto.php +++ b/bureau/class/m_crypto.php @@ -4,27 +4,27 @@ class m_crypto { function encrypt($sValue, $sSecretKey) { return rtrim( - base64_encode( - mcrypt_encrypt( - MCRYPT_RIJNDAEL_256, $sSecretKey, $sValue, MCRYPT_MODE_ECB, mcrypt_create_iv( - mcrypt_get_iv_size( - MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB - ), MCRYPT_RAND - ) - ) - ), "\0" + base64_encode( + mcrypt_encrypt( + MCRYPT_RIJNDAEL_256, $sSecretKey, $sValue, MCRYPT_MODE_ECB, mcrypt_create_iv( + mcrypt_get_iv_size( + MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB + ), MCRYPT_RAND + ) + ) + ), "\0" ); } function decrypt($sValue, $sSecretKey) { return rtrim( - mcrypt_decrypt( - MCRYPT_RIJNDAEL_256, $sSecretKey, base64_decode($sValue), MCRYPT_MODE_ECB, mcrypt_create_iv( - mcrypt_get_iv_size( - MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB - ), MCRYPT_RAND - ) - ), "\0" + mcrypt_decrypt( + MCRYPT_RIJNDAEL_256, $sSecretKey, base64_decode($sValue), MCRYPT_MODE_ECB, mcrypt_create_iv( + mcrypt_get_iv_size( + MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB + ), MCRYPT_RAND + ) + ), "\0" ); } diff --git a/bureau/class/m_debug_alternc.php b/bureau/class/m_debug_alternc.php index b8e38bdc..9e0e3e35 100644 --- a/bureau/class/m_debug_alternc.php +++ b/bureau/class/m_debug_alternc.php @@ -1,6 +1,7 @@ 'FQDN', 'type' => 'string')); } + function get_panel_url_list() { global $db, $msg; $msg->log("dom", "get_panel_url_list"); @@ -101,6 +98,7 @@ class m_dom { return $t; } + /** * @param string $fqdn */ @@ -114,6 +112,11 @@ class m_dom { return array('sub_id' => intval($db->f('id')), 'member_id' => intval($db->f('compte'))); } + + /** + * hook function called by the menu class + * to add menu to the left panel + */ function hook_menu() { global $quota; $obj = array( @@ -142,7 +145,6 @@ class m_dom { return $obj; } - /* ----------------------------------------------------------------- */ /** * Retourne un tableau contenant les types de domaines @@ -163,6 +165,7 @@ class m_dom { return $this->cache_domains_type_lst; } + function domains_type_enable_values() { global $db, $msg, $cuid; $msg->log("dom", "domains_type_target_values"); @@ -179,6 +182,7 @@ class m_dom { return $r; } + /** * @param integer $type */ @@ -206,6 +210,7 @@ class m_dom { } } + function import_manual_dns_zone($zone, $domain, $detect_redirect = true, $save = false) { global $msg; if ($save) { @@ -226,6 +231,7 @@ class m_dom { return $val; } + /** * @param string $zone */ @@ -256,150 +262,150 @@ class m_dom { $val['status'] = 'ok'; $val['comment'] = 'Just a comment, do not import'; } else - // Examples: - // $TTL 86400' - if (preg_match('/^\$TTL\h+(?P[\dMHDmhd]+)/', $zone, $ret)) { - $val['status'] = 'ok'; - $val['comment'] = 'Set TTL to ' . $ret['ttl']; - $val['entry_new']['type'] = 'set_ttl'; - $val['entry_new']['value'] = $ret['ttl']; - } else - - // Examples: - // @ IN AAAA 127.2.1.5 - // reseau IN AAAA 145.214.44.55 - if (preg_match('/^(?P[\w\.@\-]*)\h*(?P\d*)\h*IN\h+AAAA\h+(?P[0-9A-F:]{2,40})/i', $zone, $ret)) { - - // Check if it is just a redirect - if (substr($ret['sub'], -1) == '.') { // if ending by a "." it is allready a FQDN - $url = "http://" . $ret['sub']; - } else { - if ($ret['sub'] == '@' || empty($ret['sub'])) { - $url = "http://" . $domain; - } else { - $url = "http://" . $ret['sub'] . "." . $domain; - } - } - if ($detect_redirect && $dst_url = $this->is_it_a_redirect($url)) { - $val['status'] = 'warn'; - $val['comment'] = "Became a redirect to $dst_url"; - $val['entry_new']['type'] = 'URL'; - $val['entry_new']['sub'] = $ret['sub']; - $val['entry_new']['value'] = $dst_url; - } else { + // Examples: + // $TTL 86400' + if (preg_match('/^\$TTL\h+(?P[\dMHDmhd]+)/', $zone, $ret)) { $val['status'] = 'ok'; - $val['comment'] = "Create entry AAAA with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl']; - $val['entry_new']['type'] = 'IPV6'; - $val['entry_new']['sub'] = $ret['sub']; - $val['entry_new']['value'] = $ret['target']; - } - } else + $val['comment'] = 'Set TTL to ' . $ret['ttl']; + $val['entry_new']['type'] = 'set_ttl'; + $val['entry_new']['value'] = $ret['ttl']; + } else + + // Examples: + // @ IN AAAA 127.2.1.5 + // reseau IN AAAA 145.214.44.55 + if (preg_match('/^(?P[\w\.@\-]*)\h*(?P\d*)\h*IN\h+AAAA\h+(?P[0-9A-F:]{2,40})/i', $zone, $ret)) { + + // Check if it is just a redirect + if (substr($ret['sub'], -1) == '.') { // if ending by a "." it is allready a FQDN + $url = "http://" . $ret['sub']; + } else { + if ($ret['sub'] == '@' || empty($ret['sub'])) { + $url = "http://" . $domain; + } else { + $url = "http://" . $ret['sub'] . "." . $domain; + } + } + if ($detect_redirect && $dst_url = $this->is_it_a_redirect($url)) { + $val['status'] = 'warn'; + $val['comment'] = "Became a redirect to $dst_url"; + $val['entry_new']['type'] = 'URL'; + $val['entry_new']['sub'] = $ret['sub']; + $val['entry_new']['value'] = $dst_url; + } else { + $val['status'] = 'ok'; + $val['comment'] = "Create entry AAAA with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl']; + $val['entry_new']['type'] = 'IPV6'; + $val['entry_new']['sub'] = $ret['sub']; + $val['entry_new']['value'] = $ret['target']; + } + } else - // Examples: - // @ IN A 127.2.1.5 - // reseau IN A 145.214.44.55 - if (preg_match('/^(?P[\w\.@\-]*)\h*(?P\d*)\h*IN\h+A\h+(?P\d+\.\d+\.\d+\.\d+)/i', $zone, $ret)) { - // Check if it is just a redirect - if (substr($ret['sub'], -1) == '.') { // if ending by a "." it is allready a FQDN - $url = "http://" . $ret['sub']; - } else { - if ($ret['sub'] == '@' || empty($ret['sub'])) { - $url = "http://" . $domain; - } else { - $url = "http://" . $ret['sub'] . "." . $domain; - } - } - if ($detect_redirect && $dst_url = $this->is_it_a_redirect($url)) { - $val['status'] = 'warn'; - $val['comment'] = "Became a redirect to $dst_url"; - $val['entry_new']['type'] = 'URL'; - $val['entry_new']['sub'] = $ret['sub']; - $val['entry_new']['value'] = $dst_url; - } else { - $val['status'] = 'ok'; - $val['comment'] = "Create entry A with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl']; - $val['entry_new']['type'] = 'IP'; - $val['entry_new']['sub'] = $ret['sub']; - $val['entry_new']['value'] = $ret['target']; - } - } else + // Examples: + // @ IN A 127.2.1.5 + // reseau IN A 145.214.44.55 + if (preg_match('/^(?P[\w\.@\-]*)\h*(?P\d*)\h*IN\h+A\h+(?P\d+\.\d+\.\d+\.\d+)/i', $zone, $ret)) { + // Check if it is just a redirect + if (substr($ret['sub'], -1) == '.') { // if ending by a "." it is allready a FQDN + $url = "http://" . $ret['sub']; + } else { + if ($ret['sub'] == '@' || empty($ret['sub'])) { + $url = "http://" . $domain; + } else { + $url = "http://" . $ret['sub'] . "." . $domain; + } + } + if ($detect_redirect && $dst_url = $this->is_it_a_redirect($url)) { + $val['status'] = 'warn'; + $val['comment'] = "Became a redirect to $dst_url"; + $val['entry_new']['type'] = 'URL'; + $val['entry_new']['sub'] = $ret['sub']; + $val['entry_new']['value'] = $dst_url; + } else { + $val['status'] = 'ok'; + $val['comment'] = "Create entry A with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl']; + $val['entry_new']['type'] = 'IP'; + $val['entry_new']['sub'] = $ret['sub']; + $val['entry_new']['value'] = $ret['target']; + } + } else - // Examples: - // @ IN NS ns.example.tld. - // ns 3600 IN NS 145.214.44.55 - if (preg_match('/^(?P[\-\w\.@]*)\h*(?P\d*)\h*IN\h+NS\h+(?P[\w\.\-]+)/i', $zone, $ret)) { - if (empty($ret['sub']) || $ret['sub'] == '@') { - $val['status'] = 'warn'; - $val['comment'] = "Won't migrate it, there will get a new value"; - } else { - $val['status'] = 'ok'; - $val['comment'] = "Create entry NS with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl']; - $val['entry_new']['type'] = 'FIXME-NS'; - $val['entry_new']['sub'] = $ret['sub']; - $val['entry_new']['value'] = $ret['target']; - } - } else + // Examples: + // @ IN NS ns.example.tld. + // ns 3600 IN NS 145.214.44.55 + if (preg_match('/^(?P[\-\w\.@]*)\h*(?P\d*)\h*IN\h+NS\h+(?P[\w\.\-]+)/i', $zone, $ret)) { + if (empty($ret['sub']) || $ret['sub'] == '@') { + $val['status'] = 'warn'; + $val['comment'] = "Won't migrate it, there will get a new value"; + } else { + $val['status'] = 'ok'; + $val['comment'] = "Create entry NS with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl']; + $val['entry_new']['type'] = 'FIXME-NS'; + $val['entry_new']['sub'] = $ret['sub']; + $val['entry_new']['value'] = $ret['target']; + } + } else - // Examples: - // agenda IN CNAME ghs.google.com. - // www 3600 IN CNAME @ - if (preg_match('/^(?P[\-\w\.@]*)\h*(?P\d*)\h*IN\h+CNAME\h+(?P[@\w+\.\-]+)/i', $zone, $ret)) { - if (substr($ret['sub'], -1) == '.') { // if ending by a "." it is allready a FQDN - $url = "http://" . $ret['sub']; - } else { - if ($ret['sub'] == '@' || empty($ret['sub'])) { - $url = "http://" . $domain; - } else { - $url = "http://" . $ret['sub'] . "." . $domain; - } - } - if ($detect_redirect && $dst_url = $this->is_it_a_redirect($url)) { - $val['status'] = 'warn'; - $val['comment'] = "Became a redirect to $dst_url"; - $val['entry_new']['type'] = 'URL'; - $val['entry_new']['sub'] = $ret['sub']; - $val['entry_new']['value'] = $dst_url; - } else { - $val['status'] = 'ok'; - $val['comment'] = "Create entry CNAME with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl']; - $val['entry_new']['type'] = 'CNAME'; - $val['entry_new']['sub'] = $ret['sub']; - $val['entry_new']['value'] = $ret['target']; - } - } else + // Examples: + // agenda IN CNAME ghs.google.com. + // www 3600 IN CNAME @ + if (preg_match('/^(?P[\-\w\.@]*)\h*(?P\d*)\h*IN\h+CNAME\h+(?P[@\w+\.\-]+)/i', $zone, $ret)) { + if (substr($ret['sub'], -1) == '.') { // if ending by a "." it is allready a FQDN + $url = "http://" . $ret['sub']; + } else { + if ($ret['sub'] == '@' || empty($ret['sub'])) { + $url = "http://" . $domain; + } else { + $url = "http://" . $ret['sub'] . "." . $domain; + } + } + if ($detect_redirect && $dst_url = $this->is_it_a_redirect($url)) { + $val['status'] = 'warn'; + $val['comment'] = "Became a redirect to $dst_url"; + $val['entry_new']['type'] = 'URL'; + $val['entry_new']['sub'] = $ret['sub']; + $val['entry_new']['value'] = $dst_url; + } else { + $val['status'] = 'ok'; + $val['comment'] = "Create entry CNAME with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl']; + $val['entry_new']['type'] = 'CNAME'; + $val['entry_new']['sub'] = $ret['sub']; + $val['entry_new']['value'] = $ret['target']; + } + } else - // Examples: - // @ IN MX 10 aspmx.l.google.com. - // arf 3600 IN MX 20 pouet.fr. - if (preg_match('/^(?P[\-\w\.@]*)\h*(?P\d*)\h*IN\h+MX\h+(?P\d+)\h+(?P[@\w+\.\-]+)/i', $zone, $ret)) { - $val['status'] = 'warn'; - $val['comment'] = "Create entry MX with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl'] . " and weight 5 (initial weight was " . $ret['weight'] . ")"; - $val['entry_new']['type'] = 'MX'; - $val['entry_new']['sub'] = $ret['sub']; - $val['entry_new']['value'] = $ret['target']; - } else + // Examples: + // @ IN MX 10 aspmx.l.google.com. + // arf 3600 IN MX 20 pouet.fr. + if (preg_match('/^(?P[\-\w\.@]*)\h*(?P\d*)\h*IN\h+MX\h+(?P\d+)\h+(?P[@\w+\.\-]+)/i', $zone, $ret)) { + $val['status'] = 'warn'; + $val['comment'] = "Create entry MX with " . $ret['sub'] . " go to " . $ret['target'] . " with ttl " . $ret['ttl'] . " and weight 5 (initial weight was " . $ret['weight'] . ")"; + $val['entry_new']['type'] = 'MX'; + $val['entry_new']['sub'] = $ret['sub']; + $val['entry_new']['value'] = $ret['target']; + } else - // Examples: - // _sip._tcp IN SRV 1 100 5061 sip.example.tld. - if (preg_match('/^(?P[\_\w\.@\-]+)\h+(?P\d*)\h*IN\h+SRV\h+/i', $zone, $ret)) { - $val['status'] = 'err'; - $val['comment'] = "Please add yourself the entry $zone"; - } else + // Examples: + // _sip._tcp IN SRV 1 100 5061 sip.example.tld. + if (preg_match('/^(?P[\_\w\.@\-]+)\h+(?P\d*)\h*IN\h+SRV\h+/i', $zone, $ret)) { + $val['status'] = 'err'; + $val['comment'] = "Please add yourself the entry $zone"; + } else - // Examples: - // @ IN TXT "google-site-verification=jjjjjjjjjjjjjjjjjjjjjjjjsdsdjlksjdljdslgNj5" - if (preg_match('/^(?P[\_\w\.@\-]*)\h*(?P\d*)\h*IN\h+TXT\h+\"(?P.+)\"/i', $zone, $ret)) { - $val['status'] = 'ok'; - $val['comment'] = "Create TXT entry with " . $ret['sub'] . " go to " . $ret['target']; - $val['entry_new']['type'] = 'TXT'; - $val['entry_new']['sub'] = $ret['sub']; - $val['entry_new']['value'] = $ret['target']; - } else { + // Examples: + // @ IN TXT "google-site-verification=jjjjjjjjjjjjjjjjjjjjjjjjsdsdjlksjdljdslgNj5" + if (preg_match('/^(?P[\_\w\.@\-]*)\h*(?P\d*)\h*IN\h+TXT\h+\"(?P.+)\"/i', $zone, $ret)) { + $val['status'] = 'ok'; + $val['comment'] = "Create TXT entry with " . $ret['sub'] . " go to " . $ret['target']; + $val['entry_new']['type'] = 'TXT'; + $val['entry_new']['sub'] = $ret['sub']; + $val['entry_new']['value'] = $ret['target']; + } else { - // WTF can it be ? - $val['comment'] = "Unknow: $zone"; - } + // WTF can it be ? + $val['comment'] = "Unknow: $zone"; + } if ($save) { return $this->import_manual_dns_entry_doit($val); @@ -408,6 +414,7 @@ class m_dom { return $val; } + private function import_manual_dns_entry_doit($entry) { $entry['did_it'] = 0; if ($entry['status'] == 'err') { @@ -421,9 +428,9 @@ class m_dom { } switch ($val['type']) { - case "set_ttl": - $entry['did_it'] = $this->set_ttl($this->get_domain_byname($val['domain']), $val['value']); - return $entry; + case "set_ttl": + $entry['did_it'] = $this->set_ttl($this->get_domain_byname($val['domain']), $val['value']); + return $entry; } // If it is an unknown domains type @@ -445,6 +452,7 @@ class m_dom { return $entry; } + private function import_manual_dns_prep_zone($domain) { global $msg; // Prepare a domain to be importer : @@ -472,6 +480,7 @@ class m_dom { return true; } + // Take an URL, and return FALSE is there is no redirection, // and the target URL if there is one (HTTP CODE 301 & 302) // CURL is needed @@ -482,8 +491,8 @@ class m_dom { function is_it_a_redirect($url) { try { $params = array('http' => array( - 'method' => 'HEAD', - 'ignore_errors' => true + 'method' => 'HEAD', + 'ignore_errors' => true )); $context = stream_context_create($params); @@ -518,6 +527,7 @@ class m_dom { } } + function domains_type_regenerate($name) { global $db, $msg, $cuid; $db->query("update sub_domaines set web_action='UPDATE' where lower(type) = lower(?) ;", array($name)); @@ -525,6 +535,7 @@ class m_dom { return true; } + function domains_type_get($name) { global $db; $db->query("select * from domaines_type where name= ?;", array($name)); @@ -532,12 +543,14 @@ class m_dom { return $db->Record; } + function domains_type_del($name) { global $db; $db->query("delete domaines_type where name= ? ;", array($name)); return true; } + function domains_type_update($name, $description, $target, $entry, $compatibility, $enable, $only_dns, $need_dns, $advanced, $create_tmpdir, $create_targetdir) { global $msg, $db; // The name MUST contain only letter and digits, it's an identifier after all ... @@ -554,6 +567,7 @@ class m_dom { return true; } + function sub_domain_change_status($sub_id, $status) { global $db, $msg; $msg->log("dom", "sub_domain_change_status"); @@ -577,7 +591,6 @@ class m_dom { return true; } - /* ----------------------------------------------------------------- */ /** * Retourne un tableau contenant les domaines d'un membre. @@ -613,7 +626,6 @@ class m_dom { return true; } - /* ----------------------------------------------------------------- */ /** * Efface un domaine du membre courant, et tous ses sous-domaines @@ -652,11 +664,11 @@ class m_dom { return true; } + function domshort($dom, $sub = "") { return str_replace("-", "", str_replace(".", "", empty($sub) ? "" : "$sub.") . $dom); } - /* ----------------------------------------------------------------- */ /** * Installe un domaine sur le compte courant. @@ -799,6 +811,7 @@ class m_dom { return true; } + /** * @param string $domain */ @@ -823,6 +836,7 @@ class m_dom { } } + /** * @param string $domain */ @@ -830,12 +844,14 @@ class m_dom { return "/www/" . $this->domshort($domain); } + function dump_axfr($domain, $ns = 'localhost') { $axfr = array(); exec('/usr/bin/dig AXFR "' . escapeshellcmd($domain) . '" @"' . escapeshellcmd($ns) . '"', $axfr); return $axfr; } + function lst_default_subdomains() { global $db, $msg; $msg->log("dom", "lst_default_subdomains"); @@ -844,17 +860,18 @@ class m_dom { while ($db->next_record()) { $c[] = array('id' => $db->f('id'), - 'sub' => $db->f('sub'), - 'domain_type' => $db->f('domain_type'), - 'domain_type_parameter' => $db->f('domain_type_parameter'), - 'concerned' => $db->f('concerned'), - 'enabled' => $db->f('enabled') + 'sub' => $db->f('sub'), + 'domain_type' => $db->f('domain_type'), + 'domain_type_parameter' => $db->f('domain_type_parameter'), + 'concerned' => $db->f('concerned'), + 'enabled' => $db->f('enabled') ); } return $c; } + function update_default_subdomains($arr) { global $msg; $msg->log("dom", "update_default_subdomains"); @@ -876,6 +893,7 @@ class m_dom { return $ok; } + function update_one_default($domain_type, $sub, $domain_type_parameter, $concerned, $enabled, $id = null) { global $db, $msg; $msg->log("dom", "update_one_default"); @@ -889,6 +907,7 @@ class m_dom { //update } + function del_default_type($id) { global $msg, $db; $msg->log("dom", "del_default_type"); @@ -901,7 +920,6 @@ class m_dom { return true; } - /* ----------------------------------------------------------------- */ /** * Retourne les entrées DNS du domaine $domain issues du WHOIS. @@ -943,12 +961,12 @@ class m_dom { $egal = ""; switch ($ext) { - case "net": - $egal = "="; - break; - case "name": - $egal = "domain = "; - break; + case "net": + $egal = "="; + break; + case "name": + $egal = "domain = "; + break; } $serveurList = array(); // pour ajouter un nouveau TLD, utiliser le code ci-dessous. @@ -962,105 +980,105 @@ class m_dom { // pour ajouter un nouveau TLD, utiliser le code ci-dessous. // echo "| $ligne
"; switch ($ext) { - case "org": - case "com": - case "net": - case "info": - case "biz": - case "name": - case "cc": - if (preg_match("#Name Server:#", $ligne)) { - $found = true; - $tmp = strtolower(str_replace(chr(10), "", str_replace(chr(13), "", str_replace(" ", "", str_replace("Name Server:", "", $ligne))))); - if ($tmp) { - $serveurList[] = $tmp; - } - } - break; - case "co": - if (preg_match("#Name Server:#", $ligne)) { - $found = true; - $tmp = strtolower(str_replace(chr(10), "", str_replace(chr(13), "", str_replace(" ", "", str_replace("Name Server:", "", $ligne))))); - if ($tmp) - $serveurList[] = $tmp; - } - break; - case "cx": - $ligne = str_replace(chr(10), "", str_replace(chr(13), "", str_replace(" ", "", $ligne))); - if ($ligne == "" && $state == 1) { - $state = 2; - } - if ($state == 1) { - $serveurList[] = strtolower($ligne); - } - if ($ligne == "Nameservers:" && $state == 0) { - $state = 1; - $found = true; - } - break; - case "eu": - case "be": - $ligne = preg_replace("/^ *([^ ]*) \(.*\)$/", "\\1", trim($ligne)); - $tmp=""; - if ($found) { - $tmp = trim($ligne); - } + case "org": + case "com": + case "net": + case "info": + case "biz": + case "name": + case "cc": + if (preg_match("#Name Server:#", $ligne)) { + $found = true; + $tmp = strtolower(str_replace(chr(10), "", str_replace(chr(13), "", str_replace(" ", "", str_replace("Name Server:", "", $ligne))))); if ($tmp) { $serveurList[] = $tmp; } - if ($ligne == "Nameservers:") { - $state = 1; - $found = true; + } + break; + case "co": + if (preg_match("#Name Server:#", $ligne)) { + $found = true; + $tmp = strtolower(str_replace(chr(10), "", str_replace(chr(13), "", str_replace(" ", "", str_replace("Name Server:", "", $ligne))))); + if ($tmp) + $serveurList[] = $tmp; + } + break; + case "cx": + $ligne = str_replace(chr(10), "", str_replace(chr(13), "", str_replace(" ", "", $ligne))); + if ($ligne == "" && $state == 1) { + $state = 2; + } + if ($state == 1) { + $serveurList[] = strtolower($ligne); + } + if ($ligne == "Nameservers:" && $state == 0) { + $state = 1; + $found = true; + } + break; + case "eu": + case "be": + $ligne = preg_replace("/^ *([^ ]*) \(.*\)$/", "\\1", trim($ligne)); + $tmp=""; + if ($found) { + $tmp = trim($ligne); + } + if ($tmp) { + $serveurList[] = $tmp; + } + if ($ligne == "Nameservers:") { + $state = 1; + $found = true; + } + break; + case "im": + if (preg_match('/Name Server:/', $ligne)) { + $found = true; + // weird regexp (trailing garbage after name server), but I could not make it work otherwise + $tmp = strtolower(preg_replace('/Name Server: ([^ ]+)\..$/', "\\1", $ligne)); + $tmp = preg_replace('/[^-_a-z0-9\.]/', '', $tmp); + if ($tmp) { + $serveurList[] = $tmp; } - break; - case "im": - if (preg_match('/Name Server:/', $ligne)) { - $found = true; - // weird regexp (trailing garbage after name server), but I could not make it work otherwise - $tmp = strtolower(preg_replace('/Name Server: ([^ ]+)\..$/', "\\1", $ligne)); - $tmp = preg_replace('/[^-_a-z0-9\.]/', '', $tmp); - if ($tmp) { - $serveurList[] = $tmp; - } + } + break; + case "it": + if (preg_match("#nserver:#", $ligne)) { + $found = true; + $tmp = strtolower(preg_replace("/nserver:\s*[^ ]*\s*([^\s]*)$/", "\\1", $ligne)); + if ($tmp) { + $serveurList[] = $tmp; } - break; - case "it": - if (preg_match("#nserver:#", $ligne)) { - $found = true; - $tmp = strtolower(preg_replace("/nserver:\s*[^ ]*\s*([^\s]*)$/", "\\1", $ligne)); - if ($tmp) { - $serveurList[] = $tmp; - } - } - break; - case "fr": - case "re": - if (preg_match("#nserver:#", $ligne)) { - $found = true; - $tmp = strtolower(preg_replace("#nserver:\s*([^\s]*)\s*.*$#", "\\1", $ligne)); - if ($tmp) { - $serveurList[] = $tmp; - } - } - break; - case "ca": - case "ws"; - if (preg_match('#Name servers#', $ligne)) { - // found the server - $state = 1; - } elseif ($state) { - if (preg_match('#^[^%]#', $ligne) && $ligne = preg_replace('#[[:space:]]#', "", $ligne)) { - // first non-whitespace line is considered to be the nameservers themselves - $found = true; - $serveurList[] = $ligne; - } - } - break; - case "coop": - if (preg_match('#Host Name:\s*([^\s]+)#', $ligne, $matches)) { - $found = true; - $serveurList[] = $matches[1]; + } + break; + case "fr": + case "re": + if (preg_match("#nserver:#", $ligne)) { + $found = true; + $tmp = strtolower(preg_replace("#nserver:\s*([^\s]*)\s*.*$#", "\\1", $ligne)); + if ($tmp) { + $serveurList[] = $tmp; } + } + break; + case "ca": + case "ws"; + if (preg_match('#Name servers#', $ligne)) { + // found the server + $state = 1; + } elseif ($state) { + if (preg_match('#^[^%]#', $ligne) && $ligne = preg_replace('#[[:space:]]#', "", $ligne)) { + // first non-whitespace line is considered to be the nameservers themselves + $found = true; + $serveurList[] = $ligne; + } + } + break; + case "coop": + if (preg_match('#Host Name:\s*([^\s]+)#', $ligne, $matches)) { + $found = true; + $serveurList[] = $matches[1]; + } } // switch } // while fclose($fp); @@ -1075,12 +1093,8 @@ class m_dom { $msg->raise("ALERT", "dom", _("The domain cannot be found in the Whois database")); return false; } - } + } // whois -// whois - - - /* ----------------------------------------------------------------- */ /** * vérifie la presence d'un champs mx valide sur un serveur DNS @@ -1127,7 +1141,6 @@ class m_dom { return 0; } - /* ----------------------------------------------------------------- */ /** * retourne TOUTES les infos d'un domaine @@ -1201,12 +1214,8 @@ class m_dom { } $db->free(); return $r; - } + } // get_domain_all -// get_domain_all - - - /* ----------------------------------------------------------------- */ /** * Retourne TOUTES les infos d'un sous domaine du compte courant. @@ -1246,9 +1255,8 @@ class m_dom { $r["web_action"] = $db->Record["web_action"]; $db->free(); return $r; - } + } // get_sub_domain_all -// get_sub_domain_all /** * @param integer $type @@ -1259,70 +1267,69 @@ class m_dom { // check the type we can have in domaines_type.target switch ($this->domains_type_target_values($type)) { - case 'NONE': - if (empty($value) or is_null($value)) { - return true; - } - break; - case 'URL': - if ($value == strval($value)) { - if (filter_var($value, FILTER_VALIDATE_URL)) { - return true; - } else { - $msg->raise("ERROR", "dom", _("invalid url")); - return false; - } - } - break; - case 'DIRECTORY': - if (substr($value, 0, 1) != "/") { - $value = "/" . $value; - } - if (!checkuserpath($value)) { - $msg->raise("ERROR", "dom", _("The folder you entered is incorrect or does not exist")); - return false; - } + case 'NONE': + if (empty($value) or is_null($value)) { return true; - case 'IP': - if (checkip($value)) { + } + break; + case 'URL': + if ($value == strval($value)) { + if (filter_var($value, FILTER_VALIDATE_URL)) { return true; } else { - $msg->raise("ERROR", "dom", _("The ip address is invalid")); + $msg->raise("ERROR", "dom", _("invalid url")); return false; } - break; - case 'IPV6': - if (checkipv6($value)) { - return true; - } else { - $msg->raise("ERROR", "dom", _("The ip address is invalid")); - return false; - } - break; - case 'DOMAIN': - if (checkcname($value)) { - return true; - } else { - $msg->raise("ERROR", "dom", _("The name you entered is incorrect or not fully qualified (it must end with a DOT, like example.com.)")); - return false; - } - break; - case 'TXT': - if ($value == strval($value)) { - return true; - } else { - $msg->raise("ERROR", "dom", _("The TXT value you entered is incorrect")); - return false; - } - break; - default: - $msg->raise("ERROR", "dom", _("Invalid domain type selected, please check")); + } + break; + case 'DIRECTORY': + if (substr($value, 0, 1) != "/") { + $value = "/" . $value; + } + if (!checkuserpath($value)) { + $msg->raise("ERROR", "dom", _("The folder you entered is incorrect or does not exist")); return false; + } + return true; + case 'IP': + if (checkip($value)) { + return true; + } else { + $msg->raise("ERROR", "dom", _("The ip address is invalid")); + return false; + } + break; + case 'IPV6': + if (checkipv6($value)) { + return true; + } else { + $msg->raise("ERROR", "dom", _("The ip address is invalid")); + return false; + } + break; + case 'DOMAIN': + if (checkcname($value)) { + return true; + } else { + $msg->raise("ERROR", "dom", _("The name you entered is incorrect or not fully qualified (it must end with a DOT, like example.com.)")); + return false; + } + break; + case 'TXT': + if ($value == strval($value)) { + return true; + } else { + $msg->raise("ERROR", "dom", _("The TXT value you entered is incorrect")); + return false; + } + break; + default: + $msg->raise("ERROR", "dom", _("Invalid domain type selected, please check")); + return false; } return false; } - /* ----------------------------------------------------------------- */ /** * Check the compatibility of the POSTed parameters with the chosen @@ -1353,7 +1360,7 @@ class m_dom { } } - // Forbidden to create a CNAME RR on the domain APEX (RFC 1912) + // Forbidden to create a CNAME RR on the domain APEX (RFC 1912) if ($type == 'cname' && $sub == '') return false; @@ -1361,7 +1368,6 @@ class m_dom { return true; } - /* ----------------------------------------------------------------- */ /** * Modifier les information du sous-domaine demandé. @@ -1399,7 +1405,7 @@ class m_dom { if (!$this->check_type_value($type, $dest)) { //plutot verifier si la chaine d'erreur est vide avant de raise sinon sa veut dire que l(erruer est deja remonté - // error raised by check_type_value + // error raised by check_type_value return false; } @@ -1455,7 +1461,6 @@ class m_dom { return true; } - /* ----------------------------------------------------------------- */ /** * Supprime le sous-domaine demandé @@ -1481,6 +1486,7 @@ class m_dom { return true; } + /** * @param integer $dom_id */ @@ -1496,7 +1502,6 @@ class m_dom { return $j; } - /* ----------------------------------------------------------------- */ /** * Modifie les information du domaine précisé. @@ -1535,7 +1540,7 @@ class m_dom { } } - # Can't have ttl == 0. There is also a check in function_dns + // Can't have ttl == 0. There is also a check in function_dns if ($ttl == 0) { $ttl = 86400; } @@ -1559,7 +1564,7 @@ class m_dom { return true; } - //si gestion mx uniquement, vérification du dns externe + // si gestion mx uniquement, vérification du dns externe if ($dns == "0" && $gesmx == "1" && !$force) { $vmx = $this->checkmx($dom); if ($vmx == 1) { @@ -1586,11 +1591,9 @@ class m_dom { return true; } - /* * ************************* */ - /* Slave dns ip managment */ - /* * ************************* */ - /* ----------------------------------------------------------------- */ + /* Slave dns ip managment */ + /** Return the list of ip addresses and classes that are allowed access to domain list * through AXFR Transfers from the bind server. @@ -1608,9 +1611,9 @@ class m_dom { return $res; } - /* ----------------------------------------------------------------- */ - /** Add an ip address (or a ip class) to the list of allowed slave ip access list. + /** + * Add an ip address (or a ip class) to the list of allowed slave ip access list. */ function add_slave_ip($ip, $class = "32") { global $db, $msg; @@ -1634,9 +1637,9 @@ class m_dom { return true; } - /* ----------------------------------------------------------------- */ - /** Remove an ip address (or a ip class) from the list of allowed slave ip access list. + /** + * Remove an ip address (or a ip class) from the list of allowed slave ip access list. */ function del_slave_ip($ip) { global $db, $msg; @@ -1651,9 +1654,9 @@ class m_dom { return true; } - /* ----------------------------------------------------------------- */ - /** Check for a slave account + /** + * Check for a slave account */ function check_slave_account($login, $pass) { global $db; @@ -1664,9 +1667,8 @@ class m_dom { return false; } - /* ----------------------------------------------------------------- */ - - /** Out (echo) the complete hosted domain list : + /** + * Out (echo) the complete hosted domain list : */ function echo_domain_list($integrity = false) { global $db; @@ -1683,9 +1685,9 @@ class m_dom { return true; } - /* ----------------------------------------------------------------- */ - /** Returns the complete hosted domain list : + /** + * Returns the complete hosted domain list : */ function get_domain_list($uid = -1) { global $db; @@ -1726,7 +1728,6 @@ class m_dom { return $res; } - /* ----------------------------------------------------------------- */ /** Returns the name of a domain for the current user, from it's domain_id * @param $dom_id integer the domain_id to search for @@ -1750,7 +1751,6 @@ class m_dom { } } - /* ----------------------------------------------------------------- */ /** Returns the id of a domain for the current user, from it's domain name * @param $domain string the domain name to search for @@ -1774,9 +1774,9 @@ class m_dom { } } - /* ----------------------------------------------------------------- */ - /** Count all domains, for all users + /** + * Count all domains, for all users */ function count_domains_all() { global $db; @@ -1788,9 +1788,9 @@ class m_dom { } } - /* ----------------------------------------------------------------- */ - /** Return the list of allowed slave accounts + /** + * Return the list of allowed slave accounts */ function enum_slave_account() { global $db; @@ -1805,9 +1805,9 @@ class m_dom { return $res; } - /* ----------------------------------------------------------------- */ - /** Add a slave account that will be allowed to access the domain list + /** + * Add a slave account that will be allowed to access the domain list */ function add_slave_account($login, $pass) { global $db, $msg; @@ -1820,9 +1820,9 @@ class m_dom { return true; } - /* ----------------------------------------------------------------- */ - /** Remove a slave account + /** + * Remove a slave account */ function del_slave_account($login) { global $db, $msg; @@ -1830,14 +1830,11 @@ class m_dom { return true; } - /* * ********** */ /* Private */ - /* * ********** */ - /* ----------------------------------------------------------------- */ - - /** Try to lock a domain + /** + * Try to lock a domain * @access private */ function lock() { @@ -1853,9 +1850,9 @@ class m_dom { return true; } - /* ----------------------------------------------------------------- */ - /** Unlock the cron for domain management + /** + * Unlock the cron for domain management * return true * @access private */ @@ -1869,9 +1866,9 @@ class m_dom { return true; } - /* ----------------------------------------------------------------- */ - /** Declare that a domain's emails are hosted in this server : + /** + * Declare that a domain's emails are hosted in this server : * This adds 2 MX entries in this domain (if required) */ function hook_dom_add_mx_domain($dom_id) { @@ -1885,7 +1882,6 @@ class m_dom { return true; } - /* ----------------------------------------------------------------- */ /** * Delete an account (all his domains) @@ -1900,9 +1896,9 @@ class m_dom { 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. * @param $name string name of the quota * @return integer the number of service used or false if an error occured * @access private @@ -1918,11 +1914,11 @@ class m_dom { return $q; } - /* --------------------------------------------------------------------- */ - /** Returns the global domain(s) configuration(s) of a particular user + /** + * Returns the global domain(s) configuration(s) of a particular user * No parameters needed - * */ + */ function alternc_export_conf() { global $msg; $msg->log("dom", "export"); @@ -1967,6 +1963,7 @@ class m_dom { return $str; } + /** * Return an array with all the needed parameters to generate conf * of a vhost. @@ -2023,6 +2020,7 @@ class m_dom { return $r; } + /** * Return an array with all informations of the domains_type * used to generate Apache conf. @@ -2046,7 +2044,11 @@ class m_dom { return $d; } -// Launch old fashionned hooks as there was in AlternC 1.0 + + /** + * Launch old fashionned hooks as there was in AlternC 1.0 + * @TODO: do we still need that? + */ function generate_conf_oldhook($action, $lst_sub, $sub_obj = null) { if (is_null($sub_obj)) { $sub_obj = $this->generation_parameters(null, false); @@ -2072,6 +2074,7 @@ class m_dom { } // foreach $lst_by_type } + /** * Generate apache configuration. * Die if a specific FQDN have 2 vhost conf. @@ -2124,7 +2127,10 @@ class m_dom { return $ret; } - // Return an array with the list of id of sub_domains waiting for an action + + /** + * Return an array with the list of id of sub_domains waiting for an action + */ function generation_todo() { global $db, $msg; $msg->log("dom", "generation_todo"); @@ -2136,20 +2142,22 @@ class m_dom { return $r; } + function subdomain_modif_are_done($sub_domain_id, $action) { global $db; $sub_domain_id = intval($sub_domain_id); switch (strtolower($action)) { - case "delete": - $sql = "DELETE FROM sub_domaines WHERE id =$sub_domain_id;"; - break; - default: - $sql = "UPDATE sub_domaines SET web_action='OK' WHERE id='$sub_domain_id'; "; + case "delete": + $sql = "DELETE FROM sub_domaines WHERE id =$sub_domain_id;"; + break; + default: + $sql = "UPDATE sub_domaines SET web_action='OK' WHERE id='$sub_domain_id'; "; } $db->query($sql); return true; } + /** * @param string $dns_action */ @@ -2159,13 +2167,13 @@ class m_dom { return true; } + function set_dns_result($domain, $dns_result) { global $db; $db->query("UPDATE domaines SET dns_result= ? WHERE domaine= ?; ", array($dns_result, $domain)); return true; } - /* ----------------------------------------------------------------- */ /** hook function called by AlternC-upnp to know which open * tcp or udp ports this class requires or suggests @@ -2179,8 +2187,11 @@ class m_dom { ); } - // List if there is problems in the domains. - // Problems can appear when editing domains type properties + + /** + * List if there is problems in the domains. + * Problems can appear when editing domains type properties + */ function get_problems($domain) { $this->lock(); $da = $this->get_domain_all($domain); @@ -2218,6 +2229,7 @@ class m_dom { return $errors; } + function default_domain_type() { // This function is only used to allow translation of default domain types: _("Locally hosted"); @@ -2236,6 +2248,4 @@ class m_dom { _("AlternC panel access"); } -} - -/* Class m_domains */ +} /* Class m_domains */ diff --git a/bureau/class/m_err.php b/bureau/class/m_err.php index e68d6adb..2b741426 100644 --- a/bureau/class/m_err.php +++ b/bureau/class/m_err.php @@ -1,155 +1,154 @@ Cette classe gère les erreurs qui peuvent apparaitre lors d'appels -* à l'API d'AlternC. Ces erreurs sont stockées sous la forme de 2 nombres -* (Classe ID et Numéro d'erreur) ainsi qu'un texte facultatif associé. -* Des textes d'erreurs localisés sont aussi disponibles.

-*

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 -*

-* Copyleft {@link http://alternc.net/ AlternC Team} -* -* @copyright AlternC-Team 2002-11-01 http://alternc.net/ -*/ + * Classe de gestion des erreurs apparaissant lors d'appels API. + * + *

Cette classe gère les erreurs qui peuvent apparaitre lors d'appels + * à l'API d'AlternC. Ces erreurs sont stockées sous la forme de 2 nombres + * (Classe ID et Numéro d'erreur) ainsi qu'un texte facultatif associé. + * Des textes d'erreurs localisés sont aussi disponibles.

+ *

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 + *

+ * Copyleft {@link http://alternc.net/ AlternC Team} + * + * @copyright AlternC-Team 2002-11-01 http://alternc.net/ + */ class m_err { - /** Numero de classe d'erreur actuelle */ - var $clsid=0; + /** Numero de classe d'erreur actuelle */ + var $clsid=0; - /** Dernière erreur enregistrée par la classe */ - var $error=0; + /** Dernière erreur enregistrée par la classe */ + var $error=0; - /** Paramètre chaine eventuellement associé à la dernière erreur */ - var $param=""; + /** Paramètre chaine eventuellement associé à la dernière erreur */ + var $param=""; - /** Emplacement du fichier de logs d'AlternC */ - var $logfile="/var/log/alternc/bureau.log"; + /** Emplacement du fichier de logs d'AlternC */ + var $logfile="/var/log/alternc/bureau.log"; - /** - * 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, - * et la met à disposition pour le bureau virtuel pour affichage ultérieur. - * - * @todo ne plus utiliser $error de façon numérique, nulle part - * - * @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 string $param Paramètre chaine associé à l'erreur (facultatif) - * @return boolean TRUE si l'erreur est connue, FALSE sinon. - * - */ - function raise($clsid,$error,$param="") { + /** + * 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, + * et la met à disposition pour le bureau virtuel pour affichage ultérieur. + * + * @todo ne plus utiliser $error de façon numérique, nulle part + * + * @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 string $param Paramètre chaine associé à l'erreur (facultatif) + * @return boolean TRUE si l'erreur est connue, FALSE sinon. + * + */ + function raise($clsid,$error,$param="") { - // This is the old method, deprecation warning - $this->deprecated(); - /* Leve une exception. Si elle existe, sinon, stocke un message d'erreur sur erreur ...*/ - if (_("err_".$clsid."_".$error)!="err_".$clsid."_".$error || is_string($error)) { - $this->clsid=$clsid; - $this->error=$error; - $args = func_get_args(); - $this->param=array_slice($args, 2); - $this->logerr(); - return true; - } else { - $this->clsid="err"; - $this->error=1; - $this->param="Error # $error in Class $clsid, Value is $param. (sorry, no text for this error in your language at the moment)"; - $this->logerr(); - return false; + // This is the old method, deprecation warning + $this->deprecated(); + /* Leve une exception. Si elle existe, sinon, stocke un message d'erreur sur erreur ...*/ + if (_("err_".$clsid."_".$error)!="err_".$clsid."_".$error || is_string($error)) { + $this->clsid=$clsid; + $this->error=$error; + $args = func_get_args(); + $this->param=array_slice($args, 2); + $this->logerr(); + return true; + } else { + $this->clsid="err"; + $this->error=1; + $this->param="Error # $error in Class $clsid, Value is $param. (sorry, no text for this error in your language at the moment)"; + $this->logerr(); + return false; + } } - } - /** - * 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 - * 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. - * - * @return string Chaine d'erreur. - * - */ - function errstr() { - if (is_string($this->error)) { - // new way of handling errors: message directly in the class - $str = $this->error."\n"; - } else { - // old way: message in the locales files (ugly) - $str = _("err_".$this->clsid."_".$this->error)."\n"; + /** + * 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 + * 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. + * + * @return string Chaine d'erreur. + * + */ + function errstr() { + if (is_string($this->error)) { + // new way of handling errors: message directly in the class + $str = $this->error."\n"; + } else { + // old way: message in the locales files (ugly) + $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); - $msg = call_user_func_array("sprintf", $args); - return $msg; - } else { - return $args; + + /** + * Envoi un log d'erreur dans /var/log/alternc/bureau.log + * + * Cette fonction Loggue la dernière erreur dans /var/log sur la machine, + * permettant ainsi aux admins de savoir ce qu'il se passe... + * 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 - * - * Cette fonction Loggue la dernière erreur dans /var/log sur la machine, - * permettant ainsi aux admins de savoir ce qu'il se passe... - * 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'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 */ - /** - * 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 */ -?> diff --git a/bureau/class/m_export.php b/bureau/class/m_export.php index dfb0c2a4..a4a93839 100644 --- a/bureau/class/m_export.php +++ b/bureau/class/m_export.php @@ -3,10 +3,10 @@ /* --------------------------------------------------------------------------- */ /** Constructor - Classe d'export de compte Alternc. - Cette classe ce contente d'invoquer les fonctions d'exportation de configuration et de données d'un compte, - presentes dans les classes concernées. - */ + Classe d'export de compte Alternc. + Cette classe ce contente d'invoquer les fonctions d'exportation de configuration et de données d'un compte, + presentes dans les classes concernées. +*/ Class m_export { function m_export() { @@ -20,8 +20,8 @@ Class m_export { } /** le repertoire de base est passé en paramettre puis en construit une arborescence de la forme - ////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) @@ -50,6 +42,11 @@ class m_ftp { return array("ftp" => "FTP accounts"); } + + /** + * hook function called by menu class + * to add menu to the left panel + */ function hook_menu() { global $quota; $q = $quota->getquota("ftp"); @@ -81,8 +78,11 @@ class m_ftp { 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() { $c = Array(); $c['name'] = "FTP"; @@ -100,7 +100,10 @@ class m_ftp { return $c; } - // Switch enabled status of an account + + /** + * Switch enabled status of an account + */ function switch_enabled($id, $status = null) { global $cuid, $db, $msg; if (!$jj = $this->get_ftp_details($id)) { @@ -114,7 +117,6 @@ class m_ftp { $status = 1; } } - // Be sure what is in $status, in case of it was a parameter $status = ($status ? 1 : 0); @@ -126,9 +128,9 @@ class m_ftp { } } - /* ----------------------------------------------------------------- */ - /** Retourne la liste des comptes FTP du compte h�berg� + /** + * Retourne la liste des comptes FTP du compte h�berg� * Retourne la liste des comptes FTP sous forme de tableau index� de * tableaus associatifs comme suit : * $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 * @param integer $id Numero du compte dont on souhaite obtenir les d�tails * @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) * du compte actuel. */ @@ -213,14 +215,13 @@ class m_ftp { return $r; } + /** * Check if the login is fine (syntax) - * * @param string $l */ function check_login($l) { global $msg; - // special chars and the max numbers of them allowed // to be able to give a specific error $vv = array('_' => '1', ' ' => 0); @@ -230,7 +231,6 @@ class m_ftp { return false; } } - // Explicitly look for only allowed chars if (!preg_match("/^[A-Za-z0-9]+[A-Za-z0-9_\.\-]*$/", $l)) { $msg->raise("ERROR", 'ftp', _("FTP login is incorrect")); @@ -239,9 +239,9 @@ class m_ftp { 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�s sous la forme ... * La valeur $current se voit affubl�e de la balise SELECTED. * @param string $current Prefixe s�lectionn� par d�faut @@ -261,9 +261,9 @@ class m_ftp { return true; } - /* ----------------------------------------------------------------- */ - /** Modifie les param�tres du comptes FTP $id. + /** + * Modifie les param�tres du comptes FTP $id. * @param integer $id Num�ro du compte dont on veut modifier les param�tres * @param string $prefixe Prefixe du compte FTP * @param string $login login ajout� au pr�fixe ($prefixe_$login) @@ -327,9 +327,9 @@ class m_ftp { return true; } - /* ----------------------------------------------------------------- */ - /** Efface le compte ftp specifie + /** + * Efface le compte ftp specifie * @param integer $id Numero du compte FTP a supprimer. * @return boolean TRUE si le compte a ete efface, FALSE sinon. */ @@ -347,15 +347,14 @@ class m_ftp { return $name; } - /* ----------------------------------------------------------------- */ - /** Cree un nouveau compte FTP. + /** + * Cree un nouveau compte FTP. * @param string $prefixe Prefixe au login * @param string $login Login ftp (login=prefixe_login) * @param string $pass Mot de passe FTP * @param string $dir Repertoire racine du compte relatif à la racine du membre * @return boolean TRUE si le compte a ete cree, FALSE sinon. - * */ function add_ftp($prefixe, $login, $pass, $dir) { global $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 * @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. * @access private */ @@ -448,9 +447,9 @@ class m_ftp { return true; } - /* ----------------------------------------------------------------- */ - /** Fonction appellee par membres quand un membre est efface + /** + * Fonction appellee par membres quand un membre est efface * @access private */ function alternc_del_member() { @@ -460,7 +459,6 @@ class m_ftp { return true; } - /* ----------------------------------------------------------------- */ /** * Returns the used quota for the $name service for the current user. @@ -479,7 +477,6 @@ class m_ftp { return $q; } - /* ----------------------------------------------------------------- */ /** * Exporte toutes les informations ftp du compte AlternC @@ -500,9 +497,9 @@ class m_ftp { 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 * @return array a key => value list of port protocol name mandatory values * @access private @@ -513,6 +510,5 @@ class m_ftp { ); } -} +} /* Class m_ftp */ -/* Class m_ftp */ diff --git a/bureau/class/m_hooks.php b/bureau/class/m_hooks.php index 58a92b04..06a97a74 100644 --- a/bureau/class/m_hooks.php +++ b/bureau/class/m_hooks.php @@ -1,10 +1,6 @@ "Protected folders passwords"); } + /** - * + * hook called by menu class to add a menu + * to the left panel * @return array */ function hook_menu() { @@ -71,6 +51,7 @@ class m_hta { return $obj; } + /** * Create a protected folder (.htaccess et .htpasswd) * @param string $dir Folder to protect (relative to user root) @@ -115,6 +96,7 @@ class m_hta { return true; } + /** * Returns the list of all user folder currently protected by a .htpasswd file * @@ -144,6 +126,7 @@ class m_hta { return $r; } + /** * Tells if a folder is protected. * @@ -163,6 +146,7 @@ class m_hta { } } + /** * 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"; if (file_exists("$absolute/.htaccess")) { /* if (!_reading_htaccess($absolute)) { - return false; - } - */ + return false; + } + */ } $file = @fopen("$absolute/.htpasswd", "r"); $i = 0; @@ -187,7 +171,7 @@ class m_hta { if (!$file) { return false; } - // TODO: Tester la validité du .htpasswd + // TODO: Test the validity of a .htpasswd while (!feof($file)) { $s = fgets($file, 1024); $t = explode(":", $s); @@ -200,6 +184,7 @@ class m_hta { return $res; } + /** * Unprotect a folder * @@ -261,6 +246,7 @@ class m_hta { return true; } + /** * Add a user to a protected folder * @@ -326,6 +312,7 @@ class m_hta { } } + /** * Delete a user from a protected folder. * @@ -367,6 +354,7 @@ class m_hta { return true; } + /** * Change the password of a user in a protected folder * @param string $user The users whose password should be changed @@ -412,6 +400,7 @@ class m_hta { return true; } + /** * Check that a .htaccess file is valid (for authentication) * @@ -455,6 +444,5 @@ class m_hta { return true; } -} +} /* class m_hta */ -/* CLASS m_hta */ diff --git a/bureau/class/m_log.php b/bureau/class/m_log.php index 65eb3378..b02c7cdc 100644 --- a/bureau/class/m_log.php +++ b/bureau/class/m_log.php @@ -1,10 +1,6 @@ log("log", "list_logs_directory"); @@ -40,37 +33,51 @@ class m_log { $c = array(); foreach (glob("${dir}/*log*") as $absfile) { $c[] = array("name" => basename($absfile), - "creation_date" => date("F d Y H:i:s", filectime($absfile)), - "mtime" => filemtime($absfile), - "filesize" => filesize($absfile), - "downlink" => urlencode(basename($absfile)), + "creation_date" => date("F d Y H:i:s", filectime($absfile)), + "mtime" => filemtime($absfile), + "filesize" => filesize($absfile), + "downlink" => urlencode(basename($absfile)), ); } usort($c, "m_log::compare_logtime"); return $c; } - // Used by list_logs_directory to sort + + /** + * Used by list_logs_directory to sort + */ private function compare_logname($a, $b) { 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) { return $b['mtime'] - $a['mtime']; } + + /** + * hook called by the menu class + * to add menu to the left panel + */ function hook_menu() { $obj = array( 'title' => _("Logs"), 'ico' => 'images/logs.png', 'link' => 'logs_list.php', 'pos' => 130, - ); + ); return $obj; } + /** + * list all log files in all log directories + */ function list_logs_directory_all($dirs) { global $msg; $msg->log("log", "get_logs_directory_all"); @@ -81,6 +88,7 @@ class m_log { return $c; } + function get_logs_directory() { global $cuid, $mem, $msg; $msg->log("log", "get_logs_directory"); @@ -93,6 +101,10 @@ class m_log { return $c; } + + /** + * download a log file + */ function download_link($file) { global $msg; $msg->log("log", "download_link"); @@ -105,6 +117,9 @@ class m_log { readfile($ff); } + /** + * show the last lines of a file + */ function tail($file, $lines = 20) { global $msg; $msg->log("log", "tail"); @@ -119,6 +134,4 @@ class m_log { return implode("\n", $out); } -} - -// end class +} /* class m_log */ diff --git a/bureau/class/m_lxc.php b/bureau/class/m_lxc.php index 21651b07..0962ca12 100644 --- a/bureau/class/m_lxc.php +++ b/bureau/class/m_lxc.php @@ -1,10 +1,6 @@ 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 */ @@ -60,11 +57,12 @@ class m_lxc implements vm { 'ico' => 'images/ssh.png', 'link' => 'vm.php', 'pos' => 95, - ); + ); return $obj; } + /** * HOOK: remove VM history for AlternC account */ @@ -75,6 +73,7 @@ class m_lxc implements vm { return true; } + /** * Send a message to a remote VM manager instance * $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 * 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); } + /** * Stop the currently running VM */ @@ -187,6 +189,5 @@ class m_lxc implements vm { return TRUE; } -} +} /* class m_lxc */ -// class m_lxc diff --git a/bureau/class/m_mail.php b/bureau/class/m_mail.php index 0115fb4d..b5f38926 100644 --- a/bureau/class/m_mail.php +++ b/bureau/class/m_mail.php @@ -1,10 +1,6 @@ invoke in the code. */ class m_mail { - /* ----------------------------------------------------------------- */ - /** domain list for this account + /** + * domain list for this account * @access private */ 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 * @access private */ 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 * @access private */ var $forbiddenchars = array('"', "'", '\\', '/', '?', '!', '*', '$', '|', '#', '+'); - /* ----------------------------------------------------------------- */ - /** Number of results for a pager display + /** + * Number of results for a pager display * @access public */ var $total; + // Human server name for help var $srv_submission; var $srv_smtp; @@ -75,7 +69,6 @@ class m_mail { var $cache_domain_mail_size = array(); var $enum_domains = array(); - /* ----------------------------------------------------------------- */ /** * 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')); } + + /** + * Hook called by menu class to add the email menu to the left pane + */ function hook_menu() { $obj = array( 'title' => _("Email Addresses"), @@ -110,6 +107,7 @@ class m_mail { return $obj; } + function get_total_size_for_domain($domain) { global $db; if (empty($this->cache_domain_mail_size)) { @@ -125,7 +123,6 @@ class m_mail { return 0; } - // FIXME documenter /** * @param string $domain_id @@ -157,6 +154,7 @@ class m_mail { return $rr; } + /** * @param string $domain_id */ @@ -168,6 +166,7 @@ class m_mail { return $this->delete($catch['mail_id']); } + /** * @param string $domain_id * @param string $target @@ -179,9 +178,9 @@ class m_mail { $target = '@' . $target; } - if (substr($target, 0, 1) == '@') { // le premier caractere est un @ + if (substr($target, 0, 1) == '@') { // the first character is @ // FIXME validate domain - } else { // ca doit être un mail + } else { // it MUST be an email if (!filter_var($target, FILTER_VALIDATE_EMAIL)) { $msg->raise("ERROR", "mail", _("The email you entered is syntaxically incorrect")); return false; @@ -191,9 +190,9 @@ class m_mail { 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 * @param $name string the named quota we want * @return the number of used service for the specified quota, @@ -211,18 +210,18 @@ class m_mail { 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)" */ function alternc_password_policy() { 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 */ function enum_domains($uid = -1) { @@ -231,7 +230,7 @@ class m_mail { if ($uid == -1) { $uid = $cuid; } - $db->query(" + $db->query(" SELECT d.id, d.domaine, @@ -254,9 +253,9 @@ ORDER BY 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. * @param $mail string email to check * @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 $search string search that string in recipients or address. * @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. * @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) { global $db, $msg, $hooks; $msg->log("mail", "enum_domains_mail"); @@ -311,8 +310,8 @@ ORDER BY $db->next_record(); $this->total = $db->f("total"); if ($count != -1) { - $offset = intval($offset); - $count = intval($count); + $offset = intval($offset); + $count = intval($count); $limit = " LIMIT $offset, $count "; } else { $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. * * This function calls the hook "hooks_mail_cancreate" @@ -387,10 +386,10 @@ ORDER BY // Already exists? $db->query("SELECT * FROM address WHERE domain_id= ? AND address= ? ;", array($dom_id, $mail)); if ($db->next_record()) { - if ($db->f("type") == "mailman") - $msg->raise("ERROR", "mail", _("This email address already exists in mailman")); - else - $msg->raise("ERROR", "mail", _("This email address already exists")); + if ($db->f("type") == "mailman") + $msg->raise("ERROR", "mail", _("This email address already exists in mailman")); + else + $msg->raise("ERROR", "mail", _("This email address already exists")); return false; } @@ -403,9 +402,9 @@ ORDER BY 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 * @return array a hashtable with all the informations for that email */ @@ -435,9 +434,9 @@ ORDER BY 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 * @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. * @param $dom the ID of the domain to delete * @return boolean if the email has been properly deleted @@ -485,7 +484,10 @@ ORDER BY 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) { 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)); @@ -495,9 +497,9 @@ ORDER BY 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. * * @param $mail_id integer the number of the email to delete @@ -547,9 +549,9 @@ ORDER BY 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. * * @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 $pass string the new password. * @return boolean true if the password has been set, false else, raise an error. @@ -616,16 +618,16 @@ ORDER BY return false; } 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 ))) { return false; } return true; } - /* ----------------------------------------------------------------- */ - /** Enables an email address. + /** + * Enables an email address. * @param $mail_id integer Email ID * @return boolean true if the email has been enabled. */ @@ -641,9 +643,9 @@ ORDER BY return true; } - /* ----------------------------------------------------------------- */ - /** Disables an email address. + /** + * Disables an email address. * @param $mail_id integer Email ID * @return boolean true if the email has been enabled. */ @@ -659,9 +661,9 @@ ORDER BY 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. * * @param $mail_id integer the number of the email to delete @@ -719,7 +721,7 @@ ORDER BY foreach ($r as $m) { $m = trim($m); 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"; } } @@ -727,15 +729,15 @@ ORDER BY if (isset($red) && $red) { $db->query("INSERT INTO recipient SET address_id= ?, recipients= ? ;", array($mail_id, $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.")); - } + 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.")); + } 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 : $m , the left part of the mail address being created * @ param : $delivery , the delivery used to deliver the mail @@ -749,9 +751,9 @@ ORDER BY // 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 : $m , the alias we want to create * @ param : $alias , the already existing aliased address @@ -772,9 +774,9 @@ ORDER BY 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 * of the email for the current acccount. */ @@ -784,9 +786,9 @@ ORDER BY $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 * of the email for the current acccount. */ @@ -825,7 +827,6 @@ ORDER BY return $str; } - /* ----------------------------------------------------------------- */ /** * Return the list of allowed slave accounts (secondary-mx) @@ -844,7 +845,6 @@ ORDER BY return $res; } - /* ----------------------------------------------------------------- */ /** * Check for a slave account (secondary mx) @@ -861,9 +861,9 @@ ORDER BY return false; } - /* ----------------------------------------------------------------- */ - /** Out (echo) the complete hosted domain list : + /** + * Out (echo) the complete hosted domain list : */ function echo_domain_list($format = null) { global $db; @@ -875,21 +875,20 @@ ORDER BY $tt.=$db->f("domaine"); } - # Generate an integrity check + // Generate an integrity check $obj = array('integrity' => md5($tt), 'items' => $lst); switch ($format) { - case "json": - return json_encode($obj); - default: - foreach ($lst as $l) { - echo $l . "\n"; - } - return true; + case "json": + return json_encode($obj); + default: + foreach ($lst as $l) { + echo $l . "\n"; + } + return true; } // switch } - /* ----------------------------------------------------------------- */ /** * Add a slave account that will be allowed to access the mxdomain list @@ -908,7 +907,6 @@ ORDER BY return true; } - /* ----------------------------------------------------------------- */ /** * Remove a slave account @@ -920,9 +918,9 @@ ORDER BY 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 * This function create a CATCHALL to the master domain * @param string $domain_id Domain that has just been created @@ -936,9 +934,9 @@ ORDER BY 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 * This function create a postmaster mail which is an alias to LOGIN @ FQDN * 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); } - /* ----------------------------------------------------------------- */ - /** hook function called by variables when a variable is changed + /** + * hook function called by variables when a variable is changed * @access private */ 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. * don't change spf if current value is not $old * @access private @@ -1030,9 +1028,9 @@ ORDER BY $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. * don't change dmarc if current value is not $old * @access private @@ -1063,9 +1061,9 @@ ORDER BY $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 * @return array a key => value list of port protocol name mandatory values * @access private @@ -1082,6 +1080,5 @@ ORDER BY ); } -} -/* Class m_mail */ +} /* Class m_mail */ diff --git a/bureau/class/m_mem.php b/bureau/class/m_mem.php index bae05575..f11ae4b0 100644 --- a/bureau/class/m_mem.php +++ b/bureau/class/m_mem.php @@ -1,7 +1,6 @@ "AlternC's account password"); } + + /** + * hook called by the m_menu class to add menu to the left of the panel + */ function hook_menu() { $obj = array( 'title' => _("Settings"), 'ico' => 'images/settings.png', 'link' => 'mem_param.php', 'pos' => 160, - ); + ); 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. */ function checkright() { 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. * Note : If the user entered a bas password, the failure will be logged * and told to the corresponding user on next successfull login. * @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) { global $db, $msg, $cuid, $authip; $msg->log("mem", "login", $username); - // $username=addslashes($username); - // $password=addslashes($password); + $db->query("select * from membres where login= ? ;", array($username)); if ($db->num_rows() == 0) { $msg->raise("ERROR", "mem", _("User or password incorrect")); @@ -168,9 +156,9 @@ class m_mem { 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 * 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 @@ -208,9 +196,9 @@ class m_mem { return true; } - /* ----------------------------------------------------------------- */ - /** Suite � la connexion de l'utilisateur, r�initialise ses param�tres de derni�re connexion + /** + * After a successful connection, reset the user's last connection date */ function resetlast() { 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)); } + function authip_token($bis = false) { global $db, $cuid; $db->query("select pass from membres where uid= ?;", array($cuid)); @@ -232,6 +221,7 @@ class m_mem { return md5("$i--" . $db->f('pass')); } + /** * @param boolean $t */ @@ -240,27 +230,27 @@ class m_mem { } /* Faut finir de l'implementer :) * / - function authip_class() { - global $cuid; - $c = Array(); - $c['name']="Panel access"; - $c['protocol']="mem"; - $c['values']=Array($cuid=>''); + function authip_class() { + global $cuid; + $c = Array(); + $c['name']="Panel access"; + $c['protocol']="mem"; + $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 - * session pour l'utilisateur annonce. - * Cette fonction doit etre appellee a chaque page devant etre authentifiee. - * et AVANT d'emettre des donnees. (un cookie peut etre envoye) - * @global string $session Le cookie de session eventuel - * @global string $username/password le login/pass de l'utilisateur - * @return boolean TRUE si la session est correcte, FALSE sinon. + /** + * Check that the current session is correct (valid cookie) + * If necessary, and if we received username & password fields, + * create a new session for the user. + * This function MUST be called by each page to authenticate the user. + * and BEFORE sending any data (since a cookie can be sent) + * @global string $session the session cookie + * @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) { global $db, $msg, $cuid; @@ -273,16 +263,19 @@ class m_mem { return $this->login($_REQUEST["username"], $_REQUEST["password"], (isset($_REQUEST["restrictip"]) ? $_REQUEST["restrictip"] : 0)); } } // end isset + $_COOKIE["session"] = isset($_COOKIE["session"]) ? $_COOKIE["session"] : ""; + if (strlen($_COOKIE["session"]) != 32) { - if ($show_msg) + if ($show_msg) $msg->raise("ERROR", "mem", _("Identity lost or unknown, please login")); return false; } + $ip = get_remote_ip(); $db->query("select uid, ? as me,ip from sessions where sid= ?;", array($ip, $_COOKIE["session"])); if ($db->num_rows() == 0) { - if ($show_msg) + if ($show_msg) $msg->raise("ERROR", "mem", _("Identity lost or unknown, please login")); return false; } @@ -298,7 +291,8 @@ class m_mem { $db->next_record(); $this->user = $db->Record; $msg->init_msgs(); - /* Remplissage de $local */ + + /* Fills $local */ $db->query("SELECT * FROM local WHERE uid= ? ;", array($cuid)); if ($db->num_rows()) { $db->next_record(); @@ -307,11 +301,11 @@ class m_mem { return true; } - /* ----------------------------------------------------------------- */ - /** Change l'identite d'un utilisateur temporairement. - * @global string $uid Utilisateur dont on prends l'identite - * @return TRUE si la session est correcte, FALSE sinon. + /** + * Change the identity of the user temporarily (SUDO) + * @global string $uid User that we want to impersonate + * @return boolean TRUE if it's okay, FALSE if it's not. */ function su($uid) { global $cuid, $db, $msg, $mysql; @@ -332,10 +326,10 @@ class m_mem { 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() { global $mysql; @@ -349,10 +343,10 @@ class m_mem { 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() { global $db, $user, $msg, $cuid, $hooks; @@ -382,14 +376,6 @@ class m_mem { $db->query("delete from sessions where sid= ? ;", array($_COOKIE["session"])); $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"); session_unset(); @@ -397,13 +383,13 @@ class m_mem { return true; } - /* ----------------------------------------------------------------- */ - /** Change le mot de passe de l'utilisateur courant. - * @param string $oldpass Ancien mot de passe. - * @param string $newpass Nouveau mot de passe - * @param string $newpass2 Nouveau mot de passe (a nouveau) - * @return boolean TRUE si le mot de passe a ete change, FALSE sinon. + /** + * Change the password of the current user + * @param string $oldpass Old password + * @param string $newpass New password + * @param string $newpass2 New password (again) + * @return boolean TRUE if the password has been change, FALSE if not. */ function passwd($oldpass, $newpass, $newpass2) { global $db, $msg, $cuid, $admin; @@ -432,11 +418,11 @@ class m_mem { return true; } - /* ----------------------------------------------------------------- */ - /** Change les preferences administrateur d'un compte - * @param integer $admlist Mode de visualisation des membres (0=large 1=courte) - * @return boolean TRUE si les preferences ont ete changees, FALSE sinon. + /** + * Change the administrator preferences of an admin account + * @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) { global $db, $msg, $cuid; @@ -450,13 +436,13 @@ class m_mem { return true; } - /* ----------------------------------------------------------------- */ - /** Envoie en mail le mot de passe d'un compte. - * Note : On ne peut demander le mot de passe qu'une seule fois par jour. + /** + * Send a mail with a password to an account + * Note : We can ask for a password only once a day * TODO : Translate this mail into the localization program. * 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) { global $msg, $db, $L_HOSTING, $L_FQDN; @@ -495,12 +481,12 @@ Cordially. 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 - * @param string $newmail Nouveau mail souhaite pour le membre. - * @return string le cookie si le mail a bien ete envoye, FALSE sinon + * @param string $newmail New mail we want to set for this account + * @return boolean TRUE if the email with a link has been sent, FALSE if not */ function ChangeMail1($newmail) { global $msg, $db, $L_HOSTING, $L_FQDN, $cuid; @@ -537,22 +523,22 @@ again, please contact your server's administrator. Cordially. "), $db->f("login"), $L_HOSTING, $link); mail($newmail, "Email modification request on $L_HOSTING", $txt, "From: postmaster@$L_FQDN\nReply-to: postmaster@$L_FQDN"); - // Supprime les demandes pr�c�dentes de ce compte ! + $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())); - // Supprime les cookies de la veille :) + $lts = time() - 86400; $db->query("DELETE FROM chgmail WHERE ts< ? ;", array($lts)); return $KEY; } - /* ----------------------------------------------------------------- */ - /** Change le mail d'un membre (seconde etape, CookiE+cle = application) - * @param string $COOKIE Cookie envoye par mail - * @param string $KEY cle affichee a l'ecran - * @param integer $uid Utilisateur concerne (on est hors session) - * @return boolean TRUE si le mail a bien ete modifie, FALSE sinon + /** + * Change the email of a member (second step, Cookie + key change) + * @param string $COOKIE Cookie sent by mail + * @param string $KEY cle shown on the screen + * @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) { global $msg, $db; @@ -574,10 +560,10 @@ Cordially. 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) { global $db, $msg, $cuid; @@ -585,27 +571,27 @@ Cordially. $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() { return $this->user["show_help"]; } - /* ----------------------------------------------------------------- */ - /** Affiche (echo) l'aide contextuelle - * @param integer $file Numero de fichier d'aide a afficher. - * @return boolean TRUE si l'aide contextuelle a ete trouvee, FALSE sinon + /** + * show (echo) a contextual help + * @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) { if ($this->user["show_help"] || $force) { $hlp = _("hlp_$file"); if ($hlp != "hlp_$file") { $hlp = preg_replace( - "#HELPID_([0-9]*)#", "\""", $hlp); + "#HELPID_([0-9]*)#", "\""", $hlp); echo "

" . $hlp . "

"; return true; } @@ -615,6 +601,7 @@ Cordially. } } + /** * @param integer $uid */ @@ -628,7 +615,6 @@ Cordially. return intval($db->f('creator')); } - /* ----------------------------------------------------------------- */ /** * Exports all the personal user related information for an account. @@ -689,6 +675,4 @@ Cordially. return true; } -} - -/* Classe Membre */ +} /* Class m_mem */ diff --git a/bureau/class/m_menu.php b/bureau/class/m_menu.php index 597a1027..bce4ebf9 100644 --- a/bureau/class/m_menu.php +++ b/bureau/class/m_menu.php @@ -1,10 +1,6 @@ $b['pos']; } + /** + * some menus that don't have an attached class + */ function system_menu() { - // Here some needed menu who don't have a class global $help_baseurl, $lang_translation, $locales; $m = array( @@ -150,6 +144,4 @@ class m_menu { return $m; } -} - -/* Class menu */ +} /* Class m_menu */ diff --git a/bureau/class/m_messages.php b/bureau/class/m_messages.php index 10f43eb4..065fad06 100644 --- a/bureau/class/m_messages.php +++ b/bureau/class/m_messages.php @@ -52,6 +52,7 @@ class m_messages { $this->init_msgs(); } + /** * Record a message, insert it into the logfile. * @@ -83,6 +84,7 @@ class m_messages { return true; } + /** * Reset the stored messages array */ @@ -92,6 +94,7 @@ class m_messages { } } + /** * Tell if there are stored messages for a specific level * 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 * or only the last message @@ -162,6 +166,7 @@ class m_messages { return $str; } + /** * Return a message in HTML form with associated CSS * @@ -186,6 +191,7 @@ class m_messages { return $str; } + /** * Return all the messages of all levels in HTML form with associated CSS * @@ -207,6 +213,7 @@ class m_messages { return $msg; } + /** * 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 * @@ -255,6 +263,4 @@ class m_messages { ); } -} - -/* Class m_messages */ +} /* Class m_messages */ diff --git a/bureau/class/m_mysql.php b/bureau/class/m_mysql.php index 8ab46fce..697ce557 100644 --- a/bureau/class/m_mysql.php +++ b/bureau/class/m_mysql.php @@ -1,14 +1,6 @@ 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()) { - $msg->raise("ERROR", 'db_user', _("There are no databases in db_servers for this user. Please contact your administrator.")); - die(); - } + $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()) { + $msg->raise("ERROR", 'db_user', _("There are no databases in db_servers for this user. Please contact your administrator.")); + die(); + } - # Create the object - $this->HumanHostname = $db->f('name'); - $this->Host = $db->f('host'); - $this->User = $db->f('login'); - $this->Password = $db->f('password'); - $this->Client = $db->f('client'); - $this->Database = "mysql"; + // Create the object + $this->HumanHostname = $db->f('name'); + $this->Host = $db->f('host'); + $this->User = $db->f('login'); + $this->Password = $db->f('password'); + $this->Client = $db->f('client'); + $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; - /* --------------------------------------------------------------------------- */ - /** Constructor + /** + * Constructor * m_mysql([$mid]) Constructeur de la classe m_mysql, initialise le membre concerne */ - function m_mysql() { + function __construct() { global $cuid; if (!empty($cuid)) { $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'); } + function reload_dbus() { $this->dbus = new DB_users(); } + function list_db_servers() { 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;"); @@ -96,6 +88,7 @@ class m_mysql { return $c; } + function hook_menu() { global $quota; $q = $quota->getquota("mysql"); @@ -126,7 +119,6 @@ class m_mysql { return $obj; } - /* ----------------------------------------------------------------- */ /** * Password kind used in this class (hook for admin class) @@ -135,9 +127,9 @@ class m_mysql { 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 :
* "db" => database name "bck" => backup mode for this db * "dir" => Backup folder. @@ -156,9 +148,9 @@ class m_mysql { 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 * Returns FALSE if error */ @@ -179,9 +171,9 @@ class m_mysql { 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" * @return string returns an associative array as follow : * "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")); } - /* --------------------------------------------------------------------------- */ - /** 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) * @return boolean if the database $user_$db has been successfully created, or FALSE if * an error occured, such as over quota user. @@ -248,7 +240,7 @@ class m_mysql { return false; } - $len=variable_get("sql_max_database_length", 64); + $len=variable_get("sql_max_database_length", 64); if (strlen($dbname) > $len) { $msg->raise("ERROR", "mysql", _("Database name cannot exceed %d characters"), $len); 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 * @return boolean if the database $user_$db has been successfully deleted, or FALSE if * 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)); $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)); // 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; } - /* --------------------------------------------------------------------------- */ - /** Set the backup parameters for the database $db + /** + * Set the backup parameters for the database $db * @param $dbn string database name * @param $bck_mode integer Backup mode (0 = none 1 = daily 2 = weekly) * @param $bck_history integer How many backup should we keep ? @@ -402,9 +394,9 @@ class m_mysql { return true; } - /* --------------------------------------------------------------------------- */ - /** Change the password of the user in MySQL + /** + * Change the password of the user in MySQL * @param $password string new password (cleartext) * @return boolean TRUE if the password has been successfully changed, FALSE else. */ @@ -424,7 +416,7 @@ class m_mysql { return false; } - $len=variable_get("sql_max_username_length", 16); + $len=variable_get("sql_max_username_length", 16); if (strlen($password) > $len) { $msg->raise("ERROR", "mysql", _("MySQL password cannot exceed %d characters"), $len); return false; @@ -443,6 +435,7 @@ class m_mysql { return true; } + /** * Function used to grant SQL rights to users: * @base :database @@ -496,9 +489,9 @@ class m_mysql { 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 $stdout boolean shall-we dump the error to stdout ? * @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 * @return integer database size * @access private @@ -565,11 +558,10 @@ class m_mysql { return $size; } - /* ------------------------------------------------------------ */ /** * Returns the list of database users of an account - * */ + */ function get_userslist($all = null) { global $db, $msg, $cuid; $msg->log("mysql", "get_userslist"); @@ -592,13 +584,14 @@ class m_mysql { return $c; } + function get_defaultsparam($dbn) { global $db, $msg, $cuid; $msg->log("mysql", "getdefaults"); $dbu = $dbn; $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")); if (!$this->dbus->num_rows()) { @@ -645,7 +638,6 @@ class m_mysql { return $r; } - /* ------------------------------------------------------------ */ /** * 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 $passconf The password confirmation * @return boolean if the user has been created in MySQL or FALSE if an error occurred - * */ + */ function add_user($usern, $password, $passconf) { global $db, $msg, $mem, $cuid, $admin; $msg->log("mysql", "add_user", $usern); @@ -708,7 +700,6 @@ class m_mysql { return true; } - /* ------------------------------------------------------------ */ /** * Change a user's MySQL password @@ -716,7 +707,7 @@ class m_mysql { * @param $password The password for this username * @param $passconf The password confirmation * @return boolean if the password has been changed in MySQL or FALSE if an error occurred - * */ + */ function change_user_password($usern, $password, $passconf) { global $db, $msg, $cuid, $admin; $msg->log("mysql", "change_user_pass", $usern); @@ -738,14 +729,13 @@ class m_mysql { return true; } - /* ------------------------------------------------------------ */ /** * Delete a user in MySQL rights tables * @param $user the username (we will add "[alternc-account]_" to it) to delete * @param integer $all * @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) { global $db, $msg, $cuid; $msg->log("mysql", "del_user", $user); @@ -760,10 +750,10 @@ class m_mysql { } if (!$db->num_rows()) { - if (! $caller_is_deldb ) - $msg->raise("ERROR", "mysql", _("The username was not found")); + if (! $caller_is_deldb ) + $msg->raise("ERROR", "mysql", _("The username was not found")); - return false; + return false; } $db->next_record(); $login = $db->f("name"); @@ -782,13 +772,12 @@ class m_mysql { return true; } - /* ------------------------------------------------------------ */ /** * Return the list of the database rights of user $user * @param $user the username * @return array An array of database name and rights - * */ + */ function get_user_dblist($user) { global $db, $msg; @@ -801,18 +790,18 @@ class m_mysql { $r = array(); $db->free(); $dblist = $this->get_dblist(); - foreach ($dblist as $tab) { - $dbname = str_replace('_', '\_', $tab["db"]); + foreach ($dblist as $tab) { + $dbname = str_replace('_', '\_', $tab["db"]); $this->dbus->query("SELECT * FROM mysql.db WHERE User= ? AND Host= ? AND Db= ? ;", array($user, $this->dbus->Client, $dbname)); 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"), - "create_view" => $this->dbus->f("Create_view_priv"), - "show_view" => $this->dbus->f("Show_view_priv"), - "create_routine" => $this->dbus->f("Create_routine_priv"), - "alter_routine" => $this->dbus->f("Alter_routine_priv"), - "execute" => $this->dbus->f("Execute_priv"), - "event" => $this->dbus->f("Event_priv"), - "trigger" => $this->dbus->f("Trigger_priv") + "create_view" => $this->dbus->f("Create_view_priv"), + "show_view" => $this->dbus->f("Show_view_priv"), + "create_routine" => $this->dbus->f("Create_routine_priv"), + "alter_routine" => $this->dbus->f("Alter_routine_priv"), + "execute" => $this->dbus->f("Execute_priv"), + "event" => $this->dbus->f("Event_priv"), + "trigger" => $this->dbus->f("Trigger_priv") ); } 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"); @@ -821,7 +810,6 @@ class m_mysql { return $r; } - /* ------------------------------------------------------------ */ /** * 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 $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 - * - * */ + */ function set_user_rights($user, $dbn, $rights) { global $msg; $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 = ""; for ($i = 0; $i < count($rights); $i++) { switch ($rights[$i]) { - case "select": - $strrights.="SELECT,"; - break; - case "insert": - $strrights.="INSERT,"; - break; - case "update": - $strrights.="UPDATE,"; - break; - case "delete": - $strrights.="DELETE,"; - break; - case "create": - $strrights.="CREATE,"; - break; - case "drop": - $strrights.="DROP,"; - break; - case "references": - $strrights.="REFERENCES,"; - break; - case "index": - $strrights.="INDEX,"; - break; - case "alter": - $strrights.="ALTER,"; - break; - case "create_tmp": - $strrights.="CREATE TEMPORARY TABLES,"; - break; - case "lock": - $strrights.="LOCK TABLES,"; - break; - case "create_view": - $strrights.="CREATE VIEW,"; - break; - case "show_view": - $strrights.="SHOW VIEW,"; - break; - case "create_routine": - $strrights.="CREATE ROUTINE,"; - break; - case "alter_routine": - $strrights.="ALTER ROUTINE,"; - break; - case "execute": - $strrights.="EXECUTE,"; - break; - case "event": - $strrights.="EVENT,"; - break; - case "trigger": - $strrights.="TRIGGER,"; - break; + case "select": + $strrights.="SELECT,"; + break; + case "insert": + $strrights.="INSERT,"; + break; + case "update": + $strrights.="UPDATE,"; + break; + case "delete": + $strrights.="DELETE,"; + break; + case "create": + $strrights.="CREATE,"; + break; + case "drop": + $strrights.="DROP,"; + break; + case "references": + $strrights.="REFERENCES,"; + break; + case "index": + $strrights.="INDEX,"; + break; + case "alter": + $strrights.="ALTER,"; + break; + case "create_tmp": + $strrights.="CREATE TEMPORARY TABLES,"; + break; + case "lock": + $strrights.="LOCK TABLES,"; + break; + case "create_view": + $strrights.="CREATE VIEW,"; + break; + case "show_view": + $strrights.="SHOW VIEW,"; + break; + case "create_routine": + $strrights.="CREATE ROUTINE,"; + break; + case "alter_routine": + $strrights.="ALTER ROUTINE,"; + break; + case "execute": + $strrights.="EXECUTE,"; + break; + case "event": + $strrights.="EVENT,"; + break; + case "trigger": + $strrights.="TRIGGER,"; + break; } } // 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)); if ($this->dbus->num_rows()) { @@ -911,13 +898,16 @@ class m_mysql { return TRUE; } + /** + * list of all possible 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'); } - /* ----------------------------------------------------------------- */ - /** 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 * @access private */ @@ -932,9 +922,9 @@ class m_mysql { 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. * @param $name string name of the quota * @return integer the number of service used or false if an error occured @@ -952,16 +942,16 @@ class m_mysql { 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 * @access private */ function alternc_add_member() { global $db, $msg, $cuid, $mem; $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)); if ($db->num_rows()) { $myadm = $db->f("name"); @@ -976,9 +966,9 @@ class m_mysql { 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 * @access private */ @@ -1000,27 +990,26 @@ class m_mysql { 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 - a @access private - */ + * a @access private + */ function alternc_del_session() { $_SESSION['PMA_single_signon_user'] = ''; $_SESSION['PMA_single_signon_password'] = ''; $_SESSION['PMA_single_signon_host'] = ''; } - /* ----------------------------------------------------------------- */ /** - * Exporte all the mysql information of an account + * Exports all the mysql information of an account * @access private * EXPERIMENTAL 'sid' function ;) */ 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; $msg->log("mysql", "export"); $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; } - /* ----------------------------------------------------------------- */ /** - * 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 * EXPERIMENTAL 'sid' function ;) */ @@ -1069,7 +1057,6 @@ class m_mysql { } } - /* ----------------------------------------------------------------- */ /** * Return the size of each databases in a SQL Host given in parameter @@ -1084,26 +1071,24 @@ class m_mysql { global $msg; $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;"); - $alldb=array(); + $alldb=array(); while ($this->dbus->next_record()) { $alldb[] = $this->dbus->f("Database"); - } + } $res = array(); - foreach($alldb as $dbname) { + foreach($alldb as $dbname) { $c = $this->dbus->query("SHOW TABLE STATUS FROM $dbname;"); $size = 0; 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"; } return $res; } -} - -/* Class m_mysql */ +} /* Class m_mysql */ diff --git a/bureau/class/m_piwik.php b/bureau/class/m_piwik.php index 2a909b17..5d59176a 100644 --- a/bureau/class/m_piwik.php +++ b/bureau/class/m_piwik.php @@ -1,9 +1,6 @@ piwik_server_uri) || empty($this->piwik_admin_token)) return false; + function hook_menu() { + global $quota; + if ( empty($this->piwik_server_uri) || empty($this->piwik_admin_token)) return false; - $obj = array( - 'title' => _("Piwik statistics"), - 'ico' => 'images/piwik.png', - 'link' => 'toggle', - 'pos' => 115, - 'links' => array( - array( 'txt' => _("Piwik Users"), 'url' => 'piwik_userlist.php'), - array( 'txt' => _("Piwik Sites"), 'url' => 'piwik_sitelist.php'), - ), - ) ; + $obj = array( + 'title' => _("Piwik statistics"), + 'ico' => 'images/piwik.png', + 'link' => 'toggle', + 'pos' => 115, + 'links' => array( + array( 'txt' => _("Piwik Users"), 'url' => 'piwik_userlist.php'), + array( 'txt' => _("Piwik Sites"), 'url' => 'piwik_sitelist.php'), + ), + ) ; - 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 $obj; } - 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; - $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)) { - $msg->raise("ERROR", "piwik", _("All fields are mandatory")); - return false; - } + if (empty($user_login) || is_null($user_login) || empty($user_mail) || is_null($user_mail)) { + $msg->raise("ERROR", "piwik", _("All fields are mandatory")); + return false; + } - // Validate the email syntax: + // Validate the email syntax: if (!filter_var($user_mail, FILTER_VALIDATE_EMAIL)) { $msg->raise("ERROR", "piwik", _("The email you entered is syntaxically incorrect")); return false; } $user_login = $this->clean_user_name($user_login); - $user_pass = create_pass(); - $user_alias = $user_login; + $user_pass = create_pass(); + $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'); - if ($api_data) { - if ($api_data->result === 'success') { - $user = $this->get_user($user_login); - $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)); - return $ret_value; - } else { - $msg->raise("ERROR", "piwik", $api_data->message); - return FALSE; - } - } else { // api_data = false -> error is already filled - 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); - } + $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->result === 'success') { + $user = $this->get_user($user_login); + $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)); + return $ret_value; + } else { + $msg->raise("ERROR", "piwik", $api_data->message); + return FALSE; + } + } else { // api_data = false -> error is already filled + return FALSE; + } } - 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) + /** + * Change a user @TODO: code this + */ + function user_edit() { 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 get_site_access($user_login) { + return $this->call_privileged_page('API', 'UsersManager.getSitesAccessFromUser', array('userLogin' => $user_login)); } - } - - function users_list() { - global $db, $cuid, $msg; + function get_users_access_from_site($site_id) { + 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 ($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)); - } + 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; + } - // Verifie que l'utilisateur existe bien dans piwik - function user_checkremote($puser_id) { - //FIXME - return true; - } + /** + * @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; + } - // 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() { + function get_alternc_users() { 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(); $db->query("SELECT piwik_id AS site_id FROM piwik_sites WHERE uid= ? ;", array($cuid)); while ($db->next_record()) - array_push($alternc_sites, $db->f('site_id')); + array_push($alternc_sites, $db->f('site_id')); 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) { - 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'))) - return FALSE; - $api_data = $this->call_privileged_page('API', 'UsersManager.setUserAccess', array('userLogin' => $login, 'access' => $right, 'idSites' => $site_id)); - if ($api_data->result == 'success') { - return TRUE; - } else { - $msg->raise("ERROR", 'piwik', $api_data->messsage); - return FALSE; - } + if (!in_array($right, array('noaccess', 'view', 'admin'))) + return FALSE; + $api_data = $this->call_privileged_page('API', 'UsersManager.setUserAccess', array('userLogin' => $login, 'access' => $right, 'idSites' => $site_id)); + if ($api_data->result == 'success') { + return TRUE; + } else { + $msg->raise("ERROR", 'piwik', $api_data->messsage); + return FALSE; + } } - // Ajoute un alias sur un site existant - function site_alias_add() { - // FIXME - return true; - } - - /* return a clean username with a unique prefix per account */ - 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; - } + // Ajoute un alias sur un site existant + function site_alias_add() { + // FIXME + return true; + } - function dev() { - // $this->call_page('module', 'method', array('user' => 'fser', 'pass' => 'toto')); - // return $this->users_list(); - } + /** + * return a clean username with a unique prefix per account + */ + 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; + } - /** - * @param string $module - * @param string $method - */ - 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; - } - } + function dev() { + // $this->call_page('module', 'method', array('user' => 'fser', 'pass' => 'toto')); + // return $this->users_list(); + } - /** - * @param string $module - * @param string $method - */ - function call_privileged_page($module, $method, $arguments=array(), $output = 'JSON') { - global $msg; + /** + * @param string $module + * @param string $method + */ + function call_page($module, $method, $arguments=array(), $output = 'JSON') { + global $msg; - $msg->log("piwik","call_privileged_page"); + $msg->log("piwik","call_page"); - $arguments['token_auth'] = $this->piwik_admin_token; - return $this->call_page($module, $method, $arguments, $output); - } + $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 $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 */ diff --git a/bureau/class/m_quota.php b/bureau/class/m_quota.php index c0eb8ea6..c8e9af82 100644 --- a/bureau/class/m_quota.php +++ b/bureau/class/m_quota.php @@ -1,10 +1,6 @@ disk_quota_enable) { $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() { _("quota_web"); } + function hook_menu() { global $cuid, $mem, $quota; @@ -76,34 +71,34 @@ class m_quota { $q = $this->getquota(); - foreach ($q as $key=>$value) - if (($key=="web")||(isset($value['in_menu'])&&$value['in_menu'])) { - if (!isset($q[$key]["u"]) || empty($q[$key]["t"])) { + foreach ($q as $key=>$value) + if (($key=="web")||(isset($value['in_menu'])&&$value['in_menu'])) { + if (!isset($q[$key]["u"]) || empty($q[$key]["t"])) { 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; - $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' => 'progressbar', 'total' => $q[$key]["t"], 'used' => $totalsize_used); - } + $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' => 'progressbar', 'total' => $q[$key]["t"], 'used' => $totalsize_used); + } // do not return menu item if there is no quota - if (!count($obj['links'])) return false; + if (!count($obj['links'])) return false; return $obj; } + function hook_homepageblock() { - return (object)Array( - 'pos' => 20, - 'call'=> function() { - define("QUOTASONE","1"); - }, - 'include' => "quotas_oneuser.php" - ); + return (object)Array( + 'pos' => 20, + 'call'=> function() { + define("QUOTASONE","1"); + }, + 'include' => "quotas_oneuser.php" + ); } - /* ----------------------------------------------------------------- */ /** Check if a user can use a ressource. * @param string $ressource the ressource name (a named quota) @@ -115,7 +110,6 @@ class m_quota { return $t["u"] < $t["t"]; } - /* ----------------------------------------------------------------- */ /** List the quota-managed services in the server * @Return array the quota names and description (translated) @@ -135,6 +129,7 @@ class m_quota { return $qlist; } + /** * Synchronise the quotas of the users with the quota of the * user's profile. @@ -152,12 +147,11 @@ class m_quota { return true; } + /* * Create default quota in the profile * when a new quota appear - * */ - function create_missing_quota_profile() { global $db, $quota, $msg; $msg->log("quota", "create_missing_quota_profile"); @@ -171,7 +165,6 @@ class m_quota { return true; } - /* ----------------------------------------------------------------- */ /** Return a ressource usage (u) and total quota (t) * @param string $ressource ressource to get quota of @@ -191,7 +184,7 @@ class m_quota { $res = $hooks->invoke("hook_quota_get"); foreach ($res as $r) { $this->quotas[$r['name']] = $r; - $this->quotas[$r['name']]['u'] = $r['used']; // retrocompatibilité + $this->quotas[$r['name']]['u'] = $r['used']; // retrocompatibility if (isset($r['sizeondisk'])) $this->quotas[$r['name']]['s'] = $r['sizeondisk']; $this->quotas[$r['name']]['t'] = 0; // Default quota = 0 @@ -205,7 +198,7 @@ class m_quota { while (list($key, $val) = each($this->disk)) { $a = array(); if ( - isset($disk_cached[$val]) && !empty($disk_cached[$val]) && $disk_cached[$val]['uid'] == $cuid && $disk_cached[$val]['timestamp'] > ( time() - (90) ) // Cache, en seconde + isset($disk_cached[$val]) && !empty($disk_cached[$val]) && $disk_cached[$val]['uid'] == $cuid && $disk_cached[$val]['timestamp'] > ( time() - (90) ) // Cache, en seconde ) { // If there is a cached value $a = $disk_cached[$val]; @@ -218,12 +211,12 @@ class m_quota { $a['u'] = intval($ak[0]); $a['t'] = @intval($ak[1]); } - $a['sizeondisk'] = $a['u']; + $a['sizeondisk'] = $a['u']; $a['timestamp'] = time(); $a['uid'] = $cuid; $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) * @param string $ressource ressource to set quota of @@ -280,7 +272,6 @@ class m_quota { return true; } - /* ----------------------------------------------------------------- */ /** * Erase all quota information about the user. @@ -292,9 +283,9 @@ class m_quota { 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 */ function getdefaults() { @@ -313,9 +304,9 @@ class m_quota { return $c; } - /* ----------------------------------------------------------------- */ - /** Set the default quotas + /** + * Set the default quotas * @param array associative array of quota (key=>val) */ function setdefaults($newq) { @@ -334,9 +325,9 @@ class m_quota { return true; } - /* ----------------------------------------------------------------- */ - /** Add an account type for quotas + /** + * Add an account type for quotas * @param string $type account type to be added * @return boolean true if all went ok */ @@ -359,9 +350,9 @@ class m_quota { return true; } - /* ----------------------------------------------------------------- */ - /** List for quotas + /** + * List types of quotas * @return array */ function listtype() { @@ -374,7 +365,6 @@ class m_quota { return $t; } - /* ----------------------------------------------------------------- */ /** Delete an account type for quotas * @param string $type account type to be deleted @@ -384,14 +374,13 @@ class m_quota { global $db; 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; } else { return false; } } - /* ----------------------------------------------------------------- */ /** Create default quotas entries for a new user. * The user we are talking about is in the global $cuid. @@ -418,7 +407,6 @@ class m_quota { return true; } - /* ----------------------------------------------------------------- */ /** Return a quota value with its unit (when it is a space quota) * in MB, GB, TB ... @@ -428,17 +416,17 @@ class m_quota { */ function display_val($type, $value) { switch ($type) { - case 'bw_web': - return format_size($value); - case 'web': - return format_size($value * 1024); - default: - return $value; + case 'bw_web': + return format_size($value); + case 'web': + return format_size($value * 1024); + default: + return $value; } } - /* get size_xx function (filled by spoolsize.php) */ + /* get size_xx function (filled by spoolsize.php) */ function _get_sum_sql($sql) { global $db; $db->query($sql); @@ -451,6 +439,7 @@ class m_quota { } } + function _get_count_sql($sql) { global $db; $db->query($sql); @@ -463,6 +452,7 @@ class m_quota { } } + function _get_size_and_record_sql($sql) { global $db; $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) { - 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() { 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) { 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() { 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) { global $mail; 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) { - 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() { 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) { 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) { 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() { 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) { 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) { 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() { 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) { 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) { 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() { 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) { 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() { 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) { 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) { 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) { $units = array(1073741824 => _("GB"), 1048576 => _("MB"), 1024 => _("KB"), 0 => _("B")); foreach ($units as $value => $unit) { @@ -610,11 +600,13 @@ class m_quota { } } - // Affiche des barres de progression - // color_type : - // 0 = Pas de changement de couleur - // 1 = Progression du vert vers le rouge en fonction du porcentage - // 2 = Progression du rouge vers le vert en fonction du porcentage + /** + * show a progress-bar + * color_type : + * 0 = No colo change + * 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) { if ($color_type == 1) { $csscolor = " background-color:" . PercentToColor($usage); @@ -624,16 +616,15 @@ class m_quota { $csscolor = ""; } - echo '
'; echo '
'; echo '
' . $usage . '%
'; echo '
'; } + /* ==== Hook functions ==== */ - /* ----------------------------------------------------------------- */ /** Hook function call when a user is deleted * AlternC's standard function called when a user is deleted @@ -643,7 +634,6 @@ class m_quota { $this->delquotas(); } - /* ----------------------------------------------------------------- */ /** Hook function called when a user is created * This function initialize the user's quotas. @@ -656,7 +646,6 @@ class m_quota { $this->getquota('', true); // actualise quota } - /* ----------------------------------------------------------------- */ /** Exports all the quota related information for an account. * @access private diff --git a/bureau/class/mime.php b/bureau/class/mime.php index bfbb447b..5db45087 100644 --- a/bureau/class/mime.php +++ b/bureau/class/mime.php @@ -1,14 +1,6 @@