[ENH] merge of stable-3.1 and master

This commit is contained in:
Benjamin Sonntag 2015-05-07 20:12:44 +02:00
commit d2ec2e81f3
95 changed files with 7825 additions and 1650 deletions

View File

@ -126,11 +126,11 @@ foreach ($domains as $key => $domain) {
} else { } else {
# 2.1 keep a copy of where it was, in an SQL request # 2.1 keep a copy of where it was, in an SQL request
$backup .= "UPDATE `sub_domaines` SET `type`='$type', valeur='$dest',web_action='UPDATE' WHERE `domaine`='$domain' AND sub='$sub';\n"; $backup .= "UPDATE `sub_domaines` SET `type`='$type', valeur='$dest',web_action='UPDATE' WHERE id=" . $r['sub'][$k]['id'] . ";\n";
# 2.2 change the subdomain to redirect to http://spam.koumbit.org/ # 2.2 change the subdomain to redirect to http://spam.koumbit.org/
$dom->lock(); $dom->lock();
if (!$dom->set_sub_domain($domain, $sub, $dom->type_url, "edit", $redirect)) { if (! $db->query("UPDATE `sub_domaines` SET `type`='" . $dom->type_url . "', valeur='$redirect',web_action='UPDATE' WHERE id=" . $r['sub'][$k]['id'] . ";\n") ) {
print "-- error in $sub.$domain: " . $err->errstr() . "\n"; print "-- error in $sub.$domain: " . $err->errstr() . "\n";
} }
$dom->unlock(); $dom->unlock();
@ -141,6 +141,36 @@ foreach ($domains as $key => $domain) {
if (!$confirmed) print '</ul>'; if (!$confirmed) print '</ul>';
} }
$mail_dom = $mail->enum_domains();
if ($confirmed) {
print "<pre>";
printf(_("-- disabling all the mail passwords\n"));
}
if (!$confirmed) print "\n<li>mailboxes<ul>\n";
reset($mail_dom);
# 1.3 foreach mail domain, we list the email hashes
foreach ($mail_dom as $key => $domain) {
if (!$confirmed) print '' . $domain['domaine'] . '</h4><ul>';
$mails = $mail->enum_domain_mails($domain['id']);
foreach ($mails as $key => $add) {
if ($add['islocal']) {
if (!$confirmed) print '<li>' . $add['address'] . '@' . $domain['domaine'];
$pass = $add['password'];
$id = $add['id'];
$backup .= $b = "update address set password='$pass' where id=$id;\n";
if (!$confirmed) print "<!-- $b --></li>\n";
if ($confirmed) {
$db->query("update `address` set password='!$pass' where id=$id;\n");
}
}
}
if (!$confirmed) print "</ul>";
}
if (!$confirmed) print "</ul></li></ul>\n";
# 3. wrap up (?) # 3. wrap up (?)
if ($confirmed) { if ($confirmed) {
print "-- The following is a serie of SQL request you can run, as root, to revert the user's domains to their previous state.\n"; print "-- The following is a serie of SQL request you can run, as root, to revert the user's domains to their previous state.\n";

View File

@ -32,6 +32,10 @@ if (!$mem->del_session()) {
} }
$H=getenv("HTTP_HOST"); $H=getenv("HTTP_HOST");
if (variable_get('https_redirect', false, 'switch users to HTTPS') && !isset($_SERVER['HTTPS'])) {
header("Location: https://$H/");
exit();
}
if (!isset($restrictip)) { if (!isset($restrictip)) {
$restrictip=1; $restrictip=1;
@ -74,7 +78,7 @@ if ( empty($logo) || ! $logo ) {
<br/> <br/>
<?php <?php
if (isset($_GET['authip_token'])) $authip_token=$_GET['authip_token']; if (isset($_GET['authip_token'])) $authip_token=$_GET['authip_token'];
if (variable_get('https_warning', true, 'warn users to switch to HTTPS') && !isset($_SERVER['HTTPS'])) { if (!isset($_SERVER['HTTPS'])) {
echo '<h4>' . sprintf(_('WARNING: you are trying to access the control panel insecurely, click <a href="https://%s">here</a> to go to secure mode'), $_SERVER["HTTP_HOST"]) . '</h4>'; echo '<h4>' . sprintf(_('WARNING: you are trying to access the control panel insecurely, click <a href="https://%s">here</a> to go to secure mode'), $_SERVER["HTTP_HOST"]) . '</h4>';
} }
?> ?>

View File

@ -249,6 +249,7 @@ if (date("Y-m-d")==substr($val["lastlogin"],0,10)) echo substr($val["lastlogin"]
<?php __("Which protocol shall you use?"); ?> <?php __("Which protocol shall you use?"); ?>
<div id="accordion-mailin"> <div id="accordion-mailin">
<?php if ($mail->srv_imap) { ?>
<h4><?php __("IMAP");?></h4> <h4><?php __("IMAP");?></h4>
<div> <div>
<ul> <ul>
@ -259,7 +260,7 @@ if (date("Y-m-d")==substr($val["lastlogin"],0,10)) echo substr($val["lastlogin"]
<li><b><?php __("Connection security:");?></b> STARTTLS</li> <li><b><?php __("Connection security:");?></b> STARTTLS</li>
</ul> </ul>
</div> </div>
<?php } if ($mail->srv_imaps) { ?>
<h4><?php __("IMAPS");?></h4> <h4><?php __("IMAPS");?></h4>
<div> <div>
<ul> <ul>
@ -270,7 +271,7 @@ if (date("Y-m-d")==substr($val["lastlogin"],0,10)) echo substr($val["lastlogin"]
<li><b><?php __("Connection security:");?></b> SSL</li> <li><b><?php __("Connection security:");?></b> SSL</li>
</ul> </ul>
</div> </div>
<?php } if ($mail->srv_pop3) { ?>
<h4><?php __("POP3");?></h4> <h4><?php __("POP3");?></h4>
<div> <div>
<ul> <ul>
@ -281,7 +282,7 @@ if (date("Y-m-d")==substr($val["lastlogin"],0,10)) echo substr($val["lastlogin"]
<li><b><?php __("Connection security:");?></b> STARTTLS</li> <li><b><?php __("Connection security:");?></b> STARTTLS</li>
</ul> </ul>
</div> </div>
<?php } if ($mail->srv_pop3s) { ?>
<h4><?php __("POP3S");?></h4> <h4><?php __("POP3S");?></h4>
<div> <div>
<ul> <ul>
@ -292,6 +293,7 @@ if (date("Y-m-d")==substr($val["lastlogin"],0,10)) echo substr($val["lastlogin"]
<li><b><?php __("Connection security:");?></b> SSL</li> <li><b><?php __("Connection security:");?></b> SSL</li>
</ul> </ul>
</div> </div>
<?php } ?>
</div> </div>
</div><!-- tabs-mailhelp-in --> </div><!-- tabs-mailhelp-in -->
</div><!-- tabs-mailhelp --> </div><!-- tabs-mailhelp -->

View File

@ -55,7 +55,7 @@ $infos = $piwik->user_add($account_name);
if (!$infos) if (!$infos)
{ {
$error = $err->errstr(); $error = $err->errstr();
//if (isset($error) && $error) { if (!$error) { $error = 'undefined error from piwik'; }
echo "<p class=\"alert alert-danger\">$error</p>"; echo "<p class=\"alert alert-danger\">$error</p>";
if (isset($fatal) && $fatal) { if (isset($fatal) && $fatal) {
include_once("foot.php"); include_once("foot.php");

View File

@ -32,13 +32,18 @@ require_once("../class/config.php");
if (!$r=$mysql->php_myadmin_connect()) { if (!$r=$mysql->php_myadmin_connect()) {
$error=$err->errstr(); $error=$err->errstr();
} else { } else {
session_write_close();
// SSO of PhpMyAdmin // SSO of PhpMyAdmin
session_set_cookie_params(0, '/', '', 0);
session_name('AlternC_Panel');
session_start();
$_SESSION['PMA_single_signon_user'] = $r["login"]; $_SESSION['PMA_single_signon_user'] = $r["login"];
$_SESSION['PMA_single_signon_password'] = $r["pass"]; $_SESSION['PMA_single_signon_password'] = $r["pass"];
$_SESSION['PMA_single_signon_host'] = $r["host"]; // pma >= 2.11 $_SESSION['PMA_single_signon_host'] = $r["host"]; // pma >= 2.11
session_write_close();
// finally redirect to phpMyAdmin : // finally redirect to phpMyAdmin :
header("Location: /alternc-sql/"); header("Location: /alternc-sql/index.php?server=1");
exit(); exit();
} }

View File

@ -2,10 +2,10 @@
class system_bind { class system_bind {
var $ZONE_TEMPLATE ="/etc/alternc/templates/bind/templates/zone.template"; var $ZONE_TEMPLATE = "/etc/alternc/templates/bind/templates/zone.template";
var $NAMED_TEMPLATE ="/etc/alternc/templates/bind/templates/named.template"; var $NAMED_TEMPLATE = "/etc/alternc/templates/bind/templates/named.template";
var $NAMED_CONF ="/var/lib/alternc/bind/automatic.conf"; var $NAMED_CONF = "/var/lib/alternc/bind/automatic.conf";
var $RNDC ="/usr/sbin/rndc"; var $RNDC = "/usr/sbin/rndc";
var $dkim_trusted_host_file = "/etc/opendkim/TrustedHosts"; var $dkim_trusted_host_file = "/etc/opendkim/TrustedHosts";
var $dkim_keytable_file = "/etc/opendkim/KeyTable"; var $dkim_keytable_file = "/etc/opendkim/KeyTable";
@ -19,10 +19,37 @@ class system_bind {
/** /**
* *
* @param array $options optional parameters
*/ */
function system_bind() { public function __construct($options = null) {
// Constructeur
if (isset($options["ZONE_TEMPLATE"])) {
$this->ZONE_TEMPLATE = $options["ZONE_TEMPLATE"];
} }
if (isset($options["NAMED_TEMPLATE"])) {
$this->NAMED_TEMPLATE = $options["NAMED_TEMPLATE"];
}
if (isset($options["NAMED_CONF"])) {
$this->NAMED_CONF = $options["NAMED_CONF"];
}
if (isset($options["RNDC"])) {
$this->RNDC = $options["RNDC"];
}
if (isset($options["dkim_trusted_host_file"])) {
$this->dkim_trusted_host_file = $options["dkim_trusted_host_file"];
}
if (isset($options["dkim_keytable_file"])) {
$this->dkim_keytable_file = $options["dkim_keytable_file"];
}
if (isset($options["dkim_signingtable_file"])) {
$this->dkim_signingtable_file = $options["dkim_signingtable_file"];
}
if (isset($options["zone_file_directory"])) {
$this->zone_file_directory = $options["zone_file_directory"];
}
}
/** /**
* Return the part of the conf we got from the database * Return the part of the conf we got from the database
@ -43,10 +70,10 @@ class system_bind {
sub_domaines sd, sub_domaines sd,
domaines_type dt domaines_type dt
where where
sd.type=dt.name sd.type = dt.name
and sd.enable in ('ENABLE', 'ENABLED') and sd.enable in ('ENABLE', 'ENABLED')
order by entry ;"); order by entry ;");
$t=array(); $t = array();
while ($db->next_record()) { while ($db->next_record()) {
$t[$db->f('domaine')][] = $db->f('entry'); $t[$db->f('domaine')][] = $db->f('entry');
} }
@ -102,7 +129,7 @@ class system_bind {
$calc = date('Ymd').'00'."\n"; $calc = date('Ymd').'00'."\n";
// Old one : // Old one :
$old=$calc; // default value $old = $calc; // default value
$file = $this->get_zone_file($domain); $file = $this->get_zone_file($domain);
preg_match_all("/\s*(\d{10})\s+\;\sserial\s?/", $file, $output_array); preg_match_all("/\s*(\d{10})\s+\;\sserial\s?/", $file, $output_array);
if (isset($output_array[1][0]) && !empty($output_array[1][0])) { if (isset($output_array[1][0]) && !empty($output_array[1][0])) {
@ -190,7 +217,7 @@ class system_bind {
if (! is_dir($target_dir)) mkdir($target_dir); // create dir if (! is_dir($target_dir)) mkdir($target_dir); // create dir
// Generate the key // Generate the key
$old_dir=getcwd(); $old_dir = getcwd();
chdir($target_dir); chdir($target_dir);
exec('opendkim-genkey -r -d '.escapeshellarg($domain).' -s "alternc" '); exec('opendkim-genkey -r -d '.escapeshellarg($domain).' -s "alternc" ');
chdir($old_dir); chdir($old_dir);
@ -220,31 +247,31 @@ class system_bind {
if (! file_exists("/etc/opendkim/keys/$domain/alternc.txt")) continue; if (! file_exists("/etc/opendkim/keys/$domain/alternc.txt")) continue;
// Modif the files. // Modif the files.
$trusted_host_new.="$domain\n"; $trusted_host_new .= "$domain\n";
$keytable_new .="alternc._domainkey.$domain $domain:alternc:/etc/opendkim/keys/$domain/alternc.private\n"; $keytable_new .= "alternc._domainkey.$domain $domain:alternc:/etc/opendkim/keys/$domain/alternc.private\n";
$signingtable_new.="$domain alternc._domainkey.$domain\n"; $signingtable_new .= "$domain alternc._domainkey.$domain\n";
} }
$trusted_host_new.="# END AUTOMATIC FILE. ADD YOUR CHANGES AFTER THIS LINE\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"; $keytable_new .= "# END AUTOMATIC FILE. ADD YOUR CHANGES AFTER THIS LINE\n";
$signingtable_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 # Get old files
$trusted_host_old=@file_get_contents($this->dkim_trusted_host_file); $trusted_host_old = @file_get_contents($this->dkim_trusted_host_file);
$keytable_old =@file_get_contents($this->dkim_keytable_file); $keytable_old = @file_get_contents($this->dkim_keytable_file);
$signingtable_old=@file_get_contents($this->dkim_signingtable_file); $signingtable_old = @file_get_contents($this->dkim_signingtable_file);
# Keep manuel entry # Keep manuel entry
preg_match_all('/\#\s*END\ AUTOMATIC\ FILE\.\ ADD\ YOUR\ CHANGES\ AFTER\ THIS\ LINE(.*)/s', $trusted_host_old, $output_array); preg_match_all('/\#\s*END\ AUTOMATIC\ FILE\.\ ADD\ YOUR\ CHANGES\ AFTER\ THIS\ LINE(.*)/s', $trusted_host_old, $output_array);
if (isset($output_array[1][0]) && !empty($output_array[1][0])) { if (isset($output_array[1][0]) && !empty($output_array[1][0])) {
$trusted_host_new.=$output_array[1][0]; $trusted_host_new .= $output_array[1][0];
} }
preg_match_all('/\#\s*END\ AUTOMATIC\ FILE\.\ ADD\ YOUR\ CHANGES\ AFTER\ THIS\ LINE(.*)/s', $keytable_old, $output_array); preg_match_all('/\#\s*END\ AUTOMATIC\ FILE\.\ ADD\ YOUR\ CHANGES\ AFTER\ THIS\ LINE(.*)/s', $keytable_old, $output_array);
if (isset($output_array[1][0]) && !empty($output_array[1][0])) { if (isset($output_array[1][0]) && !empty($output_array[1][0])) {
$keytable_new.=$output_array[1][0]; $keytable_new .= $output_array[1][0];
} }
preg_match_all('/\#\s*END\ AUTOMATIC\ FILE\.\ ADD\ YOUR\ CHANGES\ AFTER\ THIS\ LINE(.*)/s', $signingtable_old, $output_array); preg_match_all('/\#\s*END\ AUTOMATIC\ FILE\.\ ADD\ YOUR\ CHANGES\ AFTER\ THIS\ LINE(.*)/s', $signingtable_old, $output_array);
if (isset($output_array[1][0]) && !empty($output_array[1][0])) { if (isset($output_array[1][0]) && !empty($output_array[1][0])) {
$signingtable_new.=$output_array[1][0]; $signingtable_new .= $output_array[1][0];
} }
// Save if there are some diff // Save if there are some diff
@ -265,7 +292,7 @@ class system_bind {
* @return string * @return string
*/ */
function dkim_entry($domain) { function dkim_entry($domain) {
$keyfile="/etc/opendkim/keys/$domain/alternc.txt"; $keyfile = "/etc/opendkim/keys/$domain/alternc.txt";
$domainInfo = $this->get_domain_summary($domain); $domainInfo = $this->get_domain_summary($domain);
if (! file_exists($keyfile) && $domainInfo['gesmx'] ) { if (! file_exists($keyfile) && $domainInfo['gesmx'] ) {
$this->dkim_generate_key($domain); $this->dkim_generate_key($domain);
@ -281,9 +308,9 @@ class system_bind {
* @return string * @return string
*/ */
function mail_autoconfig_entry($domain) { function mail_autoconfig_entry($domain) {
$zone= implode("\n",$this->conf_from_db($domain))."\n".$this->get_persistent($domain); $zone = implode("\n",$this->conf_from_db($domain))."\n".$this->get_persistent($domain);
$entry=''; $entry = '';
$domainInfo = $this->get_domain_summary($domain); $domainInfo = $this->get_domain_summary($domain);
if ( $domainInfo['gesmx'] ) { if ( $domainInfo['gesmx'] ) {
// If we manage the mail // If we manage the mail
@ -291,10 +318,10 @@ class system_bind {
// Check if there is no the same entry (defined or manual) // Check if there is no the same entry (defined or manual)
// can be toto IN A or toto.fqdn.tld. IN A // can be toto IN A or toto.fqdn.tld. IN A
if (! preg_match("/autoconfig(\s|\.".str_replace('.','\.',$domain)."\.)/", $zone )) { if (! preg_match("/autoconfig(\s|\.".str_replace('.','\.',$domain)."\.)/", $zone )) {
$entry.="autoconfig IN CNAME %%fqdn%%.\n"; $entry .= "autoconfig IN CNAME %%fqdn%%.\n";
} }
if (! preg_match("/autodiscover(\s|\.".str_replace('.','\.',$domain)."\.)/", $zone )) { if (! preg_match("/autodiscover(\s|\.".str_replace('.','\.',$domain)."\.)/", $zone )) {
$entry.="autodiscover IN CNAME %%fqdn%%.\n"; $entry .= "autodiscover IN CNAME %%fqdn%%.\n";
} }
} // if gesmx } // if gesmx
return $entry; return $entry;
@ -317,12 +344,12 @@ class system_bind {
function get_zone($domain) { function get_zone($domain) {
global $L_FQDN, $L_NS1_HOSTNAME, $L_NS2_HOSTNAME, $L_DEFAULT_MX, $L_DEFAULT_SECONDARY_MX, $L_PUBLIC_IP; global $L_FQDN, $L_NS1_HOSTNAME, $L_NS2_HOSTNAME, $L_DEFAULT_MX, $L_DEFAULT_SECONDARY_MX, $L_PUBLIC_IP;
$zone =$this->get_zone_header(); $zone = $this->get_zone_header();
$zone.=implode("\n",$this->conf_from_db($domain)); $zone .= implode("\n",$this->conf_from_db($domain));
$zone.="\n;;;HOOKED ENTRY\n"; $zone .= "\n;;;HOOKED ENTRY\n";
$zone.= $this->dkim_entry($domain); $zone .= $this->dkim_entry($domain);
$zone.= $this->mail_autoconfig_entry($domain); $zone .= $this->mail_autoconfig_entry($domain);
$zone.="\n;;; END ALTERNC AUTOGENERATE CONFIGURATION\n"; $zone.="\n;;; END ALTERNC AUTOGENERATE CONFIGURATION\n";
$zone.=$this->get_persistent($domain); $zone.=$this->get_persistent($domain);
@ -392,7 +419,7 @@ class system_bind {
} }
// Save file, and apply chmod/chown // Save file, and apply chmod/chown
$file=$this->get_zone_file_uri($domain); $file = $this->get_zone_file_uri($domain);
file_put_contents($file, $this->get_zone($domain)); file_put_contents($file, $this->get_zone($domain));
chown($file, 'bind'); chown($file, 'bind');
chmod($file, 0640); chmod($file, 0640);
@ -408,7 +435,7 @@ class system_bind {
* @return boolean * @return boolean
*/ */
function delete_zone($domain) { function delete_zone($domain) {
$file=$this->get_zone_file_uri($domain); $file = $this->get_zone_file_uri($domain);
if (file_exists($file)) { if (file_exists($file)) {
unlink($file); unlink($file);
} }
@ -424,11 +451,11 @@ class system_bind {
function reload_named() { function reload_named() {
global $hooks; global $hooks;
// Generate the new conf file // 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"; $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); $tpl = file_get_contents($this->NAMED_TEMPLATE);
foreach ($this->get_domain_summary() as $domain => $ds ) { foreach ($this->get_domain_summary() as $domain => $ds ) {
if ( ! $ds['gesdns'] || strtoupper($ds['dns_action']) == 'DELETE' ) continue; 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))); $new_named_conf .= strtr($tpl, array("@@DOMAINE@@"=>$domain, "@@ZONE_FILE@@"=>$this->get_zone_file_uri($domain)));
} }
// Get the actual conf file // Get the actual conf file

View File

@ -91,9 +91,9 @@ class DB_Sql {
/* establish connection, select database */ /* establish connection, select database */
if ( 0 == $this->Link_ID ) { if ( 0 == $this->Link_ID ) {
$this->Link_ID=mysql_pconnect($Host, $User, $Password); $this->Link_ID=mysql_connect($Host, $User, $Password);
if (!$this->Link_ID) { if (!$this->Link_ID) {
$this->halt("pconnect($Host, $User, \$Password) failed."); $this->halt("connect($Host, $User, \$Password) failed.");
return 0; return 0;
} }

View File

@ -196,6 +196,7 @@ class m_action {
global $db, $err; global $db, $err;
$err->log("action", "set", $type); $err->log("action", "set", $type);
$serialized = serialize($parameters); $serialized = serialize($parameters);
switch ($type) { switch ($type) {
case 'chmod': case 'chmod':
$query = "insert into actions values ('','CHMOD','$serialized',now(),'','','$user','');"; $query = "insert into actions values ('','CHMOD','$serialized',now(),'','','$user','');";
@ -224,6 +225,7 @@ class m_action {
default: default:
return false; return false;
} }
if (!$db->query($query)) { if (!$db->query($query)) {
$err->raise("action", _("Error setting actions")); $err->raise("action", _("Error setting actions"));
return false; return false;

View File

@ -111,6 +111,11 @@ class m_bro {
$root_alternc=$root ; $root_alternc=$root ;
// Passage du root en chemin rel (diffrent avec un lien) // Passage du root en chemin rel (diffrent avec un lien)
$root=realpath($root) ; $root=realpath($root) ;
if (! $root=realpath($root)) {
// Guillaume: it needed to work.. if file doesn't exist it need to crash
// gently
$root=$root_alternc;
}
// separer le chemin entre le repertoire et le fichier // separer le chemin entre le repertoire et le fichier
$file=basename($dir); $file=basename($dir);
$dir=dirname($dir); $dir=dirname($dir);
@ -556,7 +561,7 @@ class m_bro {
* @return boolean TRUE Si les fichiers ont t renomms, FALSE si une erreur s'est produite. * @return boolean TRUE Si les fichiers ont t renomms, FALSE si une erreur s'est produite.
*/ */
function ChangePermissions($R,$d,$perm,$verbose=false) { function ChangePermissions($R,$d,$perm,$verbose=false) {
global $err,$action; global $err, $action;
$absolute=$this->convertabsolute($R,false); $absolute=$this->convertabsolute($R,false);
if (!$absolute) { if (!$absolute) {
$err->raise("bro",_("File or folder name is incorrect")); $err->raise("bro",_("File or folder name is incorrect"));
@ -1022,6 +1027,9 @@ class m_bro {
header("Content-Transfer-Encoding: binary"); header("Content-Transfer-Encoding: binary");
$d=escapeshellarg(".".$this->convertabsolute($dir,true)); $d=escapeshellarg(".".$this->convertabsolute($dir,true));
set_time_limit(0); set_time_limit(0);
// relacher le lock global sinon ce download va geler alternc pour
// tout le monde
alternc_shutdown();
passthru("/bin/tar -cZ -C ".getuserpath()."/".$mem->user["login"]."/ $d"); passthru("/bin/tar -cZ -C ".getuserpath()."/".$mem->user["login"]."/ $d");
} }
@ -1040,6 +1048,9 @@ class m_bro {
header("Content-Transfer-Encoding: binary"); header("Content-Transfer-Encoding: binary");
$d=escapeshellarg(".".$this->convertabsolute($dir,true)); $d=escapeshellarg(".".$this->convertabsolute($dir,true));
set_time_limit(0); set_time_limit(0);
// relacher le lock global sinon ce download va geler alternc pour
// tout le monde
alternc_shutdown();
passthru("/bin/tar -cz -C ".getuserpath()."/ $d"); passthru("/bin/tar -cz -C ".getuserpath()."/ $d");
} }
@ -1058,6 +1069,9 @@ class m_bro {
header("Content-Transfer-Encoding: binary"); header("Content-Transfer-Encoding: binary");
$d=escapeshellarg(".".$this->convertabsolute($dir,true)); $d=escapeshellarg(".".$this->convertabsolute($dir,true));
set_time_limit(0); set_time_limit(0);
// relacher le lock global sinon ce download va geler alternc pour
// tout le monde
alternc_shutdown();
passthru("/bin/tar -cj -C ".getuserpath()."/ $d"); passthru("/bin/tar -cj -C ".getuserpath()."/ $d");
} }

View File

@ -580,7 +580,8 @@ class m_dom {
} }
} }
$db->query("update sub_domaines set enable='$status' where id = '" . intval($sub_id) . "';"); $db->query("update sub_domaines set enable='$status',web_action='UPDATE' where id = '" . intval($sub_id) . "';"); // UGLY patch fix activate deactivate sub-domains #1645
$this->set_dns_action($jh['domain'], 'UPDATE'); $this->set_dns_action($jh['domain'], 'UPDATE');
return true; return true;
@ -736,7 +737,7 @@ class m_dom {
return false; return false;
} }
if ($dns && $v == -3) { if ($dns && $v == -3) {
$err->raise("dom", _("The domain cannot be found in the whois database")); $err->raise("dom", _("The name servers referenced by this domain do not match those referenced by this AlternC instance"));
return false; return false;
} }
@ -998,7 +999,7 @@ class m_dom {
$ligne = preg_replace("/^ *([^ ]*) \(.*\)$/", "\\1", trim($ligne)); $ligne = preg_replace("/^ *([^ ]*) \(.*\)$/", "\\1", trim($ligne));
if ($found) if ($found)
$tmp = trim($ligne); $tmp = trim($ligne);
if ($tmp) if (isset($tmp) && $tmp)
$serveurList[] = $tmp; $serveurList[] = $tmp;
if ($ligne == "Nameservers:") { if ($ligne == "Nameservers:") {
$state = 1; $state = 1;
@ -1503,7 +1504,7 @@ class m_dom {
* TRUE sinon. * TRUE sinon.
* *
*/ */
function edit_domain($dom, $dns, $gesmx, $force = false, $ttl = 86400) { function edit_domain($dom, $dns, $gesmx, $force = false, $ttl = 3600) {
global $db, $err, $L_MX, $classes, $cuid, $hooks; global $db, $err, $L_MX, $classes, $cuid, $hooks;
$err->log("dom", "edit_domain", $dom . "/" . $dns . "/" . $gesmx); $err->log("dom", "edit_domain", $dom . "/" . $dns . "/" . $gesmx);
// Locked ? // Locked ?
@ -1530,7 +1531,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) { if ($ttl == 0) {
$ttl = 86400; $ttl = 3600;
} }
$t = checkfqdn($dom); $t = checkfqdn($dom);
@ -1974,8 +1975,6 @@ class m_dom {
if ($only_apache) { if ($only_apache) {
$params.=" and dt.only_dns is false "; $params.=" and dt.only_dns is false ";
} }
// BUG BUG BUG FIXME
// Suppression de comptes -> membres existe pas -> domaines a supprimer ne sont pas lister
$db->query(" $db->query("
select select
sd.id as sub_id, sd.id as sub_id,
@ -1991,6 +1990,8 @@ from
domaines_type dt domaines_type dt
where where
v.name='mailname_bounce' v.name='mailname_bounce'
and sd.web_action in ('OK', 'UPDATE')
and sd.enable in ('ENABLE', 'ENABLED')
and lower(dt.name) = lower(sd.type) and lower(dt.name) = lower(sd.type)
$params $params
order by order by
@ -2067,7 +2068,7 @@ order by
// Initialize duplicate check // Initialize duplicate check
$check_dup = array(); $check_dup = array();
$ret = ''; $ret = "## AlternC Generated conf\n";
foreach ($lst as $p) { foreach ($lst as $p) {
// Check if duplicate // Check if duplicate
if (in_array($p['fqdn'], $check_dup)) { if (in_array($p['fqdn'], $check_dup)) {
@ -2126,11 +2127,32 @@ order by
break; break;
default: default:
$sql = "UPDATE sub_domaines SET web_action='OK' WHERE id='$sub_domain_id'; "; $sql = "UPDATE sub_domaines SET web_action='OK' WHERE id='$sub_domain_id'; ";
//UGLY PATCH activate / deactivate sub-domains #1645
$sqla= " UPDATE sub_domaines SET enable='ENABLED' WHERE id =$sub_domain_id and enable='ENABLE'; ";
$db->query($sqla);
$sqlb= " UPDATE sub_domaines SET enable='DISABLED' WHERE id =$sub_domain_id and enable='DISABLE'; ";
$db->query($sqlb);
//UGLY PATCH activate / deactivate sub-domains #1645
} }
$db->query($sql); $db->query($sql);
return true; return true;
} }
/**
* @param string $domain_id: domain id to delete from database
* called from generate_apacheconf.php after a domain deletion
**/
function domain_delete() {
global $db,$err;
$err->log("dom", "domain_delete");
$sql = "delete from domaines where dns_action = 'delete' and domaine not in (select domaine from sub_domaines);";
if(!$db->query($sql)){
$err->raise("dom", "Error deleting domain from database");
return false;
}
return true;
}
/** /**
* @param string $dns_action * @param string $dns_action
*/ */
@ -2172,17 +2194,26 @@ order by
// by subdomain // by subdomain
$tmp = array(); $tmp = array();
foreach ($da['sub'] as $sub) { foreach ($da['sub'] as $sub) {
if ($sub['web_action']!='OK') continue; // Skip when disable or deleted
if (!$sub['only_dns']) { if ($sub['enable']=='DISABLE') continue;
if ($sub['enable']=='DISABLED') continue;
if ($sub['web_action']=='DELETE') continue;
// Skip if "only_dns" and no conf generated
if ($sub['only_dns']) continue;
// Init the value in the tmp array
if (!isset($tmp[$sub['fqdn']])) { if (!isset($tmp[$sub['fqdn']])) {
$tmp[$sub['fqdn']] = 0; $tmp[$sub['fqdn']] = 0;
} }
// Increment value
$tmp[$sub['fqdn']]++; $tmp[$sub['fqdn']]++;
// If there is more than 1 configuration file for this FQDN, alert !
if ($tmp[$sub['fqdn']] >= 2) { if ($tmp[$sub['fqdn']] >= 2) {
$errors[$sub['fqdn']] = sprintf(_("Problem on %s: there is more than 1 web configuration going to be generated for this sub-domain."), $sub['fqdn']); $errors[$sub['fqdn']] = sprintf(_("Problem on %s: there is more than 1 web configuration going to be generated for this sub-domain."), $sub['fqdn']);
} }
} }
}
// Check if we know each type of subdomain // Check if we know each type of subdomain
// Example: we may not know WEBMAIL if we upgrade from a previous setup // Example: we may not know WEBMAIL if we upgrade from a previous setup

View File

@ -112,6 +112,10 @@ class m_piwik {
$user_creation_date = $user->date_registered; $user_creation_date = $user->date_registered;
return $db->query("INSERT INTO piwik_users (uid, login, created_date) VALUES ('$cuid', '$user_login', '$user_creation_date')"); return $db->query("INSERT INTO piwik_users (uid, login, created_date) VALUES ('$cuid', '$user_login', '$user_creation_date')");
} }
else {
$err->raise('piwik', $api_data->message);
return FALSE;
}
} else { // api_data = false -> error is already filled } else { // api_data = false -> error is already filled
return FALSE; return FALSE;
} }
@ -256,11 +260,7 @@ class m_piwik {
$user_data = $this->call_privileged_page('API', 'UsersManager.getUsersAccessFromSite', array('idSite' => $site->idsite)); $user_data = $this->call_privileged_page('API', 'UsersManager.getUsersAccessFromSite', array('idSite' => $site->idsite));
//if (is_array($user_data)) { @$item->rights = $user_data[0];
// printvar($user_data);
//} else if(is_object($user_data)) {
$item->rights = $user_data[0];
//}
$data[] = $item; $data[] = $item;
} }

View File

@ -172,7 +172,7 @@ class m_quota {
} }
reset($this->disk); reset($this->disk);
if (!empty ($this->disk)) { // Check if there are some disk quota to check if ($this->disk_quota_enable && !empty ($this->disk)) { // Check if there are some disk quota to check
// Look if there are some cached value // Look if there are some cached value
$disk_cached = $mem->session_tempo_params_get('quota_cache_disk'); $disk_cached = $mem->session_tempo_params_get('quota_cache_disk');

View File

@ -24,13 +24,13 @@ case "$1" in
dpkg-statoverride --list /etc/roundcube/debian-db.php >/dev/null && dpkg-statoverride --list /etc/roundcube/debian-db.php >/dev/null &&
dpkg-statoverride --remove /etc/roundcube/debian-db.php dpkg-statoverride --remove /etc/roundcube/debian-db.php
chown -R www-data:root /etc/roundcube/debian-db.php chown root:www-data /etc/roundcube/debian-db.php
chmod -R 460 /etc/roundcube/debian-db.php chmod 640 /etc/roundcube/debian-db.php
dpkg-statoverride --list /etc/roundcube/main.inc.php >/dev/null && dpkg-statoverride --list /etc/roundcube/main.inc.php >/dev/null &&
dpkg-statoverride --remove /etc/roundcube/main.inc.php dpkg-statoverride --remove /etc/roundcube/main.inc.php
chown -R www-data:root /etc/roundcube/main.inc.php chown root:www-data /etc/roundcube/main.inc.php
chmod -R 460 /etc/roundcube/main.inc.php chmod 640 /etc/roundcube/main.inc.php
dpkg-statoverride --list /var/log/roundcube >/dev/null && dpkg-statoverride --list /var/log/roundcube >/dev/null &&
dpkg-statoverride --remove /var/log/roundcube dpkg-statoverride --remove /var/log/roundcube

7
debian/changelog vendored
View File

@ -1,3 +1,10 @@
alternc (3.5~rc1) stable; urgency=low
* unofficial Prerelease of AlternC 3.5
* update_domaines now in PHP and using classes and hooks instead of BASH
-- Benjamin Sonntag <benjamin@sonntag.fr> Thu, 7 May 2015 20:03:00 +0200
alternc (3.1.6) oldstable; urgency=low alternc (3.1.6) oldstable; urgency=low
* add SSL and API alternc packages (Beta) * add SSL and API alternc packages (Beta)

143
debian/control vendored
View File

@ -15,47 +15,49 @@ Pre-depends: debconf (>= 0.5.00) | debconf-2.0
, bash (>= 4) , bash (>= 4)
, acl , acl
Depends: debianutils (>= 1.13.1) Depends: debianutils (>= 1.13.1)
, adduser
, apache2-mpm-itk , apache2-mpm-itk
, bind9
, bzip2
, ca-certificates
, cron
, dnsutils
, dovecot-common (>=1:2.1.7)
, dovecot-imapd
, dovecot-managesieved
, dovecot-mysql
, dovecot-pop3d
, dovecot-sieve
, gettext (>= 0.10.40-5)
, incron
, libapache2-mod-php5 , libapache2-mod-php5
, libsasl2-modules
, locales
, lockfile-progs (>= 0.1.9)
, mailutils | mailx
, mysql-client(>= 5.0)
, opendkim
, opendkim-tools
, perl-suid | perl
, php5-cli
, php5-curl
, php5-mysql , php5-mysql
, phpmyadmin , phpmyadmin
, postfix , postfix
, proftpd-mod-mysql
, proftpd-basic
, bind9
, wget
, rsync
, ca-certificates
, locales
, perl-suid | perl
, postfix-mysql , postfix-mysql
, wwwconfig-common , proftpd-basic
, proftpd-mod-mysql
, rsync
, sasl2-bin , sasl2-bin
, libsasl2-modules
, php5-cli
, lockfile-progs (>= 0.1.9)
, gettext (>= 0.10.40-5)
, sudo , sudo
, adduser , unzip
, mysql-client
, dnsutils
, dovecot-common (>=1:1.2.15)
, dovecot-common(<< 1:2.0)
, dovecot-imapd (>= 1:1.2.15)
, dovecot-pop3d (>= 1:1.2.15)
, vlogger , vlogger
, mailutils | mailx , wget
, incron , wwwconfig-common
, cron
, opendkim
, mysql-client(>= 5.0)
, php5-curl
, ${misc:Depends} , ${misc:Depends}
Recommends: mysql-server(>= 5.0) Recommends: mysql-server(>= 5.0)
, ntp , ntp
, quota , quota
, unzip
, bzip2
Conflicts: alternc-admintools Conflicts: alternc-admintools
, alternc-awstats (<< 1.0) , alternc-awstats (<< 1.0)
, alternc-webalizer (<= 0.9.4) , alternc-webalizer (<= 0.9.4)
@ -65,16 +67,16 @@ Provides: alternc-admintools
Replaces: alternc-admintools Replaces: alternc-admintools
Suggests: alternc-awstats Suggests: alternc-awstats
, alternc-mailman , alternc-mailman
, alternc-changepass , alternc-roundcube
, alternc-squirrelmail
, alternc-api
, alternc-ssl
, amavisd-new , amavisd-new
, clamav-daemon , clamav-daemon
, spamassassin
, pop-before-smtp
, magpierss
, zip
, ncompress , ncompress
, alternc-squirrelmail , pop-before-smtp
, alternc-roundcube , spamassassin
, zip
Description: Hosting software managment suite for Debian Description: Hosting software managment suite for Debian
AlternC is a mutualized hosting software manager for Linux. AlternC is a mutualized hosting software manager for Linux.
It allows you to manage your websites, domains, ftp, emails, aliases, It allows you to manage your websites, domains, ftp, emails, aliases,
@ -99,42 +101,46 @@ Package: alternc-slave
Architecture: all Architecture: all
Pre-depends: debconf (>= 0.5.00) | debconf-2.0, acl Pre-depends: debconf (>= 0.5.00) | debconf-2.0, acl
Depends: debianutils (>= 1.13.1) Depends: debianutils (>= 1.13.1)
, adduser
, apache2-mpm-itk , apache2-mpm-itk
, bind9
, bzip2
, ca-certificates
, cron
, dovecot-common (>= 1:2.1.7)
, dovecot-imapd
, dovecot-managesieved
, dovecot-mysql
, dovecot-pop3d
, dovecot-sieve
, gettext (>= 0.10.40-5)
, incron
, libapache2-mod-php5 , libapache2-mod-php5
, libsasl2-modules
, locales
, lockfile-progs (>= 0.1.9)
, mailutils | mailx
, mysql-client(>= 5.0)
, opendkim
, opendkim-tools
, perl
, perl-suid
, php5-cli
, php5-curl
, php5-mysql , php5-mysql
, phpmyadmin , phpmyadmin
, postfix , postfix
, proftpd-mod-mysql
, proftpd-basic
, postfix-tls
, bind9
, wget
, rsync
, ca-certificates
, locales
, perl-suid
, perl
, postfix-mysql , postfix-mysql
, wwwconfig-common , postfix-tls
, proftpd-basic
, proftpd-mod-mysql
, rsync
, sasl2-bin , sasl2-bin
, libsasl2-modules
, php5-cli
, lockfile-progs (>= 0.1.9)
, gettext (>= 0.10.40-5)
, adduser
, mysql-client
, sudo , sudo
, dovecot-common (>=1:1.2.15) , unzip
, dovecot-common(<< 1:2.0)
, dovecot-imapd (>= 1:1.2.15)
, dovecot-pop3d (>= 1:1.2.15)
, vlogger , vlogger
, mailutils | mailx , wget
, incron , wwwconfig-common
, cron
, opendkim
, mysql-client(>= 5.0)
, php5-curl
, ${misc:Depends} , ${misc:Depends}
Recommends: Recommends:
quota quota
@ -146,15 +152,16 @@ Provides: alternc
Replaces: alternc Replaces: alternc
Suggests: alternc-awstats Suggests: alternc-awstats
, alternc-mailman , alternc-mailman
, alternc-changepass , alternc-roundcube
, alternc-squirrelmail
, alternc-api
, alternc-ssl
, amavisd-new , amavisd-new
, clamav-daemon , clamav-daemon
, spamassassin
, pop-before-smtp
, magpierss
, zip
, ncompress , ncompress
, bzip2 , pop-before-smtp
, spamassassin
, zip
Description: Hosting software managment suite for Debian Description: Hosting software managment suite for Debian
AlternC is a mutualized hosting software manager for Linux. AlternC is a mutualized hosting software manager for Linux.
It allows you to manage your websites, domains, ftp, emails, aliases, It allows you to manage your websites, domains, ftp, emails, aliases,

View File

@ -35,7 +35,7 @@ ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
php_admin_flag safe_mode off php_admin_flag safe_mode off
AddDefaultCharset UTF-8 AddDefaultCharset UTF-8
# open_basedir allows access to specifics directories. We need to grant access to these directories for alternc, awstats, mailman... # open_basedir allows access to specifics directories. We need to grant access to these directories for alternc, awstats, mailman...
php_admin_value open_basedir /usr/share/alternc-mailman/patches/:/etc/alternc/:/var/run/alternc/:/usr/share/alternc/panel/:%%ALTERNC_HTML%%/:/tmp:/usr/share/php/:/var/cache/alternc-webalizer/:/etc/locale.gen:%%ALTERNC_LOGS%%:/etc/awstats/:/var/log/alternc/:/var/lib/alternc/panel/ php_admin_value open_basedir /usr/share/alternc-mailman/patches/:/etc/alternc/:/run/alternc/:/var/run/alternc/:/usr/share/alternc/panel/:%%ALTERNC_HTML%%/:/tmp:/usr/share/php/:/var/cache/alternc-webalizer/:/etc/locale.gen:%%ALTERNC_LOGS%%:/etc/awstats/:/var/log/alternc/:/var/lib/alternc/panel/
</Directory> </Directory>

View File

@ -28,7 +28,6 @@ smtpd_sasl_security_options = noanonymous
broken_sasl_auth_clients = yes broken_sasl_auth_clients = yes
smtpd_sasl_type=dovecot smtpd_sasl_type=dovecot
smtpd_sasl_path=private/auth smtpd_sasl_path=private/auth
smtpd_sasl_auth_enable=yes
#Virtual Maping #Virtual Maping
alias_maps = hash:/etc/aliases alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases alias_database = hash:/etc/aliases

View File

@ -3,10 +3,9 @@
# and launch alternc.install if you want # and launch alternc.install if you want
# to modify this file. # to modify this file.
# #
# This file is opened as root, so it should be owned by root and mode 0600. # This file is opened as root, so it should be owned by root and mode 0600.
# #
# http://wiki.dovecot.org/AuthDatabase/SQL # http://wiki2.dovecot.org/AuthDatabase/SQL
# #
# For the sql passdb module, you'll need a database with a table that # For the sql passdb module, you'll need a database with a table that
# contains fields for at least the username and password. If you want to # contains fields for at least the username and password. If you want to
@ -36,9 +35,14 @@ driver = mysql
# Database connection string. This is driver-specific setting. # Database connection string. This is driver-specific setting.
# #
# HA / round-robin load-balancing is supported by giving multiple host
# settings, like: host=sql1.host.org host=sql2.host.org
#
# pgsql: # pgsql:
# For available options, see the PostgreSQL documention for the # For available options, see the PostgreSQL documention for the
# PQconnectdb function of libpq. # PQconnectdb function of libpq.
# Use maxconns=n (default 5) to change how many connections Dovecot can
# create to pgsql.
# #
# mysql: # mysql:
# Basic options emulate PostgreSQL option names: # Basic options emulate PostgreSQL option names:
@ -53,11 +57,9 @@ driver = mysql
# the default my.cnf location # the default my.cnf location
# option_group - Read options from the given group (default: client) # option_group - Read options from the given group (default: client)
# #
# You can connect to UNIX sockets by using host: host=/var/run/mysqld/mysqld.sock # You can connect to UNIX sockets by using host: host=/var/run/mysql.sock
# Note that currently you can't use spaces in parameters. # Note that currently you can't use spaces in parameters.
# #
# MySQL supports multiple host parameters for load balancing / HA.
#
# sqlite: # sqlite:
# The path to the database file. # The path to the database file.
# #
@ -71,7 +73,7 @@ connect = host=%%dbhost%% dbname=%%dbname%% user=%%db_mail_user%% password=%%db_
# Default password scheme. # Default password scheme.
# #
# List of supported schemes is in # List of supported schemes is in
# http://wiki.dovecot.org/Authentication/PasswordSchemes # http://wiki2.dovecot.org/Authentication/PasswordSchemes
# #
default_pass_scheme = MD5 default_pass_scheme = MD5
@ -86,9 +88,9 @@ default_pass_scheme = MD5
# and "domain" fields instead of "user". # and "domain" fields instead of "user".
# #
# The query can also return other fields which have a special meaning, see # The query can also return other fields which have a special meaning, see
# http://wiki.dovecot.org/PasswordDatabase/ExtraFields # http://wiki2.dovecot.org/PasswordDatabase/ExtraFields
# #
# Commonly used available substitutions (see http://wiki.dovecot.org/Variables # Commonly used available substitutions (see http://wiki2.dovecot.org/Variables
# for full list): # for full list):
# %u = entire user@domain # %u = entire user@domain
# %n = user part of user@domain # %n = user part of user@domain
@ -115,18 +117,23 @@ default_pass_scheme = MD5
# None of these are strictly required. If you use a single UID and GID, and # None of these are strictly required. If you use a single UID and GID, and
# home or mail directory fits to a template string, you could use userdb static # home or mail directory fits to a template string, you could use userdb static
# instead. For a list of all fields that can be returned, see # instead. For a list of all fields that can be returned, see
# http://wiki.dovecot.org/UserDatabase/ExtraFields # http://wiki2.dovecot.org/UserDatabase/ExtraFields
# #
# Examples: # Examples:
# user_query = SELECT home, uid, gid FROM users WHERE userid = '%u' # user_query = SELECT home, uid, gid FROM users WHERE userid = '%u'
# user_query = SELECT dir AS home, user AS uid, group AS gid FROM users where userid = '%u' # user_query = SELECT dir AS home, user AS uid, group AS gid FROM users where userid = '%u'
# user_query = SELECT home, 501 AS uid, 501 AS gid FROM users WHERE userid = '%u' # user_query = SELECT home, 501 AS uid, 501 AS gid FROM users WHERE userid = '%u'
# #
user_query = SELECT userdb_home AS home, userdb_uid AS uid, 1998 AS gid, userdb_quota_rule AS quota_rule FROM dovecot_view WHERE user = '%u'; user_query = SELECT userdb_home AS home, 1998 AS uid, userdb_gid AS gid, userdb_quota_rule AS quota_rule FROM dovecot_view WHERE user = '%u';
# If you wish to avoid two SQL lookups (passdb + userdb), you can use # If you wish to avoid two SQL lookups (passdb + userdb), you can use
# userdb prefetch instead of userdb sql in dovecot.conf. In that case you'll # userdb prefetch instead of userdb sql in dovecot.conf. In that case you'll
# also have to return userdb fields in password_query prefixed with "userdb_" # also have to return userdb fields in password_query prefixed with "userdb_"
# string. For example: # string. For example:
password_query = SELECT user, password, userdb_home, userdb_uid, 1998 AS userdb_gid,userdb_quota_rule FROM dovecot_view where user= '%u'; #
password_query = SELECT user, password, userdb_home, 1998 AS userdb_uid, userdb_gid,userdb_quota_rule FROM dovecot_view where user= '%u';
# Query to get a list of all usernames.
#iterate_query = SELECT username AS user FROM users

View File

@ -0,0 +1,342 @@
# AUTO GENERATED FILE
# Modify template in /etc/alternc/templates/
# and launch alternc.install if you want
# to modify this file.
#
## Dovecot configuration file
# This is a concatenation of all /etc/dovecot/conf.d/* from DEBIAN package
# with rules adapted to AlternC best practices and link with MySQL tables.
protocols = imap pop3 sieve
## -------------------------------------------------------------------------
## 10-auth
# Disable LOGIN command and all other plaintext authentications unless
# SSL/TLS is used (LOGINDISABLED capability). Note that if the remote IP
# matches the local IP (ie. you're connecting from the same computer), the
# connection is considered secure and plaintext authentication is allowed.
disable_plaintext_auth = no
# Space separated list of wanted authentication mechanisms:
# plain login digest-md5 cram-md5 ntlm rpa apop anonymous gssapi otp skey
# gss-spnego
# NOTE: See also disable_plaintext_auth setting.
auth_mechanisms = plain login
##
## Password and user databases
##
#
# Password database is used to verify user's password (and nothing more).
# You can have multiple passdbs and userdbs. This is useful if you want to
# allow both system users (/etc/passwd) and virtual users to login without
# duplicating the system users into virtual database.
#
# <doc/wiki/PasswordDatabase.txt>
#
# User database specifies where mails are located and what user/group IDs
# own them. For single-UID configuration use "static" userdb.
#
# <doc/wiki/UserDatabase.txt>
#!include auth-deny.conf.ext
#!include auth-master.conf.ext
#!include auth-system.conf.ext
#!include auth-sql.conf.ext
#!include auth-ldap.conf.ext
#!include auth-passwdfile.conf.ext
#!include auth-checkpassword.conf.ext
#!include auth-vpopmail.conf.ext
#!include auth-static.conf.ext
# ----------------------------------------------------------------------------
# 10-login.conf
# Prefix for each line written to log file. % codes are in strftime(3)
# format.
#log_timestamp = "%b %d %H:%M:%S "
log_timestamp = "%Y-%m-%d %H:%M:%S "
# ----------------------------------------------------------------------------
# 10-mail.conf
# Location for users' mailboxes. This is the same as the old default_mail_env
# setting. The default is empty, which means that Dovecot tries to find the
# mailboxes automatically. This won't work if the user doesn't have any mail
# yet, so you should explicitly tell Dovecot the full location.
#
# If you're using mbox, giving a path to the INBOX file (eg. /var/mail/%u)
# isn't enough. You'll also need to tell Dovecot where the other mailboxes are
# kept. This is called the "root mail directory", and it must be the first
# path given in the mail_location setting.
#
# There are a few special variables you can use, eg.:
#
# %u - username
# %n - user part in user@domain, same as %u if there's no domain
# %d - domain part in user@domain, empty if there's no domain
# %h - home directory
#
# See </usr/share/doc/dovecot-common/wiki/Variables.txt> for full list.
# Some examples:
#
# mail_location = maildir:~/Maildir
# mail_location = mbox:~/mail:INBOX=/var/mail/%u
# mail_location = mbox:/var/mail/%d/%1n/%n:INDEX=/var/indexes/%d/%1n/%n
#
# </usr/share/doc/dovecot-common/wiki/MailLocation.txt>
#
mail_location = maildir:~/Maildir
# Group to enable temporarily for privileged operations. Currently this is
# used only with INBOX when either its initial creation or dotlocking fails.
# Typically this is set to "mail" to give access to /var/mail.
#mail_privileged_group =
mail_privileged_group = vmail
# Valid UID range for users, defaults to 500 and above. This is mostly
# to make sure that users can't log in as daemons or other system users.
# Note that denying root logins is hardcoded to dovecot binary and can't
# be done even if first_valid_uid is set to 0.
first_valid_uid = 1998
last_valid_uid = 65000
# ----------------------------------------------------------------------------
# 10-master.conf
passdb {
driver = sql
args = /etc/dovecot/alternc-sql.conf
}
userdb {
driver = sql
args = /etc/dovecot/alternc-sql.conf
}
userdb {
driver = prefetch
}
service auth {
unix_listener /var/spool/postfix/private/auth {
group = postfix
mode = 0660
user = postfix
}
unix_listener auth-master {
mode = 0600
user = vmail
}
# user = vmail
}
# ----------------------------------------------------------------------------
# 10-ssl.conf
# SSL/TLS support: yes, no, required. </usr/share/doc/dovecot-common/wiki/SSL.txt>
ssl = yes
# PEM encoded X.509 SSL/TLS certificate and private key. They're opened before
# dropping root privileges, so keep the key file unreadable by anyone but
# root.
#ssl_cert = </etc/dovecot/dovecot.pem
#ssl_cert_file = /etc/alternc/apache.pem
#ssl_key = </etc/dovecot/dovecot.pem
#ssl_key_file = /etc/alternc/apache.pem
# ----------------------------------------------------------------------------
# 15-lda.conf
##
## LDA specific settings
##
protocol lda {
# Address to use when sending rejection mails (e.g. postmaster@example.com).
postmaster_address = postmaster@localhost
# Hostname to use in various parts of sent mails, eg. in Message-Id.
# Default is the system's real hostname.
#hostname =
# Support for dynamically loadable plugins. mail_plugins is a space separated
# list of plugins to load.
mail_plugins = quota sieve
#mail_plugin_dir = /usr/lib/dovecot/modules/lda
# UNIX socket path to master authentication server to find users.
auth_socket_path = /var/run/dovecot/auth-master
}
# ----------------------------------------------------------------------------
# 20-imap.conf
protocol imap {
# Support for dynamically loadable plugins. mail_plugins is a space separated
# list of plugins to load.
mail_plugins = quota imap_quota
#mail_plugin_dir = /usr/lib/dovecot/modules/imap
}
service imap {
# tell imap to do post-login lookup using a socket called "imap-postlogin"
executable = imap postlogin
}
# The service name below doesn't actually matter.
service postlogin {
# all post-login scripts are executed via script-login binary
executable = script-login /usr/lib/alternc/popimap-log-login.sh
# the script process runs as the user specified here (v2.0.14+):
#user = $default_internal_user
# this UNIX socket listener must use the same name as given to imap executable
unix_listener postlogin {
}
}
# ----------------------------------------------------------------------------
# 20-managesieve.conf
protocol sieve {
managesieve_notify_capability = mailto
managesieve_sieve_capability = fileinto reject envelope encoded-character vacation subaddress comparator-i;ascii-numeric relational regex imap4flags copy include variables body enotify environment mailbox date ihave
}
service managesieve {
executable = /usr/lib/dovecot/managesieve
}
# ----------------------------------------------------------------------------
# 20-pop3.conf
protocol pop3 {
# POP3 UIDL (unique mail identifier) format to use. You can use following
# variables, along with the variable modifiers described in
# </usr/share/doc/dovecot-common/wiki/Variables.txt> (e.g. %Uf for the
# filename in uppercase)
#
# %v - Mailbox's IMAP UIDVALIDITY
# %u - Mail's IMAP UID
# %m - MD5 sum of the mailbox headers in hex (mbox only)
# %f - filename (maildir only)
#
# If you want UIDL compatibility with other POP3 servers, use:
# UW's ipop3d : %08Xv%08Xu
# Courier : %f or %v-%u (both might be used simultaneosly)
# Cyrus (<= 2.1.3) : %u
# Cyrus (>= 2.1.4) : %v.%u
# Dovecot v0.99.x : %v.%u
# tpop3d : %Mf
#
# Note that Outlook 2003 seems to have problems with %v.%u format which was
# Dovecot's default, so if you're building a new server it would be a good
# idea to change this. %08Xu%08Xv should be pretty fail-safe.
#
pop3_uidl_format = %08Xu%08Xv
# Support for dynamically loadable plugins. mail_plugins is a space separated
# list of plugins to load.
mail_plugins = quota
#mail_plugin_dir = /usr/lib/dovecot/modules/pop3
}
service pop3 {
# tell imap to do post-login lookup using a socket called "imap-postlogin"
executable = pop3 postlogin
}
# ----------------------------------------------------------------------------
# 90-plugin.conf
plugin {
# Quota plugin. Multiple backends are supported:
# dirsize: Find and sum all the files found from mail directory.
# Extremely SLOW with Maildir. It'll eat your CPU and disk I/O.
# dict: Keep quota stored in dictionary (eg. SQL)
# maildir: Maildir++ quota
# fs: Read-only support for filesystem quota
#
# Quota limits are set using "quota_rule" parameters, either in here or in
# userdb. It's also possible to give mailbox-specific limits, for example:
# quota_rule = *:storage=1048576
quota_rule = *:storage=100M
quota_rule2 = Trash:storage=+10%%
# quota_rule2 = Trash:storage=102400
# User has now 1GB quota, but when saving to Trash mailbox the user gets
# additional 100MB.
#
# Multiple quota roots are also possible, for example:
# quota = dict:user::proxy::quota
# quota2 = dict:domain:%d:proxy::quota_domain
# quota_rule = *:storage=102400
# quota2_rule = *:storage=1048576
# Gives each user their own 100MB quota and one shared 1GB quota within
# the domain.
#
# You can execute a given command when user exceeds a specified quota limit.
# Each quota root has separate limits. Only the command for the first
# exceeded limit is excecuted, so put the highest limit first.
# Note that % needs to be escaped as %%, otherwise "% " expands to empty.
# quota_warning = storage=95%% /usr/local/bin/quota-warning.sh 95
# quota_warning2 = storage=80%% /usr/local/bin/quota-warning.sh 80
quota_warning = storage=95%% /usr/lib/alternc/quota-warning.sh 95
quota_warning2 = storage=80%% /usr/lib/alternc/quota-warning.sh 80
#quota = maildir
quota = dict:user::proxy::quotadict
# Sieve plugin (http://wiki.dovecot.org/LDA/Sieve) and ManageSieve service
#
# Location of the active script. When ManageSieve is used this is actually
# a symlink pointing to the active script in the sieve storage directory.
sieve=~/.dovecot.sieve
#
# The path to the directory where the personal Sieve scripts are stored. For
# ManageSieve this is where the uploaded scripts are stored.
sieve_dir=~/sieve
}
# Dictionary can be used by some plugins to store key=value lists, such as
# quota, expire and acl plugins. The dictionary can be used either directly or
# though a dictionary server. The following dict block maps dictionary names to
# URIs when the server is used. These can then be referenced using URIs in
# format "proxy::<name>".
dict {
quotadict = mysql:/etc/dovecot/alternc-dict-quota.conf
#expire = db:/var/lib/dovecot/expire.db
}
service auth-worker {
user = vmail
}
service dict {
unix_listener dict {
mode = 0660
user = vmail
group = vmail
}
}

File diff suppressed because it is too large Load Diff

View File

@ -113,5 +113,7 @@ mailman unix - n n - - pipe
#dovecot LDA, as explained here: http://wiki.dovecot.org/LDA/Postfix #dovecot LDA, as explained here: http://wiki.dovecot.org/LDA/Postfix
dovecot unix - n n - 0 pipe dovecot unix - n n - 0 pipe
flags=DRhu user=vmail:vmail argv=/usr/bin/sudo /usr/lib/dovecot/deliver -f ${sender} -a ${recipient} -d ${user}@${nexthop} flags=DRhu user=vmail:vmail argv=/usr/bin/sudo /usr/lib/dovecot/deliver -f ${sender} -a ${recipient} -d ${user}@${nexthop}
#smtp inet n - n - 1 postscreen
#smtpd pass - - n - - smtpd
#dnsblog unix - - n - 0 dnsblog
#tlsproxy unix - - n - 0 tlsproxy

View File

@ -22,6 +22,8 @@
# Purpose of file: Main install script, launch it anytime ;) # Purpose of file: Main install script, launch it anytime ;)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
set -e
# Somes check before start operations # Somes check before start operations
if [ `id -u` -ne 0 ]; then if [ `id -u` -ne 0 ]; then
echo "must be launched as root" echo "must be launched as root"
@ -79,7 +81,7 @@ if [ -e /etc/default/saslauthd ]; then
fi fi
if [ -e /etc/dovecot/dovecot.conf ]; then if [ -e /etc/dovecot/dovecot.conf ]; then
CONFIG_FILES="$CONFIG_FILES etc/dovecot/dovecot.conf etc/dovecot/dovecot-sql.conf etc/dovecot/dovecot-dict-quota.conf" CONFIG_FILES="$CONFIG_FILES etc/dovecot/alternc-sql.conf etc/dovecot/alternc-dict-quota.conf etc/dovecot/conf.d/95_alternc.conf"
fi fi
INSTALLED_CONFIG_TAR="/var/lib/alternc/backups/etc-installed.tar.gz" INSTALLED_CONFIG_TAR="/var/lib/alternc/backups/etc-installed.tar.gz"
@ -315,7 +317,7 @@ if [ -x /usr/sbin/apache2 ]; then
fi fi
# We enable dovecot SSL certificate instructions: (on wheezy we should use a new file in /etc/dovecot/conf.d/ ) # We enable dovecot SSL certificate instructions: (on wheezy we should use a new file in /etc/dovecot/conf.d/ )
sed -i -e 's#^ssl_cert_file.*$#ssl_cert_file = /etc/ssl/certs/ssl-cert-snakeoil.pem#' -e 's#^ssl_key_file.*$#ssl_key_file = /etc/ssl/private/ssl-cert-snakeoil.key#' /etc/dovecot/dovecot.conf ( echo "ssl_cert = </etc/alternc/apache.pem" ; echo "ssl_key = </etc/alternc/apache.pem" ) >/etc/dovecot/conf.d/96_ssl.conf
else else
# We disable proftpd tls module # We disable proftpd tls module
@ -324,7 +326,7 @@ if [ -x /usr/sbin/apache2 ]; then
cp /etc/proftpd/modules.conf /etc/alternc/templates/proftpd/ cp /etc/proftpd/modules.conf /etc/alternc/templates/proftpd/
# We disable dovecot SSL certificate instructions: (on wheezy we should remove a file in /etc/dovecot/conf.d/ ) # We disable dovecot SSL certificate instructions: (on wheezy we should remove a file in /etc/dovecot/conf.d/ )
sed -i -e 's#^ssl_cert_file.*$#ssl_cert_file = /etc/ssl/certs/ssl-cert-snakeoil.pem#' -e 's#^ssl_key_file.*$#ssl_key_file = /etc/ssl/private/ssl-cert-snakeoil.key#' /etc/dovecot/dovecot.conf ( echo "ssl_cert = </etc/ssl/certs/ssl-cert-snakeoil.pem" ; echo "ssl_key = </etc/ssl/private/ssl-cert-snakeoil.key" ) >/etc/dovecot/conf.d/96_ssl.conf
echo "SSL not configured" echo "SSL not configured"
echo "create a certificate in /etc/alternc/apache.pem and rerun alternc.install" echo "create a certificate in /etc/alternc/apache.pem and rerun alternc.install"
@ -531,7 +533,7 @@ tar -zcf "$INSTALLED_CONFIG_TAR" -C / $CONFIG_FILES
# Last touches # Last touches
# #
find $ALTERNC_HTML -maxdepth 1 -type d -exec setfacl -b -k -m d:g:alterncpanel:rw- -m d:u:alterncpanel:rw- -m u:alterncpanel:rw- -m g:alterncpanel:rw- {} \; find $ALTERNC_HTML -maxdepth 1 -type d -exec setfacl -b -k -m d:g:alterncpanel:rwx -m d:u:alterncpanel:rwx -m u:alterncpanel:rwx -m g:alterncpanel:rwx {} \;
#creating log file #creating log file
if [ ! -e "/var/log/alternc/bureau.log" ]; then if [ ! -e "/var/log/alternc/bureau.log" ]; then
@ -572,9 +574,11 @@ if [ "$HAS_ROOT" != "1" ]; then
fi fi
fi fi
#giving vmail user read access on dovecot sql file # giving vmail user read access on dovecot sql file
chgrp vmail /etc/dovecot/dovecot.conf chgrp vmail /etc/dovecot/alternc-sql.conf
chmod g+r /etc/dovecot/dovecot.conf chmod g+r /etc/dovecot/alternc-sql.conf
# Override some dovecot 2.0 configuration that may have happened during dovecot postinst:
sed -i -e 's/^ *!include/#!include/' /etc/dovecot/conf.d/10-auth.conf
# Changing owner of web panel's files # Changing owner of web panel's files
chown -R alterncpanel:alterncpanel "/usr/share/alternc/panel/" chown -R alterncpanel:alterncpanel "/usr/share/alternc/panel/"

View File

@ -115,7 +115,7 @@ CREATE TABLE IF NOT EXISTS domaines (
noerase tinyint(4) NOT NULL default '0', noerase tinyint(4) NOT NULL default '0',
dns_action enum ('OK','UPDATE','DELETE') NOT NULL default 'UPDATE', dns_action enum ('OK','UPDATE','DELETE') NOT NULL default 'UPDATE',
dns_result varchar(255) not null default '', dns_result varchar(255) not null default '',
zonettl int(10) unsigned NOT NULL default '86400', zonettl int(10) unsigned NOT NULL default '3600',
PRIMARY KEY (id), PRIMARY KEY (id),
UNIQUE KEY (domaine) UNIQUE KEY (domaine)
) ENGINE=MyISAM; ) ENGINE=MyISAM;
@ -745,5 +745,3 @@ CREATE TABLE IF NOT EXISTS `alternc_status` (
) ENGINE=MyISAM DEFAULT CHARSET=latin1; ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO alternc_status SET name='alternc_version',value='3.4.1.sh'; INSERT INTO alternc_status SET name='alternc_version',value='3.4.1.sh';

View File

@ -0,0 +1,3 @@
ALTER TABLE `actions` CHANGE `type` `type` ENUM('CREATE_FILE','FIX_USER','CREATE_DIR','DELETE','MOVE','FIX_DIR','FIX_FILE','CHMOD') DEFAULT NULL ;
-- lower default TTL
ALTER TABLE `domaines` CHANGE `zonettl` `zonettl` int(10) unsigned NOT NULL default '3600';

View File

@ -0,0 +1,22 @@
<?php
/**
* Console aware class, encapsulates the Console CommandLine class
*/
class Alternc_Diagnostic_Console extends Console_CommandLine{
const DESCRIPTION = "Handles diagnostics of an alternc server.";
const VERSION = "0.1";
function __construct(array $params = array()) {
$params = array(
'description' => self::DESCRIPTION,
'version' => self::VERSION
);
parent::__construct($params);
}
}

View File

@ -0,0 +1,157 @@
<?php
/**
* Uniform data component containing other components or real data
*/
class Alternc_Diagnostic_Data {
public $index = array();
public $data = array();
public $type = "";
public $metadata = null;
const TYPE_ROOT = "root";
const TYPE_DOMAIN = "service";
const TYPE_SECTION = "section";
public function __construct( $type, $sectionData = null) {
$this->type = $type;
if( $sectionData){
$this->data = $sectionData;
}
}
// recursive rebuild
function buildFromArray( $content ){
if( ! $this->isValidArrayData( $content ) ) {
return $content;
}
$type = $content["type"];
$newInstance = new Alternc_Diagnostic_Data( $type );
$newInstance->index = $content["index"];
$newInstance->metadata = $content["metadata"];
$data = $content["data"];
// The content is raw
if( $type === self::TYPE_SECTION){
$newInstance->data = $data;
}
// The content is made of services or sections
else foreach( $content["data"] as $section_name => $sectionData ){
$sectionContent = $this->buildFromArray( $sectionData );
$newInstance->addData( $section_name, $sectionContent );
}
return $newInstance;
}
// Make sure we have a valid format result
function isValidArrayData( $content ){
if(
!is_array($content)
|| !array_key_exists( "type", $content )
|| !array_key_exists("metadata",$content)
|| !array_key_exists("index",$content)
|| !array_key_exists("data",$content)
|| ! in_array( $content["type"], array(self::TYPE_ROOT,self::TYPE_DOMAIN,self::TYPE_SECTION) ) ){
return false;
}
return true;
}
/**
* Sets
*
* @param string $sectionname
* @param Alternc_Diagnostic_Data $data
* @return boolean
*/
function addData( $sectionname, Alternc_Diagnostic_Data $data){
$this->index[] = $sectionname;
$this->data[$sectionname] = $data;
return true;
}
/**
* @param array index
*/
public function setIndex($index) {
$this->index = $index;
return $this;
}
/**
* @return array
*/
public function getIndex() {
return $this->index;
}
/**
* @param array data
*/
public function setData($data) {
$this->data = $data;
return $this;
}
/**
* @return array
*/
public function getData() {
return $this->data;
}
/**
* @param string type
*/
public function setType($type) {
$this->type = $type;
return $this;
}
/**
* @return string
*/
public function getType() {
return $this->type;
}
/**
* @param array metadata
*/
public function setMetadata($metadata) {
$this->metadata = $metadata;
return $this;
}
/**
* @return array
*/
public function getMetadata() {
return $this->metadata;
}
/**
* Retrieves a given section of the data
*
*
* @param string $section_name
* @return boolean
*/
public function getSection( $section_name ){
if( !in_array($section_name, $this->index)){
return FALSE;
}
return $this->data[$section_name];
}
}

View File

@ -0,0 +1,83 @@
<?php
error_reporting( E_ERROR );
class Alternc_Diagnostic_Diff{
/**
*
*/
function compare(Alternc_Diagnostic_Data $source, Alternc_Diagnostic_Data $target ){
$sourceIndex = $source->getIndex();
$targetIndex = $target->getIndex();
// Check diagnostics are same level
$source_type = $source->getType();
$target_type = $target->getType();
if( $source_type != $target_type){
throw new \Exception("Invalid type comparison requested: $source_type vs $target_type");
}
$diffInstance = new Alternc_Diagnostic_Data( $source_type );
#echo "type $source_type\n";
// Compare general data
if( $source->getMetadata() != $target->getMetadata() ){
$diffInstance->setMetadata( array_diff( $source->getMetadata(), $target->getMetadata() ) );
}
if( $source->getIndex() != $target->getIndex() ){
$diffInstance->setIndex( array_diff( $source->getIndex(), $target->getIndex() ) );
}
// If section content ie. no subsections
if( $source_type == Alternc_Diagnostic_Data::TYPE_SECTION ){
#echo "Real section\n";
if( is_array( $source->getData() ) && is_array( $target->getData() ) ){
$diff = array_diff( $source->getData(), $target->getData() ) ;
if( $diff ){
$diffInstance->setData( array_diff( $source->getData(), $target->getData()) );
}
}else{
if( $source->getData() != $target->getData() ){
$diffInstance->setData( array("source" => $source->getData(),"target" => $target->getData() ) );
}
}
}else{
$sourceData = $source->getData();
$targetData = $target->getData();
$seenSections = array();
foreach( $sourceData as $section_name => $sectionData ){
#echo "section_name $section_name\n";
$section_data_type = $sectionData->getType();
if( ! isset( $targetData[$section_name] ) ) {
#echo "section_name not in target\n";
$tempDataInstance = new Alternc_Diagnostic_Data($section_data_type);
$tempDataInstance->setMetadata( array("Not in target") );
}else{
#echo "section_name for diff\n";
$tempDataInstance = $this->compare($sectionData, $targetData[$section_name] );
}
if( ! is_null( $tempDataInstance ) ){
$diffInstance->addData( $section_name, $tempDataInstance);
}
}
}
if( count( $diffInstance->getData() )
|| count( $diffInstance->getIndex() )
|| count( $diffInstance->getMetadata() )
){
return $diffInstance;
}
return null;
}
}

View File

@ -0,0 +1,89 @@
<?php
class Alternc_Diagnostic_Directory {
/**
* Location of diagnostic files
*
* @var string
*/
protected $file_path;
public function __construct( $file_path) {
if( null == $file_path){
throw new \Exception("Empty file_path in Diagnostic Format handler");
}
if( !file_exists($file_path)){
if( !mkdir($file_path, 0774, true)){
throw new \Exception("Could not access path $file_path in Diagnostic Format handler");
}
}
$this->file_path = $file_path;
}
function getList( $max = null){
$dir = new DirectoryIterator($this->file_path);
$fileList = array();
while($dir->valid()) {
if( $dir->isDot() ){
$dir->next();
continue;
}
$file_name = $dir->getFilename();
$fileList[] = $file_name;
$dir->next();
}
return $fileList;
}
/**
* @param string file_path
*/
public function setFile_path($file_path) {
$this->file_path = $file_path;
return $this;
}
// @todo Confirm usefulness
public function getFileContent( $id ) {
$fileList = $this->getList();
if( array_key_exists( $id, $fileList ) ){
return file_get_contents( $this->file_path."/".$fileList[$id]);
}
if( in_array($id, $fileList)){
$key = array_search( $id, $fileList );
return file_get_contents( $this->file_path."/".$fileList[$key]);
}
throw new \Exception("Could not find diagnostic for id : $id");
}
function getFileInfo($id){
$fileList = $this->getList();
if( array_key_exists( $id, $fileList ) ){
$file_path = $this->file_path."/".$fileList[$id];
}
if( in_array($id, $fileList)){
$key = array_search( $id, $fileList );
$file_path = $this->file_path."/".$fileList[$key];
}
$fileInfos = pathinfo( $file_path );
return ($fileInfos);
}
/**
* @return string
*/
public function getFile_path() {
if( null == $this->file_path){
throw new \Exception("Missing property 'file_path' in format instance");
}
return $this->file_path;
}
}

View File

@ -0,0 +1,122 @@
<?php
class Alternc_Diagnostic_Format_Abstract {
/**
*
* @var Alternc_Diagnostic_Data
*/
public $data;
/**
*
* @var Alternc_Diagnostic_Directory
*/
public $directory;
/**
* Files extension for the format
*
* @var string
*/
protected $extension;
/**
* @param string extension
*/
public function setExtension($extension) {
$this->extension = $extension;
return $this;
}
/**
* @return string
*/
public function getExtension() {
return $this->extension;
}
public function __construct(Alternc_Diagnostic_Directory $directory) {
$this->directory = $directory;
}
/**
* @param Alternc_Diagnostic_Data data
*/
public function setData(Alternc_Diagnostic_Data $data) {
$this->data = $data;
return $this;
}
/**
* @return Alternc_Diagnostic_Data
*/
public function getData() {
if(is_null($this->data)){
throw new \Exception("Missing property 'data' in format instance");
}
return $this->data;
}
public function getFilename(){
return $this->getDirectory()->getFile_path()."/".time().".".$this->getExtension();
}
/**
* @param Alternc_Diagnostic_Directory directory
*/
public function setDirectory($directory) {
$this->directory = $directory;
return $this;
}
/**
* @return Alternc_Diagnostic_Directory
*/
public function getDirectory() {
if( null == $this->directory){
throw new \Exception("Missing property 'directory' in format instance");
}
return $this->directory;
}
/**
* Writes a Data object to file
*
* @return boolean
*/
public function write( Alternc_Diagnostic_Data $data = null ){
if( null == $data ){
if( ! $this->data ){
throw new \Exception( "A format cannot be written without a Data");
}
$data = $this->data;
}
$content = $this->dataToContent( $data );
$filename = $this->getFilename();
if( ! file_put_contents($filename, $content) ){
throw new \Exception("Failed to write in json format to file $filename" );
}
return true;
}
/**
*
* @param string file_name
* @return Alternc_Diagnostic_Data A diagnostic structure
*/
function read( $file_name ){
$content = $this->directory->getFileContent( $file_name );
return $this->contentToData( $content );
}
}

View File

@ -0,0 +1,10 @@
<?php
interface Alternc_Diagnostic_Format_Interface{
function contentToData( $content );
function dataToContent();
}

View File

@ -0,0 +1,49 @@
<?php
/**
* JSON implementation of the format interface : writes, reads, compares
*/
class Alternc_Diagnostic_Format_Json
extends Alternc_Diagnostic_Format_Abstract
implements Alternc_Diagnostic_Format_Interface
{
/**
* @inherit
*/
public function __construct(Alternc_Diagnostic_Directory $directory) {
parent::__construct($directory);
$this->setExtension("json");
}
/**
* @inherit
*/
function contentToData( $content ){
$arrayData = json_decode( $content , true);
$dataInstance = new Alternc_Diagnostic_Data(Alternc_Diagnostic_Data::TYPE_ROOT);
$this->data = $dataInstance->buildFromArray( $arrayData );
return $this->data;
}
/**
* @inherit
*/
function dataToContent(Alternc_Diagnostic_Data $data = null ){
if( $data ){
$this->setData($data);
}
$content = json_encode($this->getData());
$filename = $this->getFilename();
if(json_last_error()){
throw new \Exception("Json conversion failed with error #".json_last_error()."for data".serialize($this->getData()));
}
return $content;
}
}

View File

@ -0,0 +1,61 @@
<?php
/**
* JSON implementation of the format interface : writes, reads, compares
*/
class Alternc_Diagnostic_Format_Txt
extends Alternc_Diagnostic_Format_Abstract
implements Alternc_Diagnostic_Format_Interface
{
/**
* @inherit
*/
public function __construct(Alternc_Diagnostic_Directory $directory) {
parent::__construct($directory);
$this->setExtension("txt");
}
/**
* @inherit
*/
function contentToData( $content ){
// @todo or skip ? Quite a fragile storage
}
/**
* @inherit
*/
function dataToContent(Alternc_Diagnostic_Data $data = null, $depth = 0 ){
$d = $this->space_depth($depth);
echo $d."Type: ".$data->type."\n";
$d .= " ";
if( $data->type == Alternc_Diagnostic_Data::TYPE_SECTION ){
foreach( $data->data as $key => $value ){
if( is_int( $key) ){
echo $d.json_encode( $value, true )."\n";
}else{
echo $d.$key." => ".json_encode( $value, true )."\n";
}
}
return;
}
foreach( $data->data as $section_name => $sectionData ){
echo $d."Section: $section_name\n";
$this->dataToContent( $sectionData, $depth+1);
}
}
function space_depth( $depth){
$buf = "";
for( $i=0; $i < $depth; $i++){
$buf .= " ";
}
return $buf;
}
}

View File

@ -0,0 +1,155 @@
<?php
/**
* Central service which provides the glue and intelligence for all parts
*/
class Alternc_Diagnostic_Manager{
/**
* @var Alternc_Diagnost_Format_Abstract
*/
public $formatInstance;
/**
* @var Alternc_Diagnost_Directory
*/
public $directoryInstance;
/** @var string the Alternc version */
public $version;
/**
* Constructor with dependancy injection
*
* @param array $options
* @throws \Exception
*/
public function __construct($options) {
// Attempts to retrieve formatInstance
if (isset($options["formatInstance"]) && ! is_null($options["formatInstance"])) {
$this->formatInstance = $options["formatInstance"];
} else {
throw new \Exception("Missing parameter formatInstance");
}
// Attempts to retrieve directoryInstance
if (isset($options["directoryInstance"]) && ! is_null($options["directoryInstance"])) {
$this->directoryInstance = $options["directoryInstance"];
} else {
throw new \Exception("Missing parameter directoryInstance");
}
// Attempts to retrieve version
if (isset($options["version"]) && ! is_null($options["version"])) {
$this->version = $options["version"];
} else {
throw new \Exception("Missing parameter version");
}
}
/**
* Controls the diagnostics creation
*
* @param Console_CommandLine_Result $options
* @throws \Exception
*/
function c_create(Console_CommandLine_Result $options){
$args = $options->args;
$options = $options->options;
$diagnosticdata = new Alternc_Diagnostic_Data(Alternc_Diagnostic_Data::TYPE_ROOT);
$servicelist = explode(',',$options["services"]);
foreach ($servicelist as $service) {
$class_name = "Alternc_Diagnostic_Service_".trim(ucfirst($service));
if(!class_exists($class_name)){
throw new \exception("invalid service $service");
}
/** @var alternc_diagnostic_service_interface */
$serviceagent = new $class_name( array("service" => $this) );
// runs the service agent and store the results
$diagnosticdata->addData($serviceagent->name, $serviceagent->run());
}
$this->formatInstance->setData($diagnosticdata)->write();
}
function c_diff( $options ){
$args = $options->args;
$options = $options->options;
$source = $options["source"];
$target = $options["target"];
$format = $options['format'];
$sourceDiagnostic = $this->getDiagnosticFromId($source);
$targetDiagnostic = $this->getDiagnosticFromId($target);
$diff = new Alternc_Diagnostic_Diff();
$diffData = $diff->compare($sourceDiagnostic,$targetDiagnostic);
$formatInstance = $this->getFormatInstance( $format );
echo $formatInstance->dataToContent( $diffData);
}
function c_list( $options ){
$args = $options->args;
$options = $options->options;
$fileList = $this->directoryInstance->getList();
foreach( $fileList as $number => $file ){
echo "$number\t$file\n";
}
}
function c_show( $options ){
$args = $options->args;
$options = $options->options;
$id = $options['id'];
$format = $options['format'];
$data = $this->getDiagnosticFromId( $id);
$formatInstance = $this->getFormatInstance( $format );
echo $formatInstance->dataToContent( $data );
}
function c_delete( $options ){}
/**
* Finds a file by reference or name
*
* @param string $file_reference
* @return Alternc_Diagnostic_Data Resulting data
* @todo add the ability to resolve by filename
*/
protected function getDiagnosticFromId ( $id ) {
$fileInfo = $this->directoryInstance->getFileInfo( $id ) ;
$extension = $fileInfo["extension"];
$formatInstance = $this->getFormatInstance( $extension);
$formatInstance->read( $fileInfo["basename"] );
$data = $formatInstance->getData();
return $data;
}
protected function getFormatInstance ( $format ){
switch( $format ){
case "json":
$instance = new Alternc_Diagnostic_Format_Json( $this->directoryInstance );
break;
case "txt":
$instance = new Alternc_Diagnostic_Format_Txt( $this->directoryInstance );
break;
default:
throw new \Exception("Invalid format : $format");
break;
}
return $instance;
}
}

View File

@ -0,0 +1,220 @@
<?php
/**
* This abstract defines properties and provides helpers to service classes
*
*/
abstract class Alternc_Diagnostic_Service_Abstract{
/** @var Alternc_Diagnostic_Data*/
protected $data;
/** @var DB_Sql*/
public $db;
/** @var m_mysql */
protected $mysql;
/** @var m_mem */
protected $mem;
/** @var m_admin */
protected $admin;
/** @var m_authip */
protected $authip;
/** @var m_cron */
protected $cron;
/** @var m_dom */
protected $dom;
/** @var m_ftp */
protected $ftp;
/** @var m_hta */
protected $hta;
/** @var m_mail */
protected $mail;
/** @var m_quota */
protected $quota;
/** @var Alternc_Diagnostic_Service */
protected $service;
public function __construct( $options ) {
$this->data = new Alternc_Diagnostic_Data(Alternc_Diagnostic_Data::TYPE_DOMAIN);
global $db;
$this->db = $db;
global $mem;
$this->mem = $mem;
global $mysql;
$this->mysql = $mysql;
global $quota;
$this->quota= $quota;
global $mail;
$this->mail= $mail;
global $hta;
$this->hta= $hta;
global $ftp;
$this->ftp= $ftp;
global $dom;
$this->dom= $dom;
global $cron;
$this->cron= $cron;
global $authip;
$this->authip= $authip;
global $admin;
$this->admin= $admin;
if( array_key_exists("service",$options) && is_object($options["service"] ) ){
$this->service = $options["service"];
}
}
/**
*
* @param string $cmd
* @return array
* @throws \Exception
*/
protected function execCmd( $cmd ){
exec(escapeshellcmd("$cmd")." 2>&1", $output, $return_var);
if( 0 != $return_var ){
throw new \Exception("Invalid return for command $cmd returned error code #$return_var with output :". json_encode($output));
}
return $output;
}
/**
* Filters lines of a result to only include the matching lines
*
* @param string $pattern
* @param array $result
* @return type
*/
protected function filterRegexp($result,$pattern){
$returnArray = array();
foreach ($result as $line) {
$captures_count = preg_match($pattern, $line, $matches);
if($captures_count){
array_shift($matches);
$returnArray[] = implode(" ", $matches);
}
}
return $returnArray;
}
/**
* @param Alternc_Diagnostic_Data data
*/
public function setData($data) {
$this->data = $data;
return $this;
}
/**
* @return Alternc_Diagnostic_Data
*/
public function getData() {
return $this->data;
}
/**
* Utility for filling the service agent data holder
*
* @param string $name
* @param mixed $content
* @return boolean
*/
function writeSectionData( $name, $content){
$section = new Alternc_Diagnostic_Data(Alternc_Diagnostic_Data::TYPE_SECTION,$content);
$this->data->addData($name, $section);
return true;
}
/**
* Reads an array of URL and returns the CURL results
*
* @param array $urlList
* @param array $fieldsList curlInfo array keys
* @param int $sockets_max
* @return array
*/
function curlRequest($urlList,$fieldsList = array("http_code","url"),$sockets_max = 8){
$returnArray = array();
// Attempts to retrive a multi connection curl handle
$multiCurlHandle = curl_multi_init();
for ($index = 0; $index < $sockets_max; $index++) {
$ch = "ch".$index;
$$ch = curl_init();
curl_setopt($$ch, CURLOPT_HEADER, 1);
curl_setopt($$ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($$ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($$ch, CURLOPT_TIMEOUT, 3);
curl_setopt($$ch, CURLOPT_NOBODY, 1);
curl_multi_add_handle($multiCurlHandle,$$ch);
}
$url_count = count($urlList);
$url_pointer = 0;
while( $url_pointer < $url_count){
$sockets = $url_count - $url_pointer > $sockets_max ? $sockets_max : $url_count - $url_pointer ;
$loopUrlList = array();
for ($index2 = 0; $index2 < $sockets; $index2++) {
$ch = "ch".$index2;
$url = $urlList[$url_pointer];
$loopUrlList[$index2] = $url;
curl_setopt($$ch, CURLOPT_URL, $url);
$url_pointer++;
}
do {
curl_multi_exec($multiCurlHandle, $running);
curl_multi_select($multiCurlHandle);
} while ($running > 0);
for ($index3 = 0; $index3 < $sockets; $index3++) {
$ch = "ch".$index3;
$url = $loopUrlList[$index3];
$curlInfo = curl_getinfo($$ch);
$urlInfo = array();
foreach ($fieldsList as $field) {
$urlInfo[$field] = $curlInfo[$field];
}
$returnArray[] = $urlInfo;
}
}
//close the handles
curl_multi_close($multiCurlHandle);
for ($index = 0; $index < $sockets_max; $index++) {
$ch = "ch".$index;
curl_close($$ch);
}
return $returnArray;
}
}

View File

@ -0,0 +1,77 @@
<?php
/**
* Lists vhosts
* Lists redirections
* Checks vhosts
* Checks redirections
*/
class Alternc_Diagnostic_Service_Apache2
extends Alternc_Diagnostic_Service_Abstract
implements Alternc_Diagnostic_Service_Interface
{
public $name = "apache2";
const SECTION_VHOSTS = "vhosts";
const SECTION_MODULES = "modules";
const SECTION_REDIRECTIONS = "redirections";
const SECTION_RESPONSES = "responses";
function run(){
// Writes the modules
$this->writeSectionData (self::SECTION_MODULES,$this->filterRegexp ($this->execCmd("apache2ctl -M"), "/^[\W]*(\w+).*\(.*$/u" ));
// Writes the vhosts in the form "port servername"
$this->writeSectionData (self::SECTION_VHOSTS,$this->getVhosts());
// Writes the redirects
$this->writeSectionData (self::SECTION_REDIRECTIONS, $this->getRedirects());
// Writes the tests
$this->writeSectionData (self::SECTION_RESPONSES,$this->testServers());
return $this->data;
}
function getVhosts(){
$list = $this->filterRegexp( $this->execCmd("apache2ctl -S"), "/^[\D]*(\d{2,4}).* (.*) \(\/.*$/u");
$returnArray = array();
foreach( $list as $vhost){
$returnArray[] = explode(" ",$vhost);
}
return $returnArray;
}
function getRedirects(){
$mysqlResource = $this->db->query("SELECT domaine as domain, valeur as url from sub_domaines where type='url';");
$resultArray = array();
if ($this->db->num_rows()) {
while(($resultArray[] = mysql_fetch_assoc($mysqlResource)) || array_pop($resultArray));
}
return $resultArray;
}
function testServers(){
$sockets_max = 8;
$fieldsList = array("http_code","url");
$vhostUrlList = array();
// Retrieves and tests local vhosts
$vhostList = $this->data->getSection(self::SECTION_VHOSTS)->getData();
foreach( $vhostList as $vhostInfo){
$protocol = $vhostInfo[0] == 443 ? "https://":"http://";
$vhostUrlList[] = "{$protocol}{$vhostInfo[1]}";
}
$vhostResult = $this->curlRequest($vhostUrlList,$fieldsList,$sockets_max);
// Retrieves and tests local redirs
$redirList = $this->data->getSection(self::SECTION_REDIRECTIONS)->getData();
foreach( $redirList as $redirInfo){
$redirUrlList[] = $redirInfo["url"];
}
$redirResult = $this->curlRequest($redirUrlList,$fieldsList,$sockets_max);
return array_merge($vhostResult,$redirResult);
}
}

View File

@ -0,0 +1,189 @@
<?php
/**
* List domains
* Check domains
* domains response
* zones locked
* slaves
*/
class Alternc_Diagnostic_Service_Dns
extends Alternc_Diagnostic_Service_Abstract
implements Alternc_Diagnostic_Service_Interface
{
public $name = "dns";
/** @var array */
protected $domainList;
/** @var array */
protected $zonesList;
/** var system_bind */
protected $bind;
const SECTION_LIST = "list";
const SECTION_HOST = "host";
const SECTION_NAMESERVERS = "nameservers";
const SECTION_ZONES = "zones";
const SECTION_ZONES_LOCKED = "zones_locked";
const SECTION_SLAVES = "slaves";
function run(){
/** @var m_dom */
global $dom;
$version = $this->service->version;
if( $version < 3.2 ) {
$this->bind = new system_bind(array(
"zone_file_directory" => "/var/alternc/bind/zones/"));
$this->domainList = $this->get_domain_all_summary();
}else{
$this->bind = new system_bind();
$this->domainList = $dom->get_domain_all_summary();
}
// Attempts to retrieve zone list
$this->zonesList = $this->getZonesList();
// Writes the dns slaves
$this->writeSectionData (self::SECTION_SLAVES,$this->getSlaves());
// Writes the domains list
$this->writeSectionData (self::SECTION_LIST,$this->domainList);
// Writes the domains hosts
$this->writeSectionData (self::SECTION_HOST, $this->getHosts());
// Writes the domains nameservers
$this->writeSectionData (self::SECTION_NAMESERVERS,$this->getNameservers());
// Writes the domains zones
$this->writeSectionData (self::SECTION_ZONES,$this->zonesList);
// Writes the domains zones locked
$this->writeSectionData (self::SECTION_ZONES_LOCKED,$this->getZonesLocked());
// Writes the domains zones with custom records
$this->writeSectionData (self::SECTION_ZONES_LOCKED,$this->getZonesCustomRecords());
return $this->data;
}
/**
* Local override if not available (1.0)
* @return array
*/
function get_domain_all_summary() {
global $db, $err;
$res = array();
$db->query("SELECT domaine, gesdns, gesmx, dns_action FROM domaines ORDER BY domaine");
while ($db->next_record()) {
$res[$db->f("domaine")] = array(
"gesdns" => $db->f("gesdns"),
"gesmx" => $db->f("gesmx"),
"dns_action" => $db->f("dns_action"),
);
}
return $res;
}
/**
* Lists domains `host $DOMAIN` data
* @return array
*/
function getHosts(){
$resultArray = array();
foreach ($this->domainList as $domain => $domainInfo) {
try{
$resultArray[$domain] = $this->execCmd("host {$domain}");
}catch( \Exception $e){
echo $e->getMessage()."\n";
}
}
return $resultArray;
}
/**
* Lists domains NS
*
* @return array
*/
function getNameservers(){
$resultArray = array();
foreach ($this->domainList as $domain => $domainInfo) {
try{
$resultArray[$domain] = $this->execCmd("dig NS {$domain} +short");
}catch( \Exception $e){
echo $e->getMessage()."\n";
}
}
return $resultArray;
}
/**
* Lists zones content
*
* @return array
*/
function getZonesList(){
$resultArray = array();
foreach ($this->domainList as $domain => $domainInfo) {
try{
$resultArray[$domain] = $this->bind->get_zone_file($domain);
}catch( \Exception $e){
echo $e->getMessage()."\n";
}
}
return $resultArray;
}
/**
* Lists which domains zones are locked
*
* @return array
*/
function getZonesLocked(){
$resultArray = array();
foreach ($this->domainList as $domain => $domainInfo) {
try{
$resultArray[$domain] = $this->bind->is_locked($domain);
}catch( \Exception $e){
echo $e->getMessage()."\n";
}
}
return $resultArray;
}
/**
* Lists which domains zones have custom records
*
* @return array
*/
function getZonesCustomRecords(){
$resultArray = array();
$regexp = ";;; END ALTERNC AUTOGENERATE CONFIGURATION\n(.+\w+.+)";
foreach ($this->zonesList as $domain => $zone) {
$is_custom = false;
try{
if(preg_match("/$regexp/ms", $zone, $matches)){
$is_custom = $matches[1];
}
}catch( \Exception $e){
echo $e->getMessage()."\n";
}
$resultArray[$domain] = $is_custom;
}
return $resultArray;
}
/**
* Lists servers DNS slaves accounts
*
* @return array
*/
function getSlaves(){
return $this->dom->enum_slave_account();
}
}

View File

@ -0,0 +1,69 @@
<?php
/**
* Lists accounts
* Checks root
*/
class Alternc_Diagnostic_Service_Ftp
extends Alternc_Diagnostic_Service_Abstract
implements Alternc_Diagnostic_Service_Interface
{
public $name = "ftp";
// /** @var m_ftp */
// protected $ftp;
/** @var array */
protected $ftpList;
const SECTION_LIST = "list";
const SECTION_CHECK_HOMEDIR = "check_homedir";
function run(){
$this->ftpList = $this->get_list();
// Writes the domains list
$this->writeSectionData (self::SECTION_LIST,$this->ftpList);
// Checks the homedir existence
$this->writeSectionData (self::SECTION_CHECK_HOMEDIR, $this->checkHomeDir());
return $this->data;
}
function checkHomeDir() {
$returnArray = array();
foreach( $this->ftpList as $login => $ftpData){
$exists = false;
$homedir = $ftpData["dir"];
if(is_dir($homedir) ){
$exists = true;
}
$returnArray[$login] = $exists;
}
return $returnArray;
}
function get_list() {
$returnArray = array();
$this->db->query("SELECT id, name, homedir, enabled FROM ftpusers ORDER BY name;");
if ($this->db->num_rows()) {
while ($this->db->next_record()) {
$returnArray[$this->db->f("name")]=array(
"enabled" => $this->db->f("enabled"),
"dir" => $this->db->f("homedir")
);
}
}
return $returnArray;
}
}

View File

@ -0,0 +1,11 @@
<?php
/**
*
*/
interface Alternc_Diagnostic_Service_Interface{
function run();
}

View File

@ -0,0 +1,119 @@
<?php
/**
* Lists emails
* Stats pop / alias
* Checks SMTP / SIEVE
*/
class Alternc_Diagnostic_Service_Mail
extends Alternc_Diagnostic_Service_Abstract
implements Alternc_Diagnostic_Service_Interface
{
public $name = "email";
protected $mailList = array();
const SECTION_LIST = "list";
const SECTION_STAT_ALIAS = "stat_alias";
const SECTION_CHECK_STORAGE = "check_storage";
function run(){
// Attempts to retrieve all email addresses
$this->mailList = $this->getList();
// Writes the domains list
$this->writeSectionData (self::SECTION_LIST,$this->getList());
// Writes the alias stats
$this->writeSectionData (self::SECTION_STAT_ALIAS,$this->getStatAlias());
// Writes the quota stats
$this->writeSectionData (self::SECTION_CHECK_STORAGE,$this->getCheckStorage());
return $this->data;
}
/**
* Gets list from db
*
* @return array
*/
function getList(){
$returnArray = array();
// Check the availability
$this->db->query('
SELECT CONCAT(a.address,"@",d.domaine) as email, a.type, a.enabled, r.recipients, m.path,m.quota,m.bytes/(1024*1024) as size_mo,m.messages
FROM address a
LEFT JOIN recipient r ON r.address_id = a.id
LEFT JOIN mailbox m ON m.address_id = a.id
JOIN domaines d ON a.domain_id = d.id;');
if ($this->db->num_rows()) {
while ($this->db->next_record()) {
$email = $this->db->f("email");
$returnArray[$email] = array(
"enabled" => $this->db->f("enabled"),
"type" => $this->db->f("type"),
"recipients" => $this->db->f("recipients"),
"path" => $this->db->f("path"),
"quota" => $this->db->f("quota"),
"size_mo" => $this->db->f("size_mo"),
"messages" => $this->db->f("messages"),
);
}
}
return $returnArray;
}
/**
* Searches mails with alias
*
* @return array
*/
function getStatAlias() {
$returnArray = array();
foreach ($this->mailList as $email => $emailInfo) {
$is_alias = false;
if( !is_null($emailInfo["recipients"])){
$is_alias = true;
}
$returnArray[$email] = $is_alias;
}
return $returnArray;
}
/**
* Checks the box oversize and effective existence
*
* @return array
*/
function getCheckStorage() {
$returnArray = array();
foreach ($this->mailList as $email => $emailInfo) {
// Only account real boxes
if( ! $emailInfo["path"]){
continue;
}
$quota_pct = "0";
$box_exists = true;
$quota = $emailInfo["quota"];
$size_mo = $emailInfo["size_mo"] ;
if( $quota > 0 ){
$quota_pct = $size_mo * 100 / $quota;
}
if( !is_dir($emailInfo["path"]) ){
$box_exists = false;
}
$returnArray[$email] = array(
"percent" => number_format($quota_pct, 2),
"box_exists" => $box_exists
);
}
return $returnArray;
}
}

View File

@ -0,0 +1,16 @@
<?php
/**
* Lists mailing lists
*/
class Alternc_Diagnostic_Service_Mailman
extends Alternc_Diagnostic_Service_Abstract
implements Alternc_Diagnostic_Service_Interface
{
public $name = "mailman";
function run(){
return $this->data;
}
}

View File

@ -0,0 +1,168 @@
<?php
/**
* Lists databases
* Lists users
*/
class Alternc_Diagnostic_Service_Mysql
extends Alternc_Diagnostic_Service_Abstract
implements Alternc_Diagnostic_Service_Interface {
public $name = "mysql";
protected $dbList;
protected $usersList;
protected $serversList;
const SECTION_DB_LIST = "dbs_list";
const SECTION_USER_LIST = "users_list";
const SECTION_SERVERS_LIST = "servers_list";
const SECTION_STAT_SIZE = "stat_size";
const SECTION_CHECK_ACCESS = "check_access";
/**
*
* @inherit
*/
function run() {
$this->dbList = $this->getDbList();
$this->usersList = $this->getUsersList();
$this->serversList = $this->getServersList();
// Writes the mysql db list
$this->writeSectionData(self::SECTION_DB_LIST, $this->dbList);
// Writes the mysql user list
$this->writeSectionData(self::SECTION_USER_LIST, $this->usersList);
// Writes the mysql servers list
$this->writeSectionData(self::SECTION_SERVERS_LIST, $this->serversList);
// Writes the mysql size stats
$this->writeSectionData(self::SECTION_STAT_SIZE, $this->getSizeStats());
// Writes the mysql access check
$this->writeSectionData(self::SECTION_CHECK_ACCESS, $this->getCheckAccess());
return $this->data;
}
/**
* Returns a db_name -> dbInfo array
*
* @return array
*/
function getDbList() {
$returnArray = array();
$this->db->query("SELECT login,pass,db, bck_mode, bck_dir FROM db ORDER BY db;");
if ($this->db->num_rows()) {
while ($this->db->next_record()) {
$db = $this->db->f("db");
list($dbu,$dbn) = split_mysql_database_name($db);
$returnArray[$db] = array(
"user" => $dbu,
"bck_mode" => $this->db->f("bck_mode"),
"bck_dir" => $this->db->f("bck_dir"),
"login" => $this->db->f("login"),
"pass" => $this->db->f("pass")
);
}
}
return $returnArray;
}
/**
* Returns a db_user_name -> dbUserInfo array
*
* @return array
*/
function getUsersList() {
$returnArray = array();
$this->db->query("SELECT name, password, enable FROM dbusers ORDER BY name;");
if ($this->db->num_rows()) {
while ($this->db->next_record()) {
$returnArray[$this->db->f("name")] = array(
"enable" => $this->db->f("enable"),
"password" => $this->db->f("password")
);
}
}
return $returnArray;
}
/**
* Returns a server_name -> serverInfo array
*
* @return array
*/
function getServersList() {
$returnArray = array();
$this->db->query("SELECT name, host, login, password FROM db_servers ORDER BY host;");
if ($this->db->num_rows()) {
while ($this->db->next_record()) {
$returnArray[$this->db->f("name")] = array(
"host" => $this->db->f("host"),
"login" => $this->db->f("login"),
"password" => $this->db->f("password")
);
}
}
return $returnArray;
}
/**
* Returns a db_name -> db_size array
*
* @return array
*/
function getSizeStats(){
$returnArray = array();
global $L_MYSQL_LOGIN, $L_MYSQL_HOST, $L_MYSQL_PWD;
$db = new DB_Sql();
$db->Host = $L_MYSQL_HOST;
$db->User = $L_MYSQL_LOGIN;
$db->Password = $L_MYSQL_PWD;
$db->Database = "mysql";
foreach ($this->dbList as $dbname => $dbInfo) {
$db->query("SHOW TABLE STATUS FROM `$dbname`;");
$size = 0;
while ($db->next_record()) {
$size += $db->f('Data_length') + $db->f('Index_length');
if ( $db->f('Engine') != 'InnoDB') $size += $db->f('Data_free');
}
$returnArray[$dbname] = $size;
}
return $returnArray;
}
/**
* Returns a user_name -> has_access array
*
* @return array
*/
function getCheckAccess(){
$returnArray = array();
global $L_MYSQL_LOGIN, $L_MYSQL_HOST, $L_MYSQL_PWD;
$db = new DB_Sql();
$db->Host = $L_MYSQL_HOST;
$db->User = $L_MYSQL_LOGIN;
$db->Password = $L_MYSQL_PWD;
$db->Database = "mysql";
foreach ($this->usersList as $user => $userInfo) {
$has_access = false;
$password = $userInfo["password"];
$db->query("SELECT FROM user where user='".$user."' and password=PASSWORD('".$password."') ORDER BY host;");
if ($this->db->num_rows()) {
$has_access = true;
}
$returnArray[$user] = $has_access;
}
return $returnArray;
}
}

View File

@ -0,0 +1,16 @@
<?php
/**
* Lists members
*/
class Alternc_Diagnostic_Service_Panel
extends Alternc_Diagnostic_Service_Abstract
implements Alternc_Diagnostic_Service_Interface
{
public $name = "panel";
function run(){
return $this->data;
}
}

View File

@ -0,0 +1,17 @@
<?php
/**
* Lists versions : php mysql posfix dovecot roundcubke squirrelmail courier mailman alternc-* acl quota sasl
*
*/
class Alternc_Diagnostic_Service_System
extends Alternc_Diagnostic_Service_Abstract
implements Alternc_Diagnostic_Service_Interface
{
public $name = "system";
function run(){
$this->writeSectionData("ip list", $this->execCmd("ip a"));
return $this->data;
}
}

1289
lib/Console/CommandLine.php Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,142 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Class that represent an option action.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
abstract class Console_CommandLine_Action
{
// Properties {{{
/**
* A reference to the result instance.
*
* @var Console_CommandLine_Result $result The result instance
*/
protected $result;
/**
* A reference to the option instance.
*
* @var Console_CommandLine_Option $option The action option
*/
protected $option;
/**
* A reference to the parser instance.
*
* @var Console_CommandLine $parser The parser
*/
protected $parser;
// }}}
// __construct() {{{
/**
* Constructor
*
* @param Console_CommandLine_Result $result The result instance
* @param Console_CommandLine_Option $option The action option
* @param Console_CommandLine $parser The current parser
*
* @return void
*/
public function __construct($result, $option, $parser)
{
$this->result = $result;
$this->option = $option;
$this->parser = $parser;
}
// }}}
// getResult() {{{
/**
* Convenience method to retrieve the value of result->options[name].
*
* @return mixed The result value or null
*/
public function getResult()
{
if (isset($this->result->options[$this->option->name])) {
return $this->result->options[$this->option->name];
}
return null;
}
// }}}
// format() {{{
/**
* Allow a value to be pre-formatted prior to being used in a choices test.
* Setting $value to the new format will keep the formatting.
*
* @param mixed &$value The value to format
*
* @return mixed The formatted value
*/
public function format(&$value)
{
return $value;
}
// }}}
// setResult() {{{
/**
* Convenience method to assign the result->options[name] value.
*
* @param mixed $result The result value
*
* @return void
*/
public function setResult($result)
{
$this->result->options[$this->option->name] = $result;
}
// }}}
// execute() {{{
/**
* Executes the action with the value entered by the user.
* All children actions must implement this method.
*
* @param mixed $value The option value
* @param array $params An optional array of parameters
*
* @return string
*/
abstract public function execute($value = false, $params = array());
// }}}
}

View File

@ -0,0 +1,80 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine/Action.php';
/**
* Class that represent the Callback action.
*
* The result option array entry value is set to the return value of the
* callback defined in the option.
*
* There are two steps to defining a callback option:
* - define the option itself using the callback action
* - write the callback; this is a function (or method) that takes five
* arguments, as described below.
*
* All callbacks are called as follows:
* <code>
* callable_func(
* $value, // the value of the option
* $option_instance, // the option instance
* $result_instance, // the result instance
* $parser_instance, // the parser instance
* $params // an array of params as specified in the option
* );
* </code>
* and *must* return the option value.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Action_Callback extends Console_CommandLine_Action
{
// execute() {{{
/**
* Executes the action with the value entered by the user.
*
* @param mixed $value The value of the option
* @param array $params An optional array of parameters
*
* @return string
*/
public function execute($value = false, $params = array())
{
$this->setResult(call_user_func($this->option->callback, $value,
$this->option, $this->result, $this->parser, $params));
}
// }}}
}

View File

@ -0,0 +1,86 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine/Action.php';
/**
* Class that represent the Version action.
*
* The execute methode add 1 to the value of the result option array entry.
* The value is incremented each time the option is found, for example
* with an option defined like that:
*
* <code>
* $parser->addOption(
* 'verbose',
* array(
* 'short_name' => '-v',
* 'action' => 'Counter'
* )
* );
* </code>
* If the user type:
* <code>
* $ script.php -v -v -v
* </code>
* or:
* <code>
* $ script.php -vvv
* </code>
* the verbose variable will be set to to 3.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Action_Counter extends Console_CommandLine_Action
{
// execute() {{{
/**
* Executes the action with the value entered by the user.
*
* @param mixed $value The option value
* @param array $params An optional array of parameters
*
* @return string
*/
public function execute($value = false, $params = array())
{
$result = $this->getResult();
if ($result === null) {
$result = 0;
}
$this->setResult(++$result);
}
// }}}
}

View File

@ -0,0 +1,60 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine/Action.php';
/**
* Class that represent the Help action, a special action that displays the
* help message, telling the user how to use the program.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Action_Help extends Console_CommandLine_Action
{
// execute() {{{
/**
* Executes the action with the value entered by the user.
*
* @param mixed $value The option value
* @param array $params An optional array of parameters
*
* @return string
*/
public function execute($value = false, $params = array())
{
return $this->parser->displayUsage();
}
// }}}
}

View File

@ -0,0 +1,73 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine/Action.php';
/**
* Class that represent the List action, a special action that simply output an
* array as a list.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Action_List extends Console_CommandLine_Action
{
// execute() {{{
/**
* Executes the action with the value entered by the user.
* Possible parameters are:
* - message: an alternative message to display instead of the default
* message,
* - delimiter: an alternative delimiter instead of the comma,
* - post: a string to append after the message (default is the new line
* char).
*
* @param mixed $value The option value
* @param array $params An optional array of parameters
*
* @return string
*/
public function execute($value = false, $params = array())
{
$list = isset($params['list']) ? $params['list'] : array();
$msg = isset($params['message'])
? $params['message']
: $this->parser->message_provider->get('LIST_DISPLAYED_MESSAGE');
$del = isset($params['delimiter']) ? $params['delimiter'] : ', ';
$post = isset($params['post']) ? $params['post'] : "\n";
$this->parser->outputter->stdout($msg . implode($del, $list) . $post);
exit(0);
}
// }}}
}

View File

@ -0,0 +1,90 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine/Action.php';
/**
* Class that represent the Password action, a special action that allow the
* user to specify the password on the commandline or to be prompted for
* entering it.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Action_Password extends Console_CommandLine_Action
{
// execute() {{{
/**
* Executes the action with the value entered by the user.
*
* @param mixed $value The option value
* @param array $params An array of optional parameters
*
* @return string
*/
public function execute($value = false, $params = array())
{
$this->setResult(empty($value) ? $this->_promptPassword() : $value);
}
// }}}
// _promptPassword() {{{
/**
* Prompts the password to the user without echoing it.
*
* @return string
* @todo not echo-ing the password does not work on windows is there a way
* to make this work ?
*/
private function _promptPassword()
{
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
fwrite(STDOUT,
$this->parser->message_provider->get('PASSWORD_PROMPT_ECHO'));
@flock(STDIN, LOCK_EX);
$passwd = fgets(STDIN);
@flock(STDIN, LOCK_UN);
} else {
fwrite(STDOUT, $this->parser->message_provider->get('PASSWORD_PROMPT'));
// disable echoing
system('stty -echo');
@flock(STDIN, LOCK_EX);
$passwd = fgets(STDIN);
@flock(STDIN, LOCK_UN);
system('stty echo');
}
return trim($passwd);
}
// }}}
}

View File

@ -0,0 +1,78 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine/Action.php';
/**
* Class that represent the StoreArray action.
*
* The execute method appends the value of the option entered by the user to
* the result option array entry.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Action_StoreArray extends Console_CommandLine_Action
{
// Protected properties {{{
/**
* Force a clean result when first called, overriding any defaults assigned.
*
* @var object $firstPass First time this action has been called.
*/
protected $firstPass = true;
// }}}
// execute() {{{
/**
* Executes the action with the value entered by the user.
*
* @param mixed $value The option value
* @param array $params An optional array of parameters
*
* @return string
*/
public function execute($value = false, $params = array())
{
$result = $this->getResult();
if (null === $result || $this->firstPass) {
$result = array();
$this->firstPass = false;
}
$result[] = $value;
$this->setResult($result);
}
// }}}
}

View File

@ -0,0 +1,64 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine/Action.php';
/**
* Class that represent the StoreFalse action.
*
* The execute method store the boolean 'false' in the corrsponding result
* option array entry (the value is true if the option is not present in the
* command line entered by the user).
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Action_StoreFalse extends Console_CommandLine_Action
{
// execute() {{{
/**
* Executes the action with the value entered by the user.
*
* @param mixed $value The option value
* @param array $params An array of optional parameters
*
* @return string
*/
public function execute($value = false, $params = array())
{
$this->setResult(false);
}
// }}}
}

View File

@ -0,0 +1,76 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine/Action.php';
/**
* Class that represent the StoreFloat action.
*
* The execute method store the value of the option entered by the user as a
* float in the result option array entry, if the value passed is not a float
* an Exception is raised.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Action_StoreFloat extends Console_CommandLine_Action
{
// execute() {{{
/**
* Executes the action with the value entered by the user.
*
* @param mixed $value The option value
* @param array $params An array of optional parameters
*
* @return string
* @throws Console_CommandLine_Exception
*/
public function execute($value = false, $params = array())
{
if (!is_numeric($value)) {
include_once 'Console/CommandLine/Exception.php';
throw Console_CommandLine_Exception::factory(
'OPTION_VALUE_TYPE_ERROR',
array(
'name' => $this->option->name,
'type' => 'float',
'value' => $value
),
$this->parser
);
}
$this->setResult((float)$value);
}
// }}}
}

View File

@ -0,0 +1,76 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine/Action.php';
/**
* Class that represent the StoreInt action.
*
* The execute method store the value of the option entered by the user as an
* integer in the result option array entry, if the value passed is not an
* integer an Exception is raised.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Action_StoreInt extends Console_CommandLine_Action
{
// execute() {{{
/**
* Executes the action with the value entered by the user.
*
* @param mixed $value The option value
* @param array $params An array of optional parameters
*
* @return string
* @throws Console_CommandLine_Exception
*/
public function execute($value = false, $params = array())
{
if (!is_numeric($value)) {
include_once 'Console/CommandLine/Exception.php';
throw Console_CommandLine_Exception::factory(
'OPTION_VALUE_TYPE_ERROR',
array(
'name' => $this->option->name,
'type' => 'int',
'value' => $value
),
$this->parser
);
}
$this->setResult((int)$value);
}
// }}}
}

View File

@ -0,0 +1,62 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine/Action.php';
/**
* Class that represent the StoreString action.
*
* The execute method store the value of the option entered by the user as a
* string in the result option array entry.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Action_StoreString extends Console_CommandLine_Action
{
// execute() {{{
/**
* Executes the action with the value entered by the user.
*
* @param mixed $value The option value
* @param array $params An array of optional parameters
*
* @return string
*/
public function execute($value = false, $params = array())
{
$this->setResult((string)$value);
}
// }}}
}

View File

@ -0,0 +1,63 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine/Action.php';
/**
* Class that represent the StoreTrue action.
*
* The execute method store the boolean 'true' in the corrsponding result
* option array entry (the value is false if the option is not present in the
* command line entered by the user).
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Action_StoreTrue extends Console_CommandLine_Action
{
// execute() {{{
/**
* Executes the action with the value entered by the user.
*
* @param mixed $value The option value
* @param array $params An array of optional parameters
*
* @return string
*/
public function execute($value = false, $params = array())
{
$this->setResult(true);
}
// }}}
}

View File

@ -0,0 +1,60 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine/Action.php';
/**
* Class that represent the Version action, a special action that displays the
* version string of the program.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Action_Version extends Console_CommandLine_Action
{
// execute() {{{
/**
* Executes the action with the value entered by the user.
*
* @param mixed $value The option value
* @param array $params An array of optional parameters
*
* @return string
*/
public function execute($value = false, $params = array())
{
return $this->parser->displayVersion();
}
// }}}
}

View File

@ -0,0 +1,102 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Include base element class.
*/
require_once 'Console/CommandLine/Element.php';
/**
* Class that represent a command line argument.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Argument extends Console_CommandLine_Element
{
// Public properties {{{
/**
* Setting this to true will tell the parser that the argument expects more
* than one argument and that argument values should be stored in an array.
*
* @var boolean $multiple Whether the argument expects multiple values
*/
public $multiple = false;
/**
* Setting this to true will tell the parser that the argument is optional
* and can be ommited.
* Note that it is not a good practice to make arguments optional, it is
* the role of the options to be optional, by essence.
*
* @var boolean $optional Whether the argument is optional or not.
*/
public $optional = false;
/**
* An array of possible values for the argument.
*
* @var array $choices Valid choices for the argument
*/
public $choices = array();
// }}}
// validate() {{{
/**
* Validates the argument instance.
*
* @return void
* @throws Console_CommandLine_Exception
* @todo use exceptions
*/
public function validate()
{
// check if the argument name is valid
if (!preg_match('/^[a-zA-Z_\x7f-\xff]+[a-zA-Z0-9_\x7f-\xff]*$/',
$this->name)) {
Console_CommandLine::triggerError(
'argument_bad_name',
E_USER_ERROR,
array('{$name}' => $this->name)
);
}
if (!$this->optional && $this->default !== null) {
Console_CommandLine::triggerError(
'argument_no_default',
E_USER_ERROR
);
}
parent::validate();
}
// }}}
}

View File

@ -0,0 +1,76 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* File containing the parent class.
*/
require_once 'Console/CommandLine.php';
/**
* Class that represent a command with option and arguments.
*
* This class exist just to clarify the interface but at the moment it is
* strictly identical to Console_CommandLine class, it could change in the
* future though.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Command extends Console_CommandLine
{
// Public properties {{{
/**
* An array of aliases for the subcommand.
*
* @var array $aliases Aliases for the subcommand.
*/
public $aliases = array();
// }}}
// __construct() {{{
/**
* Constructor.
*
* @param array $params An optional array of parameters
*
* @return void
*/
public function __construct($params = array())
{
if (isset($params['aliases'])) {
$this->aliases = $params['aliases'];
}
parent::__construct($params);
}
// }}}
}

View File

@ -0,0 +1,66 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @author Michael Gauthier <mike@silverorange.com>
* @copyright 2007 David JEAN LOUIS, 2009 silverorange
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 1.1.0
* @filesource
*/
/**
* Common interfacefor message providers that allow overriding with custom
* messages
*
* Message providers may optionally implement this interface.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @author Michael Gauthier <mike@silverorange.com>
* @copyright 2007 David JEAN LOUIS, 2009 silverorange
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Interface available since release 1.1.0
*/
interface Console_CommandLine_CustomMessageProvider
{
// getWithCustomMesssages() {{{
/**
* Retrieves the given string identifier corresponding message.
*
* For a list of identifiers please see the provided default message
* provider.
*
* @param string $code The string identifier of the message
* @param array $vars An array of template variables
* @param array $messages An optional array of messages to use. Array
* indexes are message codes.
*
* @return string
* @see Console_CommandLine_MessageProvider
* @see Console_CommandLine_MessageProvider_Default
*/
public function getWithCustomMessages(
$code, $vars = array(), $messages = array()
);
// }}}
}

View File

@ -0,0 +1,151 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Class that represent a command line element (an option, or an argument).
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
abstract class Console_CommandLine_Element
{
// Public properties {{{
/**
* The element name.
*
* @var string $name Element name
*/
public $name;
/**
* The name of variable displayed in the usage message, if no set it
* defaults to the "name" property.
*
* @var string $help_name Element "help" variable name
*/
public $help_name;
/**
* The element description.
*
* @var string $description Element description
*/
public $description;
/**
* The default value of the element if not provided on the command line.
*
* @var mixed $default Default value of the option.
*/
public $default;
/**
* Custom errors messages for this element
*
* This array is of the form:
* <code>
* <?php
* array(
* $messageName => $messageText,
* $messageName => $messageText,
* ...
* );
* ?>
* </code>
*
* If specified, these messages override the messages provided by the
* default message provider. For example:
* <code>
* <?php
* $messages = array(
* 'ARGUMENT_REQUIRED' => 'The argument foo is required.',
* );
* ?>
* </code>
*
* @var array
* @see Console_CommandLine_MessageProvider_Default
*/
public $messages = array();
// }}}
// __construct() {{{
/**
* Constructor.
*
* @param string $name The name of the element
* @param array $params An optional array of parameters
*
* @return void
*/
public function __construct($name = null, $params = array())
{
$this->name = $name;
foreach ($params as $attr => $value) {
if (property_exists($this, $attr)) {
$this->$attr = $value;
}
}
}
// }}}
// toString() {{{
/**
* Returns the string representation of the element.
*
* @return string The string representation of the element
* @todo use __toString() instead
*/
public function toString()
{
return $this->help_name;
}
// }}}
// validate() {{{
/**
* Validates the element instance and set it's default values.
*
* @return void
* @throws Console_CommandLine_Exception
*/
public function validate()
{
// if no help_name passed, default to name
if ($this->help_name == null) {
$this->help_name = $this->name;
}
}
// }}}
}

View File

@ -0,0 +1,97 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Include the PEAR_Exception class
*/
require_once 'PEAR/Exception.php';
/**
* Interface for custom message provider.
*/
require_once 'Console/CommandLine/CustomMessageProvider.php';
/**
* Class for exceptions raised by the Console_CommandLine package.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Exception extends PEAR_Exception
{
// Codes constants {{{
/**#@+
* Exception code constants.
*/
const OPTION_VALUE_REQUIRED = 1;
const OPTION_VALUE_UNEXPECTED = 2;
const OPTION_VALUE_TYPE_ERROR = 3;
const OPTION_UNKNOWN = 4;
const ARGUMENT_REQUIRED = 5;
const INVALID_SUBCOMMAND = 6;
/**#@-*/
// }}}
// factory() {{{
/**
* Convenience method that builds the exception with the array of params by
* calling the message provider class.
*
* @param string $code The string identifier of the
* exception.
* @param array $params Array of template vars/values
* @param Console_CommandLine $parser An instance of the parser
* @param array $messages An optional array of messages
* passed to the message provider.
*
* @return object an instance of Console_CommandLine_Exception
*/
public static function factory(
$code, $params, $parser, array $messages = array()
) {
$provider = $parser->message_provider;
if ($provider instanceof Console_CommandLine_CustomMessageProvider) {
$msg = $provider->getWithCustomMessages(
$code,
$params,
$messages
);
} else {
$msg = $provider->get($code, $params);
}
$const = 'Console_CommandLine_Exception::' . $code;
$code = defined($const) ? constant($const) : 0;
return new Console_CommandLine_Exception($msg, $code);
}
// }}}
}

View File

@ -0,0 +1,56 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Message providers common interface, all message providers must implement
* this interface.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
interface Console_CommandLine_MessageProvider
{
// get() {{{
/**
* Retrieves the given string identifier corresponding message.
* For a list of identifiers please see the provided default message
* provider.
*
* @param string $code The string identifier of the message
* @param array $vars An array of template variables
*
* @return string
* @see Console_CommandLine_MessageProvider_Default
*/
public function get($code, $vars=array());
// }}}
}

View File

@ -0,0 +1,153 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* The message provider interface.
*/
require_once 'Console/CommandLine/MessageProvider.php';
/**
* The custom message provider interface.
*/
require_once 'Console/CommandLine/CustomMessageProvider.php';
/**
* Lightweight class that manages messages used by Console_CommandLine package,
* allowing the developper to customize these messages, for example to
* internationalize a command line frontend.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_MessageProvider_Default
implements Console_CommandLine_MessageProvider,
Console_CommandLine_CustomMessageProvider
{
// Properties {{{
/**
* Associative array of messages
*
* @var array $messages
*/
protected $messages = array(
'OPTION_VALUE_REQUIRED' => 'Option "{$name}" requires a value.',
'OPTION_VALUE_UNEXPECTED' => 'Option "{$name}" does not expect a value (got "{$value}").',
'OPTION_VALUE_NOT_VALID' => 'Option "{$name}" must be one of the following: "{$choices}" (got "{$value}").',
'ARGUMENT_VALUE_NOT_VALID'=> 'Argument "{$name}" must be one of the following: "{$choices}" (got "{$value}").',
'OPTION_VALUE_TYPE_ERROR' => 'Option "{$name}" requires a value of type {$type} (got "{$value}").',
'OPTION_AMBIGUOUS' => 'Ambiguous option "{$name}", can be one of the following: {$matches}.',
'OPTION_UNKNOWN' => 'Unknown option "{$name}".',
'ARGUMENT_REQUIRED' => 'You must provide at least {$argnum} argument{$plural}.',
'PROG_HELP_LINE' => 'Type "{$progname} --help" to get help.',
'PROG_VERSION_LINE' => '{$progname} version {$version}.',
'COMMAND_HELP_LINE' => 'Type "{$progname} <command> --help" to get help on specific command.',
'USAGE_WORD' => 'Usage',
'OPTION_WORD' => 'Options',
'ARGUMENT_WORD' => 'Arguments',
'COMMAND_WORD' => 'Commands',
'PASSWORD_PROMPT' => 'Password: ',
'PASSWORD_PROMPT_ECHO' => 'Password (warning: will echo): ',
'INVALID_CUSTOM_INSTANCE' => 'Instance does not implement the required interface',
'LIST_OPTION_MESSAGE' => 'lists valid choices for option {$name}',
'LIST_DISPLAYED_MESSAGE' => 'Valid choices are: ',
'INVALID_SUBCOMMAND' => 'Command "{$command}" is not valid.',
'SUBCOMMAND_REQUIRED' => 'Please enter one of the following command: {$commands}.',
);
// }}}
// get() {{{
/**
* Retrieve the given string identifier corresponding message.
*
* @param string $code The string identifier of the message
* @param array $vars An array of template variables
*
* @return string
*/
public function get($code, $vars = array())
{
if (!isset($this->messages[$code])) {
return 'UNKNOWN';
}
return $this->replaceTemplateVars($this->messages[$code], $vars);
}
// }}}
// getWithCustomMessages() {{{
/**
* Retrieve the given string identifier corresponding message.
*
* @param string $code The string identifier of the message
* @param array $vars An array of template variables
* @param array $messages An optional array of messages to use. Array
* indexes are message codes.
*
* @return string
*/
public function getWithCustomMessages(
$code, $vars = array(), $messages = array()
) {
// get message
if (isset($messages[$code])) {
$message = $messages[$code];
} elseif (isset($this->messages[$code])) {
$message = $this->messages[$code];
} else {
$message = 'UNKNOWN';
}
return $this->replaceTemplateVars($message, $vars);
}
// }}}
// replaceTemplateVars() {{{
/**
* Replaces template vars in a message
*
* @param string $message The message
* @param array $vars An array of template variables
*
* @return string
*/
protected function replaceTemplateVars($message, $vars = array())
{
$tmpkeys = array_keys($vars);
$keys = array();
foreach ($tmpkeys as $key) {
$keys[] = '{$' . $key . '}';
}
return str_replace($keys, array_values($vars), $message);
}
// }}}
}

View File

@ -0,0 +1,366 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required by this class.
*/
require_once 'Console/CommandLine.php';
require_once 'Console/CommandLine/Element.php';
/**
* Class that represent a commandline option.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Option extends Console_CommandLine_Element
{
// Public properties {{{
/**
* The option short name (ex: -v).
*
* @var string $short_name Short name of the option
*/
public $short_name;
/**
* The option long name (ex: --verbose).
*
* @var string $long_name Long name of the option
*/
public $long_name;
/**
* The option action, defaults to "StoreString".
*
* @var string $action Option action
*/
public $action = 'StoreString';
/**
* An array of possible values for the option. If this array is not empty
* and the value passed is not in the array an exception is raised.
* This only make sense for actions that accept values of course.
*
* @var array $choices Valid choices for the option
*/
public $choices = array();
/**
* The callback function (or method) to call for an action of type
* Callback, this can be any callable supported by the php function
* call_user_func.
*
* Example:
*
* <code>
* $parser->addOption('myoption', array(
* 'short_name' => '-m',
* 'long_name' => '--myoption',
* 'action' => 'Callback',
* 'callback' => 'myCallbackFunction'
* ));
* </code>
*
* @var callable $callback The option callback
*/
public $callback;
/**
* An associative array of additional params to pass to the class
* corresponding to the action, this array will also be passed to the
* callback defined for an action of type Callback, Example:
*
* <code>
* // for a custom action
* $parser->addOption('myoption', array(
* 'short_name' => '-m',
* 'long_name' => '--myoption',
* 'action' => 'MyCustomAction',
* 'action_params' => array('foo'=>true, 'bar'=>false)
* ));
*
* // if the user type:
* // $ <yourprogram> -m spam
* // in your MyCustomAction class the execute() method will be called
* // with the value 'spam' as first parameter and
* // array('foo'=>true, 'bar'=>false) as second parameter
* </code>
*
* @var array $action_params Additional parameters to pass to the action
*/
public $action_params = array();
/**
* For options that expect an argument, this property tells the parser if
* the option argument is optional and can be ommited.
*
* @var bool $argumentOptional Whether the option arg is optional or not
*/
public $argument_optional = false;
/**
* For options that uses the "choice" property only.
* Adds a --list-<choice> option to the parser that displays the list of
* choices for the option.
*
* @var bool $add_list_option Whether to add a list option or not
*/
public $add_list_option = false;
// }}}
// Private properties {{{
/**
* When an action is called remember it to allow for multiple calls.
*
* @var object $action_instance Placeholder for action
*/
private $_action_instance = null;
// }}}
// __construct() {{{
/**
* Constructor.
*
* @param string $name The name of the option
* @param array $params An optional array of parameters
*
* @return void
*/
public function __construct($name = null, $params = array())
{
parent::__construct($name, $params);
if ($this->action == 'Password') {
// special case for Password action, password can be passed to the
// commandline or prompted by the parser
$this->argument_optional = true;
}
}
// }}}
// toString() {{{
/**
* Returns the string representation of the option.
*
* @param string $delim Delimiter to use between short and long option
*
* @return string The string representation of the option
* @todo use __toString() instead
*/
public function toString($delim = ", ")
{
$ret = '';
$padding = '';
if ($this->short_name != null) {
$ret .= $this->short_name;
if ($this->expectsArgument()) {
$ret .= ' ' . $this->help_name;
}
$padding = $delim;
}
if ($this->long_name != null) {
$ret .= $padding . $this->long_name;
if ($this->expectsArgument()) {
$ret .= '=' . $this->help_name;
}
}
return $ret;
}
// }}}
// expectsArgument() {{{
/**
* Returns true if the option requires one or more argument and false
* otherwise.
*
* @return bool Whether the option expects an argument or not
*/
public function expectsArgument()
{
if ($this->action == 'StoreTrue' || $this->action == 'StoreFalse' ||
$this->action == 'Help' || $this->action == 'Version' ||
$this->action == 'Counter' || $this->action == 'List') {
return false;
}
return true;
}
// }}}
// dispatchAction() {{{
/**
* Formats the value $value according to the action of the option and
* updates the passed Console_CommandLine_Result object.
*
* @param mixed $value The value to format
* @param Console_CommandLine_Result $result The result instance
* @param Console_CommandLine $parser The parser instance
*
* @return void
* @throws Console_CommandLine_Exception
*/
public function dispatchAction($value, $result, $parser)
{
$actionInfo = Console_CommandLine::$actions[$this->action];
if (true === $actionInfo[1]) {
// we have a "builtin" action
$tokens = explode('_', $actionInfo[0]);
include_once implode('/', $tokens) . '.php';
}
$clsname = $actionInfo[0];
if ($this->_action_instance === null) {
$this->_action_instance = new $clsname($result, $this, $parser);
}
// check value is in option choices
if (!empty($this->choices) && !in_array($this->_action_instance->format($value), $this->choices)) {
throw Console_CommandLine_Exception::factory(
'OPTION_VALUE_NOT_VALID',
array(
'name' => $this->name,
'choices' => implode('", "', $this->choices),
'value' => $value,
),
$parser,
$this->messages
);
}
$this->_action_instance->execute($value, $this->action_params);
}
// }}}
// validate() {{{
/**
* Validates the option instance.
*
* @return void
* @throws Console_CommandLine_Exception
* @todo use exceptions instead
*/
public function validate()
{
// check if the option name is valid
if (!preg_match('/^[a-zA-Z_\x7f-\xff]+[a-zA-Z0-9_\x7f-\xff]*$/',
$this->name)) {
Console_CommandLine::triggerError('option_bad_name',
E_USER_ERROR, array('{$name}' => $this->name));
}
// call the parent validate method
parent::validate();
// a short_name or a long_name must be provided
if ($this->short_name == null && $this->long_name == null) {
Console_CommandLine::triggerError('option_long_and_short_name_missing',
E_USER_ERROR, array('{$name}' => $this->name));
}
// check if the option short_name is valid
if ($this->short_name != null &&
!(preg_match('/^\-[a-zA-Z]{1}$/', $this->short_name))) {
Console_CommandLine::triggerError('option_bad_short_name',
E_USER_ERROR, array(
'{$name}' => $this->name,
'{$short_name}' => $this->short_name
));
}
// check if the option long_name is valid
if ($this->long_name != null &&
!preg_match('/^\-\-[a-zA-Z]+[a-zA-Z0-9_\-]*$/', $this->long_name)) {
Console_CommandLine::triggerError('option_bad_long_name',
E_USER_ERROR, array(
'{$name}' => $this->name,
'{$long_name}' => $this->long_name
));
}
// check if we have a valid action
if (!is_string($this->action)) {
Console_CommandLine::triggerError('option_bad_action',
E_USER_ERROR, array('{$name}' => $this->name));
}
if (!isset(Console_CommandLine::$actions[$this->action])) {
Console_CommandLine::triggerError('option_unregistered_action',
E_USER_ERROR, array(
'{$action}' => $this->action,
'{$name}' => $this->name
));
}
// if the action is a callback, check that we have a valid callback
if ($this->action == 'Callback' && !is_callable($this->callback)) {
Console_CommandLine::triggerError('option_invalid_callback',
E_USER_ERROR, array('{$name}' => $this->name));
}
}
// }}}
// setDefaults() {{{
/**
* Set the default value according to the configured action.
*
* Note that for backward compatibility issues this method is only called
* when the 'force_options_defaults' is set to true, it will become the
* default behaviour in the next major release of Console_CommandLine.
*
* @return void
*/
public function setDefaults()
{
if ($this->default !== null) {
// already set
return;
}
switch ($this->action) {
case 'Counter':
case 'StoreInt':
$this->default = 0;
break;
case 'StoreFloat':
$this->default = 0.0;
break;
case 'StoreArray':
$this->default = array();
break;
case 'StoreTrue':
$this->default = false;
break;
case 'StoreFalse':
$this->default = true;
break;
default:
return;
}
}
// }}}
}

View File

@ -0,0 +1,63 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Outputters common interface, all outputters must implement this interface.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
interface Console_CommandLine_Outputter
{
// stdout() {{{
/**
* Processes the output for a message that should be displayed on STDOUT.
*
* @param string $msg The message to output
*
* @return void
*/
public function stdout($msg);
// }}}
// stderr() {{{
/**
* Processes the output for a message that should be displayed on STDERR.
*
* @param string $msg The message to output
*
* @return void
*/
public function stderr($msg);
// }}}
}

View File

@ -0,0 +1,82 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* The Outputter interface.
*/
require_once 'Console/CommandLine/Outputter.php';
/**
* Console_CommandLine default Outputter.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Outputter_Default implements Console_CommandLine_Outputter
{
// stdout() {{{
/**
* Writes the message $msg to STDOUT.
*
* @param string $msg The message to output
*
* @return void
*/
public function stdout($msg)
{
if (defined('STDOUT')) {
fwrite(STDOUT, $msg);
} else {
echo $msg;
}
}
// }}}
// stderr() {{{
/**
* Writes the message $msg to STDERR.
*
* @param string $msg The message to output
*
* @return void
*/
public function stderr($msg)
{
if (defined('STDERR')) {
fwrite(STDERR, $msg);
} else {
echo $msg;
}
}
// }}}
}

View File

@ -0,0 +1,71 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Renderers common interface, all renderers must implement this interface.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
interface Console_CommandLine_Renderer
{
// usage() {{{
/**
* Returns the full usage message.
*
* @return string The usage message
*/
public function usage();
// }}}
// error() {{{
/**
* Returns a formatted error message.
*
* @param string $error The error message to format
*
* @return string The error string
*/
public function error($error);
// }}}
// version() {{{
/**
* Returns the program version string.
*
* @return string The version string
*/
public function version();
// }}}
}

View File

@ -0,0 +1,424 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* The renderer interface.
*/
require_once 'Console/CommandLine/Renderer.php';
/**
* Console_CommandLine default renderer.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Renderer_Default implements Console_CommandLine_Renderer
{
// Properties {{{
/**
* Integer that define the max width of the help text.
*
* @var integer $line_width Line width
*/
public $line_width = 75;
/**
* Integer that define the max width of the help text.
*
* @var integer $line_width Line width
*/
public $options_on_different_lines = false;
/**
* An instance of Console_CommandLine.
*
* @var Console_CommandLine $parser The parser
*/
public $parser = false;
// }}}
// __construct() {{{
/**
* Constructor.
*
* @param object $parser A Console_CommandLine instance
*
* @return void
*/
public function __construct($parser = false)
{
$this->parser = $parser;
}
// }}}
// usage() {{{
/**
* Returns the full usage message.
*
* @return string The usage message
*/
public function usage()
{
$ret = '';
if (!empty($this->parser->description)) {
$ret .= $this->description() . "\n\n";
}
$ret .= $this->usageLine() . "\n";
if (count($this->parser->commands) > 0) {
$ret .= $this->commandUsageLine() . "\n";
}
if (count($this->parser->options) > 0) {
$ret .= "\n" . $this->optionList() . "\n";
}
if (count($this->parser->args) > 0) {
$ret .= "\n" . $this->argumentList() . "\n";
}
if (count($this->parser->commands) > 0) {
$ret .= "\n" . $this->commandList() . "\n";
}
$ret .= "\n";
return $ret;
}
// }}}
// error() {{{
/**
* Returns a formatted error message.
*
* @param string $error The error message to format
*
* @return string The error string
*/
public function error($error)
{
$ret = 'Error: ' . $error . "\n";
if ($this->parser->add_help_option) {
$name = $this->name();
$ret .= $this->wrap($this->parser->message_provider->get('PROG_HELP_LINE',
array('progname' => $name))) . "\n";
if (count($this->parser->commands) > 0) {
$ret .= $this->wrap($this->parser->message_provider->get('COMMAND_HELP_LINE',
array('progname' => $name))) . "\n";
}
}
return $ret;
}
// }}}
// version() {{{
/**
* Returns the program version string.
*
* @return string The version string
*/
public function version()
{
return $this->parser->message_provider->get('PROG_VERSION_LINE', array(
'progname' => $this->name(),
'version' => $this->parser->version
)) . "\n";
}
// }}}
// name() {{{
/**
* Returns the full name of the program or the sub command
*
* @return string The name of the program
*/
protected function name()
{
$name = $this->parser->name;
$parent = $this->parser->parent;
while ($parent) {
if (count($parent->options) > 0) {
$name = '['
. strtolower($this->parser->message_provider->get('OPTION_WORD',
array('plural' => 's')))
. '] ' . $name;
}
$name = $parent->name . ' ' . $name;
$parent = $parent->parent;
}
return $this->wrap($name);
}
// }}}
// description() {{{
/**
* Returns the command line description message.
*
* @return string The description message
*/
protected function description()
{
return $this->wrap($this->parser->description);
}
// }}}
// usageLine() {{{
/**
* Returns the command line usage message
*
* @return string the usage message
*/
protected function usageLine()
{
$usage = $this->parser->message_provider->get('USAGE_WORD') . ":\n";
$ret = $usage . ' ' . $this->name();
if (count($this->parser->options) > 0) {
$ret .= ' ['
. strtolower($this->parser->message_provider->get('OPTION_WORD'))
. ']';
}
if (count($this->parser->args) > 0) {
foreach ($this->parser->args as $name=>$arg) {
$arg_str = $arg->help_name;
if ($arg->multiple) {
$arg_str .= '1 ' . $arg->help_name . '2 ...';
}
if ($arg->optional) {
$arg_str = '[' . $arg_str . ']';
}
$ret .= ' ' . $arg_str;
}
}
return $this->columnWrap($ret, 2);
}
// }}}
// commandUsageLine() {{{
/**
* Returns the command line usage message for subcommands.
*
* @return string The usage line
*/
protected function commandUsageLine()
{
if (count($this->parser->commands) == 0) {
return '';
}
$ret = ' ' . $this->name();
if (count($this->parser->options) > 0) {
$ret .= ' ['
. strtolower($this->parser->message_provider->get('OPTION_WORD'))
. ']';
}
$ret .= " <command>";
$hasArgs = false;
$hasOptions = false;
foreach ($this->parser->commands as $command) {
if (!$hasArgs && count($command->args) > 0) {
$hasArgs = true;
}
if (!$hasOptions && ($command->add_help_option ||
$command->add_version_option || count($command->options) > 0)) {
$hasOptions = true;
}
}
if ($hasOptions) {
$ret .= ' [options]';
}
if ($hasArgs) {
$ret .= ' [args]';
}
return $this->columnWrap($ret, 2);
}
// }}}
// argumentList() {{{
/**
* Render the arguments list that will be displayed to the user, you can
* override this method if you want to change the look of the list.
*
* @return string The formatted argument list
*/
protected function argumentList()
{
$col = 0;
$args = array();
foreach ($this->parser->args as $arg) {
$argstr = ' ' . $arg->toString();
$args[] = array($argstr, $arg->description);
$ln = strlen($argstr);
if ($col < $ln) {
$col = $ln;
}
}
$ret = $this->parser->message_provider->get('ARGUMENT_WORD') . ":";
foreach ($args as $arg) {
$text = str_pad($arg[0], $col) . ' ' . $arg[1];
$ret .= "\n" . $this->columnWrap($text, $col+2);
}
return $ret;
}
// }}}
// optionList() {{{
/**
* Render the options list that will be displayed to the user, you can
* override this method if you want to change the look of the list.
*
* @return string The formatted option list
*/
protected function optionList()
{
$col = 0;
$options = array();
foreach ($this->parser->options as $option) {
$delim = $this->options_on_different_lines ? "\n" : ', ';
$optstr = $option->toString($delim);
$lines = explode("\n", $optstr);
$lines[0] = ' ' . $lines[0];
if (count($lines) > 1) {
$lines[1] = ' ' . $lines[1];
$ln = strlen($lines[1]);
} else {
$ln = strlen($lines[0]);
}
$options[] = array($lines, $option->description);
if ($col < $ln) {
$col = $ln;
}
}
$ret = $this->parser->message_provider->get('OPTION_WORD') . ":";
foreach ($options as $option) {
if (count($option[0]) > 1) {
$text = str_pad($option[0][1], $col) . ' ' . $option[1];
$pre = $option[0][0] . "\n";
} else {
$text = str_pad($option[0][0], $col) . ' ' . $option[1];
$pre = '';
}
$ret .= "\n" . $pre . $this->columnWrap($text, $col+2);
}
return $ret;
}
// }}}
// commandList() {{{
/**
* Render the command list that will be displayed to the user, you can
* override this method if you want to change the look of the list.
*
* @return string The formatted subcommand list
*/
protected function commandList()
{
$commands = array();
$col = 0;
foreach ($this->parser->commands as $cmdname=>$command) {
$cmdname = ' ' . $cmdname;
$commands[] = array($cmdname, $command->description, $command->aliases);
$ln = strlen($cmdname);
if ($col < $ln) {
$col = $ln;
}
}
$ret = $this->parser->message_provider->get('COMMAND_WORD') . ":";
foreach ($commands as $command) {
$text = str_pad($command[0], $col) . ' ' . $command[1];
if ($aliasesCount = count($command[2])) {
$pad = '';
$text .= ' (';
$text .= $aliasesCount > 1 ? 'aliases: ' : 'alias: ';
foreach ($command[2] as $alias) {
$text .= $pad . $alias;
$pad = ', ';
}
$text .= ')';
}
$ret .= "\n" . $this->columnWrap($text, $col+2);
}
return $ret;
}
// }}}
// wrap() {{{
/**
* Wraps the text passed to the method.
*
* @param string $text The text to wrap
* @param int $lw The column width (defaults to line_width property)
*
* @return string The wrapped text
*/
protected function wrap($text, $lw=null)
{
if ($this->line_width > 0) {
if ($lw === null) {
$lw = $this->line_width;
}
return wordwrap($text, $lw, "\n", false);
}
return $text;
}
// }}}
// columnWrap() {{{
/**
* Wraps the text passed to the method at the specified width.
*
* @param string $text The text to wrap
* @param int $cw The wrap width
*
* @return string The wrapped text
*/
protected function columnWrap($text, $cw)
{
$tokens = explode("\n", $this->wrap($text));
$ret = $tokens[0];
$chunks = $this->wrap(trim(substr($text, strlen($ret))),
$this->line_width - $cw);
$tokens = explode("\n", $chunks);
foreach ($tokens as $token) {
if (!empty($token)) {
$ret .= "\n" . str_repeat(' ', $cw) . $token;
}
}
return $ret;
}
// }}}
}

View File

@ -0,0 +1,71 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* A lightweight class to store the result of the command line parsing.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: 1.2.0
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Result
{
// Public properties {{{
/**
* The result options associative array.
* Key is the name of the option and value its value.
*
* @var array $options Result options array
*/
public $options = array();
/**
* The result arguments array.
*
* @var array $args Result arguments array
*/
public $args = array();
/**
* Name of the command invoked by the user, false if no command invoked.
*
* @var string $command_name Result command name
*/
public $command_name = false;
/**
* A result instance for the subcommand.
*
* @var Console_CommandLine_Result Result instance for the subcommand
*/
public $command = false;
// }}}
}

View File

@ -0,0 +1,312 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* This file is part of the PEAR Console_CommandLine package.
*
* PHP version 5
*
* LICENSE: This source file is subject to the MIT license that is available
* through the world-wide-web at the following URI:
* http://opensource.org/licenses/mit-license.php
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version CVS: $Id$
* @link http://pear.php.net/package/Console_CommandLine
* @since File available since release 0.1.0
* @filesource
*/
/**
* Required file
*/
require_once 'Console/CommandLine.php';
/**
* Parser for command line xml definitions.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license.php MIT License
* @version Release: @package_version@
* @link http://pear.php.net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_XmlParser
{
// parse() {{{
/**
* Parses the given xml definition file and returns a
* Console_CommandLine instance constructed with the xml data.
*
* @param string $xmlfile The xml file to parse
*
* @return Console_CommandLine A parser instance
*/
public static function parse($xmlfile)
{
if (!is_readable($xmlfile)) {
Console_CommandLine::triggerError('invalid_xml_file',
E_USER_ERROR, array('{$file}' => $xmlfile));
}
$doc = new DomDocument();
$doc->load($xmlfile);
self::validate($doc);
$nodes = $doc->getElementsByTagName('command');
$root = $nodes->item(0);
return self::_parseCommandNode($root, true);
}
// }}}
// parseString() {{{
/**
* Parses the given xml definition string and returns a
* Console_CommandLine instance constructed with the xml data.
*
* @param string $xmlstr The xml string to parse
*
* @return Console_CommandLine A parser instance
*/
public static function parseString($xmlstr)
{
$doc = new DomDocument();
$doc->loadXml($xmlstr);
self::validate($doc);
$nodes = $doc->getElementsByTagName('command');
$root = $nodes->item(0);
return self::_parseCommandNode($root, true);
}
// }}}
// validate() {{{
/**
* Validates the xml definition using Relax NG.
*
* @param DomDocument $doc The document to validate
*
* @return boolean Whether the xml data is valid or not.
* @throws Console_CommandLine_Exception
* @todo use exceptions
*/
public static function validate($doc)
{
if (is_dir('@data_dir@' . DIRECTORY_SEPARATOR . 'Console_CommandLine')) {
$rngfile = '@data_dir@' . DIRECTORY_SEPARATOR
. 'Console_CommandLine' . DIRECTORY_SEPARATOR . 'data'
. DIRECTORY_SEPARATOR . 'xmlschema.rng';
} else {
$rngfile = dirname(__FILE__) . DIRECTORY_SEPARATOR . '..'
. DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'data'
. DIRECTORY_SEPARATOR . 'xmlschema.rng';
}
if (!is_readable($rngfile)) {
Console_CommandLine::triggerError('invalid_xml_file',
E_USER_ERROR, array('{$file}' => $rngfile));
}
return $doc->relaxNGValidate($rngfile);
}
// }}}
// _parseCommandNode() {{{
/**
* Parses the root command node or a command node and returns the
* constructed Console_CommandLine or Console_CommandLine_Command instance.
*
* @param DomDocumentNode $node The node to parse
* @param bool $isRootNode Whether it is a root node or not
*
* @return mixed Console_CommandLine or Console_CommandLine_Command
*/
private static function _parseCommandNode($node, $isRootNode = false)
{
if ($isRootNode) {
$obj = new Console_CommandLine();
} else {
include_once 'Console/CommandLine/Command.php';
$obj = new Console_CommandLine_Command();
}
foreach ($node->childNodes as $cNode) {
$cNodeName = $cNode->nodeName;
switch ($cNodeName) {
case 'name':
case 'description':
case 'version':
$obj->$cNodeName = trim($cNode->nodeValue);
break;
case 'add_help_option':
case 'add_version_option':
case 'force_posix':
$obj->$cNodeName = self::_bool(trim($cNode->nodeValue));
break;
case 'option':
$obj->addOption(self::_parseOptionNode($cNode));
break;
case 'argument':
$obj->addArgument(self::_parseArgumentNode($cNode));
break;
case 'command':
$obj->addCommand(self::_parseCommandNode($cNode));
break;
case 'aliases':
if (!$isRootNode) {
foreach ($cNode->childNodes as $subChildNode) {
if ($subChildNode->nodeName == 'alias') {
$obj->aliases[] = trim($subChildNode->nodeValue);
}
}
}
break;
case 'messages':
$obj->messages = self::_messages($cNode);
break;
default:
break;
}
}
return $obj;
}
// }}}
// _parseOptionNode() {{{
/**
* Parses an option node and returns the constructed
* Console_CommandLine_Option instance.
*
* @param DomDocumentNode $node The node to parse
*
* @return Console_CommandLine_Option The built option
*/
private static function _parseOptionNode($node)
{
include_once 'Console/CommandLine/Option.php';
$obj = new Console_CommandLine_Option($node->getAttribute('name'));
foreach ($node->childNodes as $cNode) {
$cNodeName = $cNode->nodeName;
switch ($cNodeName) {
case 'choices':
foreach ($cNode->childNodes as $subChildNode) {
if ($subChildNode->nodeName == 'choice') {
$obj->choices[] = trim($subChildNode->nodeValue);
}
}
break;
case 'messages':
$obj->messages = self::_messages($cNode);
break;
default:
if (property_exists($obj, $cNodeName)) {
$obj->$cNodeName = trim($cNode->nodeValue);
}
break;
}
}
if ($obj->action == 'Password') {
$obj->argument_optional = true;
}
return $obj;
}
// }}}
// _parseArgumentNode() {{{
/**
* Parses an argument node and returns the constructed
* Console_CommandLine_Argument instance.
*
* @param DomDocumentNode $node The node to parse
*
* @return Console_CommandLine_Argument The built argument
*/
private static function _parseArgumentNode($node)
{
include_once 'Console/CommandLine/Argument.php';
$obj = new Console_CommandLine_Argument($node->getAttribute('name'));
foreach ($node->childNodes as $cNode) {
$cNodeName = $cNode->nodeName;
switch ($cNodeName) {
case 'description':
case 'help_name':
case 'default':
$obj->$cNodeName = trim($cNode->nodeValue);
break;
case 'multiple':
$obj->multiple = self::_bool(trim($cNode->nodeValue));
break;
case 'optional':
$obj->optional = self::_bool(trim($cNode->nodeValue));
break;
case 'choices':
foreach ($cNode->childNodes as $subChildNode) {
if ($subChildNode->nodeName == 'choice') {
$obj->choices[] = trim($subChildNode->nodeValue);
}
}
break;
case 'messages':
$obj->messages = self::_messages($cNode);
break;
default:
break;
}
}
return $obj;
}
// }}}
// _bool() {{{
/**
* Returns a boolean according to true/false possible strings.
*
* @param string $str The string to process
*
* @return boolean
*/
private static function _bool($str)
{
return in_array(strtolower((string)$str), array('true', '1', 'on', 'yes'));
}
// }}}
// _messages() {{{
/**
* Returns an array of custom messages for the element
*
* @param DOMNode $node The messages node to process
*
* @return array an array of messages
*
* @see Console_CommandLine::$messages
* @see Console_CommandLine_Element::$messages
*/
private static function _messages(DOMNode $node)
{
$messages = array();
foreach ($node->childNodes as $cNode) {
if ($cNode->nodeType == XML_ELEMENT_NODE) {
$name = $cNode->getAttribute('name');
$value = trim($cNode->nodeValue);
$messages[$name] = $value;
}
}
return $messages;
}
// }}}
}

65
lib/Console/Exception.php Normal file
View File

@ -0,0 +1,65 @@
<?php
/**
* Class for exceptions raised by the Console_CommandLine package.
*
* @category Console
* @package Console_CommandLine
* @author David JEAN LOUIS <izimobil@gmail.com>
* @copyright 2007 David JEAN LOUIS
* @license http://opensource.org/licenses/mit-license. MIT License
* @version Release: 1.2.0
* @link http://pear..net/package/Console_CommandLine
* @since Class available since release 0.1.0
*/
class Console_CommandLine_Exception extends PEAR_Exception
{
// Codes constants {{{
/**#@+
* Exception code constants.
*/
const OPTION_VALUE_REQUIRED = 1;
const OPTION_VALUE_UNEXPECTED = 2;
const OPTION_VALUE_TYPE_ERROR = 3;
const OPTION_UNKNOWN = 4;
const ARGUMENT_REQUIRED = 5;
const INVALID_SUBCOMMAND = 6;
/**#@-*/
// }}}
// factory() {{{
/**
* Convenience method that builds the exception with the array of params by
* calling the message provider class.
*
* @param string $code The string identifier of the
* exception.
* @param array $params Array of template vars/values
* @param Console_CommandLine $parser An instance of the parser
* @param array $messages An optional array of messages
* passed to the message provider.
*
* @return object an instance of Console_CommandLine_Exception
*/
public static function factory(
$code, $params, $parser, array $messages = array()
) {
$provider = $parser->message_provider;
if ($provider instanceof Console_CommandLine_CustomMessageProvider) {
$msg = $provider->getWithCustomMessages(
$code,
$params,
$messages
);
} else {
$msg = $provider->get($code, $params);
}
$const = 'Console_CommandLine_Exception::' . $code;
$code = defined($const) ? constant($const) : 0;
return new Console_CommandLine_Exception($msg, $code);
}
// }}}
}

388
lib/PEAR/Exception.php Normal file
View File

@ -0,0 +1,388 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
/**
* PEAR_Exception
*
* PHP version 5
*
* @category pear
* @package PEAR_Exception
* @author Tomas V. V. Cox <cox@idecnet.com>
* @author Hans Lellelid <hans@velum.net>
* @author Bertrand Mansion <bmansion@mamasam.com>
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @link http://pear.php.net/package/PEAR_Exception
* @since File available since Release 1.0.0
*/
/**
* Base PEAR_Exception Class
*
* 1) Features:
*
* - Nestable exceptions (throw new PEAR_Exception($msg, $prev_exception))
* - Definable triggers, shot when exceptions occur
* - Pretty and informative error messages
* - Added more context info available (like class, method or cause)
* - cause can be a PEAR_Exception or an array of mixed
* PEAR_Exceptions/PEAR_ErrorStack warnings
* - callbacks for specific exception classes and their children
*
* 2) Ideas:
*
* - Maybe a way to define a 'template' for the output
*
* 3) Inherited properties from PHP Exception Class:
*
* protected $message
* protected $code
* protected $line
* protected $file
* private $trace
*
* 4) Inherited methods from PHP Exception Class:
*
* __clone
* __construct
* getMessage
* getCode
* getFile
* getLine
* getTraceSafe
* getTraceSafeAsString
* __toString
*
* 5) Usage example
*
* <code>
* require_once 'PEAR/Exception.php';
*
* class Test {
* function foo() {
* throw new PEAR_Exception('Error Message', ERROR_CODE);
* }
* }
*
* function myLogger($pear_exception) {
* echo $pear_exception->getMessage();
* }
* // each time a exception is thrown the 'myLogger' will be called
* // (its use is completely optional)
* PEAR_Exception::addObserver('myLogger');
* $test = new Test;
* try {
* $test->foo();
* } catch (PEAR_Exception $e) {
* print $e;
* }
* </code>
*
* @category pear
* @package PEAR_Exception
* @author Tomas V.V.Cox <cox@idecnet.com>
* @author Hans Lellelid <hans@velum.net>
* @author Bertrand Mansion <bmansion@mamasam.com>
* @author Greg Beaver <cellog@php.net>
* @copyright 1997-2009 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version Release: 1.0.0beta1
* @link http://pear.php.net/package/PEAR_Exception
* @since Class available since Release 1.0.0
*
*/
class PEAR_Exception extends Exception
{
const OBSERVER_PRINT = -2;
const OBSERVER_TRIGGER = -4;
const OBSERVER_DIE = -8;
protected $cause;
private static $_observers = array();
private static $_uniqueid = 0;
private $_trace;
/**
* Supported signatures:
* - PEAR_Exception(string $message);
* - PEAR_Exception(string $message, int $code);
* - PEAR_Exception(string $message, Exception $cause);
* - PEAR_Exception(string $message, Exception $cause, int $code);
* - PEAR_Exception(string $message, PEAR_Error $cause);
* - PEAR_Exception(string $message, PEAR_Error $cause, int $code);
* - PEAR_Exception(string $message, array $causes);
* - PEAR_Exception(string $message, array $causes, int $code);
* @param string exception message
* @param int|Exception|PEAR_Error|array|null exception cause
* @param int|null exception code or null
*/
public function __construct($message, $p2 = null, $p3 = null)
{
if (is_int($p2)) {
$code = $p2;
$this->cause = null;
} elseif (is_object($p2) || is_array($p2)) {
// using is_object allows both Exception and PEAR_Error
if (is_object($p2) && !($p2 instanceof Exception)) {
if (!class_exists('PEAR_Error') || !($p2 instanceof PEAR_Error)) {
throw new PEAR_Exception('exception cause must be Exception, ' .
'array, or PEAR_Error');
}
}
$code = $p3;
if (is_array($p2) && isset($p2['message'])) {
// fix potential problem of passing in a single warning
$p2 = array($p2);
}
$this->cause = $p2;
} else {
$code = null;
$this->cause = null;
}
parent::__construct($message, $code);
$this->signal();
}
/**
* @param mixed $callback - A valid php callback, see php func is_callable()
* - A PEAR_Exception::OBSERVER_* constant
* - An array(const PEAR_Exception::OBSERVER_*,
* mixed $options)
* @param string $label The name of the observer. Use this if you want
* to remove it later with removeObserver()
*/
public static function addObserver($callback, $label = 'default')
{
self::$_observers[$label] = $callback;
}
public static function removeObserver($label = 'default')
{
unset(self::$_observers[$label]);
}
/**
* @return int unique identifier for an observer
*/
public static function getUniqueId()
{
return self::$_uniqueid++;
}
private function signal()
{
foreach (self::$_observers as $func) {
if (is_callable($func)) {
call_user_func($func, $this);
continue;
}
settype($func, 'array');
switch ($func[0]) {
case self::OBSERVER_PRINT :
$f = (isset($func[1])) ? $func[1] : '%s';
printf($f, $this->getMessage());
break;
case self::OBSERVER_TRIGGER :
$f = (isset($func[1])) ? $func[1] : E_USER_NOTICE;
trigger_error($this->getMessage(), $f);
break;
case self::OBSERVER_DIE :
$f = (isset($func[1])) ? $func[1] : '%s';
die(printf($f, $this->getMessage()));
break;
default:
trigger_error('invalid observer type', E_USER_WARNING);
}
}
}
/**
* Return specific error information that can be used for more detailed
* error messages or translation.
*
* This method may be overridden in child exception classes in order
* to add functionality not present in PEAR_Exception and is a placeholder
* to define API
*
* The returned array must be an associative array of parameter => value like so:
* <pre>
* array('name' => $name, 'context' => array(...))
* </pre>
* @return array
*/
public function getErrorData()
{
return array();
}
/**
* Returns the exception that caused this exception to be thrown
* @access public
* @return Exception|array The context of the exception
*/
public function getCause()
{
return $this->cause;
}
/**
* Function must be public to call on caused exceptions
* @param array
*/
public function getCauseMessage(&$causes)
{
$trace = $this->getTraceSafe();
$cause = array('class' => get_class($this),
'message' => $this->message,
'file' => 'unknown',
'line' => 'unknown');
if (isset($trace[0])) {
if (isset($trace[0]['file'])) {
$cause['file'] = $trace[0]['file'];
$cause['line'] = $trace[0]['line'];
}
}
$causes[] = $cause;
if ($this->cause instanceof PEAR_Exception) {
$this->cause->getCauseMessage($causes);
} elseif ($this->cause instanceof Exception) {
$causes[] = array('class' => get_class($this->cause),
'message' => $this->cause->getMessage(),
'file' => $this->cause->getFile(),
'line' => $this->cause->getLine());
} elseif (class_exists('PEAR_Error') && $this->cause instanceof PEAR_Error) {
$causes[] = array('class' => get_class($this->cause),
'message' => $this->cause->getMessage(),
'file' => 'unknown',
'line' => 'unknown');
} elseif (is_array($this->cause)) {
foreach ($this->cause as $cause) {
if ($cause instanceof PEAR_Exception) {
$cause->getCauseMessage($causes);
} elseif ($cause instanceof Exception) {
$causes[] = array('class' => get_class($cause),
'message' => $cause->getMessage(),
'file' => $cause->getFile(),
'line' => $cause->getLine());
} elseif (class_exists('PEAR_Error') && $cause instanceof PEAR_Error) {
$causes[] = array('class' => get_class($cause),
'message' => $cause->getMessage(),
'file' => 'unknown',
'line' => 'unknown');
} elseif (is_array($cause) && isset($cause['message'])) {
// PEAR_ErrorStack warning
$causes[] = array(
'class' => $cause['package'],
'message' => $cause['message'],
'file' => isset($cause['context']['file']) ?
$cause['context']['file'] :
'unknown',
'line' => isset($cause['context']['line']) ?
$cause['context']['line'] :
'unknown',
);
}
}
}
}
public function getTraceSafe()
{
if (!isset($this->_trace)) {
$this->_trace = $this->getTrace();
if (empty($this->_trace)) {
$backtrace = debug_backtrace();
$this->_trace = array($backtrace[count($backtrace)-1]);
}
}
return $this->_trace;
}
public function getErrorClass()
{
$trace = $this->getTraceSafe();
return $trace[0]['class'];
}
public function getErrorMethod()
{
$trace = $this->getTraceSafe();
return $trace[0]['function'];
}
public function __toString()
{
if (isset($_SERVER['REQUEST_URI'])) {
return $this->toHtml();
}
return $this->toText();
}
public function toHtml()
{
$trace = $this->getTraceSafe();
$causes = array();
$this->getCauseMessage($causes);
$html = '<table style="border: 1px" cellspacing="0">' . "\n";
foreach ($causes as $i => $cause) {
$html .= '<tr><td colspan="3" style="background: #ff9999">'
. str_repeat('-', $i) . ' <b>' . $cause['class'] . '</b>: '
. htmlspecialchars($cause['message']) . ' in <b>' . $cause['file'] . '</b> '
. 'on line <b>' . $cause['line'] . '</b>'
. "</td></tr>\n";
}
$html .= '<tr><td colspan="3" style="background-color: #aaaaaa; text-align: center; font-weight: bold;">Exception trace</td></tr>' . "\n"
. '<tr><td style="text-align: center; background: #cccccc; width:20px; font-weight: bold;">#</td>'
. '<td style="text-align: center; background: #cccccc; font-weight: bold;">Function</td>'
. '<td style="text-align: center; background: #cccccc; font-weight: bold;">Location</td></tr>' . "\n";
foreach ($trace as $k => $v) {
$html .= '<tr><td style="text-align: center;">' . $k . '</td>'
. '<td>';
if (!empty($v['class'])) {
$html .= $v['class'] . $v['type'];
}
$html .= $v['function'];
$args = array();
if (!empty($v['args'])) {
foreach ($v['args'] as $arg) {
if (is_null($arg)) $args[] = 'null';
elseif (is_array($arg)) $args[] = 'Array';
elseif (is_object($arg)) $args[] = 'Object('.get_class($arg).')';
elseif (is_bool($arg)) $args[] = $arg ? 'true' : 'false';
elseif (is_int($arg) || is_double($arg)) $args[] = $arg;
else {
$arg = (string)$arg;
$str = htmlspecialchars(substr($arg, 0, 16));
if (strlen($arg) > 16) $str .= '&hellip;';
$args[] = "'" . $str . "'";
}
}
}
$html .= '(' . implode(', ',$args) . ')'
. '</td>'
. '<td>' . (isset($v['file']) ? $v['file'] : 'unknown')
. ':' . (isset($v['line']) ? $v['line'] : 'unknown')
. '</td></tr>' . "\n";
}
$html .= '<tr><td style="text-align: center;">' . ($k+1) . '</td>'
. '<td>{main}</td>'
. '<td>&nbsp;</td></tr>' . "\n"
. '</table>';
return $html;
}
public function toText()
{
$causes = array();
$this->getCauseMessage($causes);
$causeMsg = '';
foreach ($causes as $i => $cause) {
$causeMsg .= str_repeat(' ', $i) . $cause['class'] . ': '
. $cause['message'] . ' in ' . $cause['file']
. ' on line ' . $cause['line'] . "\n";
}
return $causeMsg . $this->getTraceAsString();
}
}

View File

@ -50,6 +50,20 @@ foreach ($configFile as $line) {
} }
// Class list global array
//***********************
$dirroot= ALTERNC_PANEL;
$classes=array();
global $classes;
/* CLASSES PHP : automatic include : */
foreach ( glob( $dirroot."/class/m_*.php") as $di ) {
if (preg_match("#${dirroot}/class/m_(.*)\\.php$#",$di,$match)) { // $
$classes[]=$match[1];
}
}
// Constants and globals // Constants and globals
// ******************** // ********************
@ -151,6 +165,16 @@ foreach ($queryList as $exec_command) {
} }
echo "*** In progress: mysql.sql imported\n"; echo "*** In progress: mysql.sql imported\n";
global $db;
global $cuid;
global $variables;
global $err;
global $mem;
global $admin;
global $mysql;
global $ftp;
global $quota;
global $db;
$db = new \DB_system($user,$database,$password); $db = new \DB_system($user,$database,$password);
$db->connect(); $db->connect();
$cuid = 0; $cuid = 0;
@ -160,3 +184,7 @@ $err = new \m_err();
$authip = new \m_authip(); $authip = new \m_authip();
$hooks = new \m_hooks(); $hooks = new \m_hooks();
$bro = new \m_bro(); $bro = new \m_bro();
$admin = new \m_admin();
$mysql = new \m_mysql();
$ftp = new \m_ftp();
$quota = new \m_quota();

View File

@ -39,7 +39,7 @@ abstract class AlterncTest extends PHPUnit_Extensions_Database_TestCase
$datasetList[] = $dataSet; $datasetList[] = $dataSet;
} }
$compositeDataSet = new PHPUnit_Extensions_Database_DataSet_CompositeDataSet($datasetList); $compositeDataSet = new PHPUnit_Extensions_Database_DataSet_CompositeDataSet($datasetList);
return $dataSet; return $compositeDataSet;
} }

View File

@ -0,0 +1,8 @@
db_servers:
-
id: 1
name: Default
host: 127.0.0.1
login: sysusr
password: Z4SYPRiCDQ
client: %

View File

@ -0,0 +1,65 @@
quotas:
-
uid : 2000
name : cron
total : 0
-
uid: 2000
name: dom
total: 1
-
uid: 2000
name: ftp
total: 2
-
uid: 2000
name: mail
total: 10
-
uid: 2000
name: mysql
total: 1
-
uid: 2000
name: piwik
total: 0
-
uid: 2000
name: stats
total: 1
-
uid : 2000
name : web
total : 51200
uid : 2001
name : cron
total : 0
-
uid: 2001
name: dom
total: 1
-
uid: 2001
name: ftp
total: 2
-
uid: 2001
name: mail
total: 10
-
uid: 2001
name: mysql
total: 1
-
uid: 2001
name: piwik
total: 0
-
uid: 2001
name: stats
total: 1
-
uid : 2001
name : web
total : 51200

View File

@ -1,11 +1,21 @@
domaines: domaines:
- -
id : 1 id : 1
compte : 2001 compte : 2000
domaine : example.tld domaine : admin.tld
gesdns : 1 gesdns : 1
gesmx : 1 gesmx : 1
noerase : 0 noerase : 0
dns_action : OK dns_action : OK
dns_result : 0 dns_result : 0
zonettl : 86400 zonettl : 3600
-
id : 2
compte : 2001
domaine : domain1.tld
gesdns : 1
gesmx : 1
noerase : 0
dns_action : OK
dns_result : 0
zonettl : 3600

View File

@ -0,0 +1 @@
ftpusers:

View File

@ -9,6 +9,7 @@ membres:
show_help : 0 show_help : 0
lastlogin : 2014-01-01 00:00:00 lastlogin : 2014-01-01 00:00:00
lastfail : 0 lastfail : 0
db_server_id: 1
lastip : 127.0.0.1 lastip : 127.0.0.1
- -
uid : 2001 uid : 2001
@ -17,6 +18,7 @@ membres:
enabled : 1 enabled : 1
su : 0 su : 0
mail : phpunit@alternc.org mail : phpunit@alternc.org
db_server_id: 1
show_help : 1 show_help : 1
lastlogin : 2014-01-01 00:00:00 lastlogin : 2014-01-01 00:00:00
lastfail : 0 lastfail : 0

View File

@ -0,0 +1,13 @@
policy:
-
name : ftp
minsize : 0
maxsize : 66
classcount : 0
allowlogin : 0
-
name : mem
minsize : 0
maxsize : 64
classcount : 0
allowlogin: 0

View File

@ -2,7 +2,7 @@
/** /**
* Generated by PHPUnit_SkeletonGenerator 1.2.1 on 2014-03-13 at 15:55:58. * Generated by PHPUnit_SkeletonGenerator 1.2.1 on 2014-03-13 at 15:55:58.
*/ */
class m_ftpTest extends PHPUnit_Framework_TestCase class m_ftpTest extends AlterncTest
{ {
/** /**
* @var m_ftp * @var m_ftp
@ -19,6 +19,21 @@ class m_ftpTest extends PHPUnit_Framework_TestCase
$this->object = new m_ftp; $this->object = new m_ftp;
} }
/**
* @return PHPUnit_Extensions_Database_DataSet_IDataSet
*/
public function getDataSet()
{ $t=array("1" => "ftp/ftp.yml",
"2" => "membres.yml",
"3" => "domaines.yml",
"3" => "policy.yml",
"4" => "default-quota.yml",
"5" => "db_servers.yml"
);
return parent::loadDataSet($t);
}
/** /**
* Tears down the fixture, for example, closes a network connection. * Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed. * This method is called after a test is executed.
@ -165,16 +180,62 @@ class m_ftpTest extends PHPUnit_Framework_TestCase
/** /**
* @covers m_ftp::add_ftp * @covers m_ftp::add_ftp
* @todo Implement testAdd_ftp().
*/ */
public function testAdd_ftp() public function testAdd_ftp_prefix_ok()
{ {
// Remove the following lines when you implement this test. global $db,$mysql,$cuid,$mem,$admin ;
$this->markTestIncomplete( // we go super-admin
'This test has not been implemented yet.' $admin->enabled=1;
); $mem->su("2001");
$queryTable = $this->getConnection()->createQueryTable('domain', 'SELECT * FROM db_servers');
$row_count = $queryTable->getRowCount();
#first ftp account
$result=$this->object->add_ftp("phpunit","","123456","/");
$this->assertTrue($result);
#first ftp account again ( should fail )
$result=$this->object->add_ftp("phpunit","","123456","/");
$this->assertFalse($result);
#ftp account with suffix
$result=$this->object->add_ftp("phpunit","new","123456","/");
$this->assertTrue($result);
#ftp account with suffix again should fail
$result=$this->object->add_ftp("phpunit","new","123456","/");
$this->assertFalse($result);
#ftp account with domain prefix ok
$result=$this->object->add_ftp("domain1.tld","","123456","/");
$this->assertFalse($result);
#ftp account with domain prefix again : should fail
$result=$this->object->add_ftp("domain1.tld","","123456","/");
$this->assertFalse($result);
} }
/**
* @covers m_ftp::add_ftp
*/
public function testAdd_ftp_prefix_not_ok()
{
global $db,$mysql,$cuid,$mem,$admin ;
// we go super-admin
$admin->enabled=1;
$mem->su("2001");
#test with a prefix that is not the user's login
$result=$this->object->add_ftp("phpunity","","123456","/");
$this->assertFalse($result);
#test with a prefix that is not a domain associated to the specified user
$result=$this->object->add_ftp("admin.ltd","","123456","/");
$this->assertFalse($result);
}
/** /**
* @covers m_ftp::is_ftp * @covers m_ftp::is_ftp
* @todo Implement testIs_ftp(). * @todo Implement testIs_ftp().

79
src/cron_users_doit.sh Executable file
View File

@ -0,0 +1,79 @@
#!/bin/bash
# FIXME relecture + commentaires
id=$1
url=$2
email=$3
schedule=$4
now=$5
user=$6
password=$7
timeout=3600
for CONFIG_FILE in \
/etc/alternc/local.sh \
/usr/lib/alternc/functions.sh
do
if [ ! -r "$CONFIG_FILE" ]; then
echo "Can't access $CONFIG_FILE."
exit 1
fi
. "$CONFIG_FILE"
done
if [ "x$url" == "x" ] ; then
echo Missing arguments
exit 0
fi
urldecode() {
arg="$1"
i="0"
(
while [ "$i" -lt ${#arg} ]; do
c0=${arg:$i:1}
if [ "x$c0" = "x%" ]; then
c1=${arg:$((i+1)):1}
c2=${arg:$((i+2)):1}
printf "\x$c1$c2"
i=$((i+3))
else
echo -n "$c0"
i=$((i+1))
fi
done
) | sed -e 's/"/\\"/g' -e 's/\!/\\\!/g' -e 's/\ /\\\ /g' -e "s/'/\\'/g"
}
tmpfile=$(mktemp /tmp/altern-cron-id$id-$$.XXX)
# Don't really understand why it must be called this way...
(
echo -e "Here the report for the scheduled task for the cron #$id in your AlternC configuration (from http://$FQDN)\n\n"
echo -e "\n---------- BEGIN ----------"
bash -c "wget --tries=1 -O - --no-check-certificate --http-user=$(urldecode $user) --http-password=$(urldecode $password) \"$(urldecode $url)\" --timeout=$timeout 2>&1"
echo -e "\n---------- END ----------"
) > "$tmpfile"
# If there is an email specified, mail it
if [ ! "x$email" == "x" -a ! "$email" == "null" ] ; then
date=$(date +%x\ %X)
mailx -s "AlternC Cron #$id - Report $date" -a "From: noreply@$FQDN" "$(urldecode $email)" < "$tmpfile"
fi
rm -f "$tmpfile"
# On calcule l'heure de la prochaine execution idéale
((interval=$schedule * 60))
((next=$(( $(( $now / $interval)) + 1 )) * $interval ))
# On check pour pas avoir d'injection SQL
if [[ ! "$id" =~ ^[0-9]+$ || ! "$next" =~ ^[0-9]+$ ]] ; then
echo "Id +$id+ or time +$next+ is incorrect."
return 2
fi
$MYSQL_DO "update cron set next_execution = FROM_UNIXTIME($next) where id = $id;"

233
src/diagnostic.php Normal file
View File

@ -0,0 +1,233 @@
#!/usr/bin/php -q
<?php
/*
$Id: diagnostic.php 2014/05/19 alban Exp $
----------------------------------------------------------------------
AlternC - Web Hosting System
Copyright (C) 2002 by the AlternC Development Team.
http://alternc.org/
----------------------------------------------------------------------
Based on:
Valentin Lacambre's web hosting softwares: http://altern.org/
----------------------------------------------------------------------
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
To read the license please visit http://www.gnu.org/copyleft/gpl.html
----------------------------------------------------------------------
Original Author of file: alban
Purpose of file: Provide a diagnostic of the server state
----------------------------------------------------------------------
*/
/*
Handles diagnostics of an alternc server.
Notes
The diagnostic files are located by default in /var/lib/alternc/diagnostics
*/
/**
* Attempts to load a class in multiple path, the PSR-0 or old style way
*
* @staticvar array $srcPathList
* @staticvar boolean $init
* @param string $class_name
* @return boolean
*/
function __autoload($class_name)
{
// Contains (Namespace) => directory
static $srcPathList = array();
static $init;
// Attempts to set include path and directories once
if( is_null( $init )){
// Sets init flag
$init = true;
// Sets a contextual directory
$srcPathList["standard"] = __DIR__."/../lib";
// Updates include_path according to this list
$includePathList = explode(PATH_SEPARATOR, get_include_path());
foreach($srcPathList as $path){
if ( !in_array($path, $includePathList)){
$includePathList[] = $path;
}
}
// Reverses the path for search efficiency
$finalIncludePathList = array_reverse($includePathList);
// Sets the updated include_path
set_include_path(implode(PATH_SEPARATOR, $finalIncludePathList));
}
// Accepts old Foo_Bar namespacing
if(preg_match("/_/", $class_name)){
$file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name) . '.php';
// Accepts 5.3 Foo\Bar PSR-0 namespacing
} else if(preg_match("/\\/", $class_name)){
$file_name = str_replace('\\', DIRECTORY_SEPARATOR, ltrim($class_name,'\\')) . '.php';
// Accepts non namespaced classes
} else {
$file_name = $class_name . '.php';
}
// Attempts to find file in namespace
foreach($srcPathList as $namespace => $path ){
$file_path = $path.DIRECTORY_SEPARATOR.$file_name;
if(is_file($file_path) && is_readable($file_path)){
require $file_path;
return true;
}
}
// Failed to find file
return false;
}
// ==================================================================
// ==================================================================
// alternc config
// ==================================================================
// ==================================================================
$version = "3.2";
// alternc 1.0
if(is_file("/usr/share/alternc/panel/class/config_nochk.php")){
require_once("/usr/share/alternc/panel/class/config_nochk.php");
}else{
$version = "1.0";
require_once("/var/alternc/bureau/class/config_nochk.php");
include "../bureau/class/class_system_bind.php";
}
$directoryInstance = new Alternc_Diagnostic_Directory("/var/log/alternc/diagnostic");
// instanciation of the diagnosticManager service
$diagnosticManager = new Alternc_Diagnostic_Manager( array(
"directoryInstance" => $directoryInstance,
"formatInstance" => new Alternc_Diagnostic_Format_Json($directoryInstance),
"version" => $version
));
// ==================================================================
// ==================================================================
// Console parser configuration
// ==================================================================
// ==================================================================
$consoleParser = new Alternc_Diagnostic_Console();
$createCommmand = $consoleParser->addCommand('create', array('multiple'=>true,"alias"=>"c","description" => "Creates a new diagnostic"));
$createCommmand->addOption('services', array(
'short_name' => '-s',
'long_name' => '--services',
'action' => 'StoreString',
'default' => 'apache2,dns,mail,system,mailman,mysql,panel,ftp',
'description' => 'Sets the services to use for diagnostics separated by comma
ex: -d apache2,dns,mail',
'help_name' => 'services'
));
$createCommmand->addOption('format', array(
'short_name' => '-f',
'long_name' => '--format',
'action' => 'StoreString',
'default' => 'json',
'description' => 'Sets the format of the diagnostic file : json (default)',
'help_name' => 'format'
));
$listCommmand = $consoleParser->addCommand('list', array('multiple'=>false,"alias"=>"i","description" => "Shows all available diagnostics"));
$diffCommmand = $consoleParser->addCommand('diff', array('multiple'=>false,"alias"=>"x","description" => "Removes one or more diagnotics"));
$diffCommmand->addOption('source', array(
'short_name' => '-s',
'long_name' => '--source',
'action' => 'StoreString',
'default' => '0',
'description' => 'First file to diff, id or basename. Default: 0',
'help_name' => 'source'
));
$diffCommmand->addOption('target', array(
'short_name' => '-t',
'long_name' => '--target',
'action' => 'StoreString',
'default' => '1',
'description' => 'First file to diff, id or basename. Default: 1',
'help_name' => 'target'
));
$diffCommmand->addOption('format', array(
'short_name' => '-f',
'long_name' => '--format',
'action' => 'StoreString',
'default' => 'txt',
'description' => 'Sets the format of the diagnostic diff. default: txt',
'help_name' => 'format'
));
$showCommand = $consoleParser->addCommand('show', array('multiple'=>false,"alias"=>"s","description" => "Prints a diagnotic content"));
$showCommand->addOption('id', array(
'short_name' => '-i',
'long_name' => '--id',
'action' => 'StoreString',
'default' => '0',
'description' => 'Provides the id or name of a diagnostic to show. Default: 0',
'help_name' => 'id'
));
$showCommand->addOption('format', array(
'short_name' => '-f',
'long_name' => '--format',
'action' => 'StoreString',
'default' => 'txt',
'description' => 'Sets the format of the output. Default: txt. Other choices : array',
'help_name' => 'format'
));
$deleteCommmand = $consoleParser->addCommand('delete', array('multiple'=>false,"alias"=>"d","description" => "Deletes diagnostic files"));
// Attempts to parse command line
try {
$result = $consoleParser->parse();
if ($result->command_name){
$command_name = "c_".$result->command_name;
$command = $result->command;
}else{
throw new \Exception("Welcome to AlternC Diagnostics! Use -h to learn about available commands.");
}
if( !method_exists($diagnosticManager, $command_name)){
throw new \Exception("Invalid command : $command");
}
$result = $diagnosticManager->$command_name($command);
} catch (\Exception $exc) {
$consoleParser->displayError($exc->getMessage());
}

View File

@ -85,12 +85,8 @@ function d($mess){
*/ */
function mail_it(){ function mail_it(){
global $errorsList,$L_FQDN; global $errorsList,$L_FQDN;
// Forces array
if( !is_array($errorsList)){
$errorsList = array($errorsList);
}
// Builds message from array // Builds message from array
$msg = implode("\n", $errorsList); $msg = var_export($errorsList, TRUE);
// Attempts to send email // Attempts to send email
// @todo log if fails // @todo log if fails
mail("alterncpanel@$L_FQDN",'Script do_actions.php issues',"\n Errors reporting mail:\n\n$msg"); mail("alterncpanel@$L_FQDN",'Script do_actions.php issues',"\n Errors reporting mail:\n\n$msg");
@ -259,14 +255,9 @@ while ($rr=$action->get_action()){
} }
break; break;
default : default :
$output=array("Fail: Sorry dude, i do not know this type of action"); $errorsList[]=array("Fail: Sorry, i do not know this type of action: ". $r['type']);
break; break;
} }
// Get the error (if exists).
if(isset($output[0])){
$return=$output[0];
$errorsList[]="\nAction n°".$r["id"]." '".$r["type"]."' failed! With user: ".$r["user"]."\nHere is the complete output:\n".print_r($output);
}
// We finished the action, notify the DB. // We finished the action, notify the DB.
d("Finishing... return value is : $return\n"); d("Finishing... return value is : $return\n");
if(!$action->finish($r["id"],addslashes($return))){ if(!$action->finish($r["id"],addslashes($return))){

View File

@ -126,15 +126,15 @@ doone() {
# Set the file readable only for the AlternC User # Set the file readable only for the AlternC User
mkdir -p "$REP" mkdir -p "$REP"
chown -R $GID:$GID "$REP" chown -R $GID:$GID "$REP"
chmod 2770 -R "$REP" chmod 2750 -R "$REP"
# # Delete existings ACL # # Delete existings ACL
# # Set the defaults acl on all the files # # Set the defaults acl on all the files
# setfacl -b -k -n -R -m d:g:alterncpanel:rwx -m d:u::rwx -m d:g::rwx -m d:u:$GID:rwx -m d:g:$GID:rwx -m d:o::--- -m d:mask:rwx\ # setfacl -b -k -n -R -m d:g:alterncpanel:rwx -m d:u::rwx -m d:g::rwx -m d:u:$GID:rwx -m d:g:$GID:rwx -m d:o::--- -m d:mask:rwx\
# -Rm g:alterncpanel:rwx -m u:$GID:rwx -m g:$GID:rwx -m mask:rwx\ # -Rm g:alterncpanel:rwx -m u:$GID:rwx -m g:$GID:rwx -m mask:rwx\
# "$REP" # "$REP"
setfacl -bknR -m d:u:alterncpanel:rwx -m d:g:alterncpanel:rwx -m u:alterncpanel:rwx -m g:alterncpanel:rwx -m d:o::--- -m o::---\ setfacl -bknR -m d:u:alterncpanel:rwx -m d:g:alterncpanel:r-x -m u:alterncpanel:rwx -m g:alterncpanel:r-x -m d:o::--- -m o::---\
-m d:u:$GID:rwx -m d:g:$GID:rwx -m u:$GID:rwx -m g:$GID:rwx -m d:mask:rwx -m mask:rwx "$REP" -m d:u:$GID:rwx -m d:g:$GID:r-x -m u:$GID:rwx -m g:$GID:r-x -m d:mask:rwx -m mask:rwx "$REP"
fixtmp $GID fixtmp $GID
read GID LOGIN || true read GID LOGIN || true

View File

@ -42,10 +42,10 @@ dns_get_zonettl() {
) )
# default value # default value
if [ "$zonettl" == "" ] ; then if [ "$zonettl" == "" ] ; then
zonettl="86400" zonettl="3600"
fi fi
if [ "$zonettl" -eq "0" ] ; then if [ "$zonettl" -eq "0" ] ; then
zonettl="86400" zonettl="3600"
fi fi
echo $zonettl echo $zonettl
} }

View File

@ -6,7 +6,7 @@ TEMPLATE_DIR="/etc/alternc/templates/apache2"
HOSTING_DIR="/etc/alternc/functions_hosting" HOSTING_DIR="/etc/alternc/functions_hosting"
HTML_HOME="$ALTERNC_HTML" HTML_HOME="$ALTERNC_HTML"
VHOST_DIR="/var/lib/alternc/apache-vhost" VHOST_DIR="/var/lib/alternc/apache-vhost/"
launch_hooks() { launch_hooks() {
local ACTION=$1 local ACTION=$1

View File

@ -76,6 +76,12 @@ foreach ( $todo as $taction=>$tlist){
} }
} }
/**
* This function is used to delete a domain from the database
* after all it's sub domains were deleted.
**/
$dom->domain_delete();
// Hooks ! // Hooks !
foreach (array('DELETE', 'CREATE', 'UPDATE', 'ENABLE', 'DISABLE') as $y) { foreach (array('DELETE', 'CREATE', 'UPDATE', 'ENABLE', 'DISABLE') as $y) {
if (!isset($todo[$y]) || empty($todo[$y])) continue; if (!isset($todo[$y]) || empty($todo[$y])) continue;

View File

@ -19,7 +19,7 @@ global $cuid;
// those will be tried in order, the first one to return more than 7 // those will be tried in order, the first one to return more than 7
// chars will win // chars will win
$generators = array('pwqgen', 'pwgen'); $generators = array('pwqgen', 'pwgen');
$dryrun = false; $dryrun = true;
// 1GB default quota // 1GB default quota
$default_quotas = 1024; // in MB because using bytes would be too $default_quotas = 1024; // in MB because using bytes would be too
// precise (try to guess AlternC, just you try) // precise (try to guess AlternC, just you try)

View File

@ -15,7 +15,10 @@ if [ ! -r "$ALTERNC_CONFIG_FILE" ]; then
fi fi
. "$ALTERNC_CONFIG_FILE" . "$ALTERNC_CONFIG_FILE"
mysql_query "update address a, domaines d, mailbox m set m.lastlogin=now() where a.domain_id=d.id and m.address_id=a.id and concat_ws('@',a.address,d.domaine) = '$USER';" addr=$(echo $USER | sed 's/@.*//')
dom=$(echo $USER | sed 's/^.*@//')
mysql_query "update address a, domaines d, mailbox m set m.lastlogin=now() where a.domain_id=d.id and m.address_id=a.id and a.address='$addr' and d.domaine='$dom';"
# Now launch the expected binary server # Now launch the expected binary server
exec "$@" exec "$@"

View File

@ -114,7 +114,7 @@ do
mysql_query "delete from sub_domaines where domaine='$dom'; delete from domaines where domaine='$dom';" mysql_query "delete from sub_domaines where domaine='$dom'; delete from domaines where domaine='$dom';"
done done
if [ ! -z "$(cat "$RELOAD_WEB")" ] ; then if [ ! -z "$(cat "$RELOAD_WEB")" ] || [ "$1" = "force" ]; then
# Just to encourage user to use THIS directory and not another one # Just to encourage user to use THIS directory and not another one
test -d "$VHOST_MANUALCONF" || mkdir -p "$VHOST_MANUALCONF" test -d "$VHOST_MANUALCONF" || mkdir -p "$VHOST_MANUALCONF"
@ -132,7 +132,7 @@ if [ ! -z "$(cat "$RELOAD_WEB")" ] ; then
else else
echo "Include \"$LOGFORMAT_FILE\"" echo "Include \"$LOGFORMAT_FILE\""
fi fi
find "$VHOST_DIR" -mindepth 2 -type f -iname "*.conf" -print0 | xargs -0 cat find "$VHOST_DIR/" -mindepth 2 -type f -iname "*.conf" -print0 | xargs -0 cat
echo "###END OF ALTERNC AUTO-GENERATED FILE - DO NOT EDIT MANUALLY###" echo "###END OF ALTERNC AUTO-GENERATED FILE - DO NOT EDIT MANUALLY###"
) > "$tempo" ) > "$tempo"

View File

@ -4,9 +4,9 @@
#You can call this script either without arguments, inwich case each maildir quotas will be recalculated #You can call this script either without arguments, inwich case each maildir quotas will be recalculated
#or you can call it with a directory reffering to a maildir to just sync one mailbox #or you can call it with a directory reffering to a maildir to just sync one mailbox
function showhelp() { function panic() {
echo "FIXME: some help" echo "$1" >&2
exit exit 1
} }
# FIXME: storing THAT amount of data in MAILDIRS (on BIG install like Lautre.net) may crash the shell? # FIXME: storing THAT amount of data in MAILDIRS (on BIG install like Lautre.net) may crash the shell?
@ -16,70 +16,55 @@ while getopts "am:d:c:" optname
do do
case "$optname" in case "$optname" in
"a") "a")
# All mails # All mails
maildirs=$(mysql_query "select userdb_home from dovecot_view order by 1") maildirs=$(mysql_query "select path from mailbox")
;; ;;
"m") "m")
# An email # An email
if [[ "$OPTARG" =~ ^[^\@]*@[^\@]*$ ]] ; then if [[ ! "$OPTARG" =~ ^[^\@]*@[^\@]*$ ]] ; then
if [[ "$(mysql_query "select userdb_home from dovecot_view where user = '$OPTARG'")" ]]; then panic "bad mail address provided"
maildirs=$(mysql_query "select userdb_home from dovecot_view where user = '$OPTARG' order by 1")
else
echo "Bad mail provided"
showhelp
fi fi
else if [[ ! "$(mysql_query "select userdb_home from dovecot_view where user = '$OPTARG'")" ]]; then
echo "Bad mail provided" panic "non existant mail address"
showhelp
fi fi
maildirs=$(mysql_query "select userdb_home from dovecot_view where user = '$OPTARG'")
;; ;;
"d") "d")
# Expecting a domain # Expecting a domain
# Check if domain is well-formed # Check if domain is well-formed
if [[ ! "$OPTARG" =~ ^[a-z\-]+(\.[a-z\-]+)+$ ]] ; then if [[ ! "$OPTARG" =~ ^[a-z0-9\-]+(\.[a-z\-]+)+$ ]] ; then
echo "Bad domain provided" panic "bad domain provided"
showhelp
fi fi
# Attemp to get from database. # Attemp to get from database.
if [[ ! "$(mysql_query "select domaine from domaines where domaine = '$OPTARG'")" ]]; then if [[ ! "$(mysql_query "select domaine from domaines where domaine = '$OPTARG'")" ]]; then
# Seem to be empty # Seem to be empty
echo "Bad domain provided" panic "non existant domain"
showhelp
fi fi
maildirs=$(mysql_query "select userdb_home from dovecot_view where user like '%@$OPTARG' order by 1") maildirs=$(mysql_query "select userdb_home from dovecot_view where user like '%@$OPTARG'")
;; ;;
"c") "c")
# An account # An account
if [[ "$OPTARG" =~ ^[a-z]*$ ]] ; then if [[! "$OPTARG" =~ ^[a-z0-9]*$ ]] ; then
if [[ "$(mysql_query "select domaine from domaines where domaine = '$1'")" ]]; then panic "bad account provided"
maildirs=$(mysql_query "select userdb_home from dovecot_view where userdb_uid = $OPTARG order by 1")
else
echo "Bad account provided"
showhelp
fi fi
else if [[! "$(mysql_query "select domaine from domaines where domaine = '$1'")" ]]; then
echo "Bad account provided" panic "non existant account"
showhelp
fi fi
maildirs=$(mysql_query "select userdb_home from dovecot_view where userdb_uid = $OPTARG")
;; ;;
"?") "?")
echo "Unknown option $OPTARG - stop processing" panic "Unknown option $OPTARG - stop processing"
showhelp
exit
;; ;;
":") ":")
echo "No argument value for option $OPTARG - stop processing" panic "No argument value for option $OPTARG - stop processing"
showhelp
exit
;; ;;
*) *)
# Should not occur # Should not occur
echo "Unknown error while processing options" echo
showhelp panic "Unknown error while processing options"
exit
;; ;;
esac esac
done done
@ -96,10 +81,15 @@ for i in $maildirs ; do
continue continue
fi fi
# We grep only mails, not the others files if [ ! -d "$i" ];then
echo "The maildir $i does not exists. It's quota won't be resync"
continue
fi
# We grep only mails, not the others files
mails=`find $i -type f | egrep "(^$i)*[0-9]+\.M"` mails=`find $i -type f | egrep "(^$i)*[0-9]+\.M"`
# This part count the total mailbox size (mails + sieve scripts + ...) # This part count the total mailbox size (mails + sieve scripts + ...)
size=`du -b -s $i|awk '{print $1}'` size=`du -b -s $i|awk '{print $1}'`
mail_count=`echo $mails|wc -w` mail_count=`echo $mails|wc -w`
@ -107,7 +97,7 @@ for i in $maildirs ; do
echo "mail count : "$mail_count echo "mail count : "$mail_count
echo "dir size : "$size echo "dir size : "$size
echo "" echo ""
#update the mailbox table accordingly #update the mailbox table accordingly
mysql_query "UPDATE mailbox SET bytes=$size WHERE path='$i' ; " mysql_query "UPDATE mailbox SET bytes=$size WHERE path='$i' ; "
mysql_query "UPDATE mailbox SET messages=$mail_count WHERE path='$i' ; " mysql_query "UPDATE mailbox SET messages=$mail_count WHERE path='$i' ; "
done done

View File

@ -195,18 +195,22 @@ protocol imap {
} }
service imap { service imap {
executable = imap imap-postlogin # tell imap to do post-login lookup using a socket called "postlogin"
executable = imap postlogin
vsz_limit = 512M vsz_limit = 512M
} }
service imap-postlogin { # The service name below doesn't actually matter.
service postlogin {
# all post-login scripts are executed via script-login binary
executable = script-login /usr/lib/alternc/popimap-log-login.sh executable = script-login /usr/lib/alternc/popimap-log-login.sh
# the script process runs as the user specified here (v2.0.14+): # the script process runs as the user specified here (v2.0.14+):
# user = $default_internal_user #user = $default_internal_user
# this UNIX socket listener must use the same name as given to imap executable # this UNIX socket listener must use the same name as given to imap executable
unix_listener imap-postlogin { unix_listener postlogin {
}
} }
}
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
# 20-managesieve.conf # 20-managesieve.conf
@ -259,7 +263,8 @@ protocol pop3 {
} }
service pop3 { service pop3 {
executable = /usr/lib/alternc/popimap-log-login.sh /usr/lib/dovecot/pop3 # tell imap to do post-login lookup using a socket called "postlogin"
executable = pop3 postlogin
} }
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------