diff --git a/helper_scripts/dns_export_to_bind.php b/helper_scripts/dns_export_to_bind.php index ea5adf94c00b0695a7a5a566114e5d90c7f67911..6a3f59035a5d68810a957fab77e7800220985a8e 100644 --- a/helper_scripts/dns_export_to_bind.php +++ b/helper_scripts/dns_export_to_bind.php @@ -2,103 +2,103 @@ $host="IP_ADDRESS"; $user="USERNAME"; $password="PASSWORD"; -mysql_connect($host,$user,$password) or die(mysql_error()); +mysql_connect($host, $user, $password) or die(mysql_error()); mysql_select_db("dbispconfig"); $result = ""; $result = mysql_query("SELECT id,origin,ns,ttl,mbox,serial,refresh,retry,expire,minimum FROM dns_soa;"); function hostname2ipfunktion($tmp1, $timeout = 1) - { - if ($tmp1 == 0) - { - $query = `nslookup -timeout=$timeout -retry=0 $tmp1`; - if(preg_match('/\nAddress: (.*)\n/', $query, $matches)) - return trim($matches[1]); - return $tmp1; - } - } +{ + if ($tmp1 == 0) + { + $query = `nslookup -timeout=$timeout -retry=0 $tmp1`; + if(preg_match('/\nAddress: (.*)\n/', $query, $matches)) + return trim($matches[1]); + return $tmp1; + } +} $serialsearch=date("Ymd"); $resultx12 = mysql_query("SELECT origin,serial FROM dns_soa WHERE serial LIKE '$serialsearch%' ORDER BY origin ASC;"); while ($rowx12=mysql_fetch_array($resultx12)) { - $zone=substr($rowx12["origin"],0,-1); - $filename_x1="/var/cache/bind/".$zone; - if (file_exists($filename_x1)) { - $serialvergleich[$zone]=exec("grep \";Serial\" /var/cache/bind/$zone |cut -d\" \" -f1 | awk '{print $1}'"); - } + $zone=substr($rowx12["origin"], 0, -1); + $filename_x1="/var/cache/bind/".$zone; + if (file_exists($filename_x1)) { + $serialvergleich[$zone]=exec("grep \";Serial\" /var/cache/bind/$zone |cut -d\" \" -f1 | awk '{print $1}'"); + } } while($row = mysql_fetch_array($result)) - { -### Hier ALLES Aktivieren bei Primary Nameserver TEIL 1 ################################################################################# - $varx11=substr($row["origin"],0,-1); - $filename="/var/cache/bind/".$varx11; - if (file_exists($filename)) { - unlink("/var/cache/bind/$varx11"); - } - $arr1[$x11]="zone \"$varx11\" in { type master; file \"$varx11\"; };\n"; - $x11=$x11+1; - $result2 = mysql_query("select name,type,aux,data from dns_rr where zone=$row[id] and active='Y' ORDER BY name ASC;"); - $arr3[0]="\$TTL ".$row['ttl']."\n@ IN SOA ".$row['ns']." ".$row['mbox']." (\n ".$row['serial']." ;Serial\n"." ".$row['refresh']." ;Refresh\n"." ".$row['retry']." ;Retry\n"." ".$row['expire']." ;Expire\n"." ".$row['minimum']." ) ;Minimum\n\n"; +{ + //## Hier ALLES Aktivieren bei Primary Nameserver TEIL 1 ################################################################################# + $varx11=substr($row["origin"], 0, -1); + $filename="/var/cache/bind/".$varx11; + if (file_exists($filename)) { + unlink("/var/cache/bind/$varx11"); + } + $arr1[$x11]="zone \"$varx11\" in { type master; file \"$varx11\"; };\n"; + $x11=$x11+1; + $result2 = mysql_query("select name,type,aux,data from dns_rr where zone=$row[id] and active='Y' ORDER BY name ASC;"); + $arr3[0]="\$TTL ".$row['ttl']."\n@ IN SOA ".$row['ns']." ".$row['mbox']." (\n ".$row['serial']." ;Serial\n"." ".$row['refresh']." ;Refresh\n"." ".$row['retry']." ;Retry\n"." ".$row['expire']." ;Expire\n"." ".$row['minimum']." ) ;Minimum\n\n"; - $xx1=1; - while($row2 = mysql_fetch_row($result2)) - { - $arr2[$xx1]=$row2['0']." IN ".$row2['1']." "; + $xx1=1; + while($row2 = mysql_fetch_row($result2)) + { + $arr2[$xx1]=$row2['0']." IN ".$row2['1']." "; - if ($row2['2']>0) - { - $arr3[$xx1]=$arr2[$xx1].$row2['2']." ".$row2['3']."\n"; - } - else - { - $arr3[$xx1]=$arr2[$xx1].$row2['3']."\n"; - } - $xx1=$xx1+1; - } - $f = fopen("/var/cache/bind/$varx11", "a+"); - foreach($arr3 as $values) fputs($f, $values); - fclose($f); - $arr2=array(); - $arr3=array(); -### ENDE Primärer Nameserver TEIL 2 ##################################################################################################### + if ($row2['2']>0) + { + $arr3[$xx1]=$arr2[$xx1].$row2['2']." ".$row2['3']."\n"; + } + else + { + $arr3[$xx1]=$arr2[$xx1].$row2['3']."\n"; + } + $xx1=$xx1+1; + } + $f = fopen("/var/cache/bind/$varx11", "a+"); + foreach($arr3 as $values) fputs($f, $values); + fclose($f); + $arr2=array(); + $arr3=array(); + //## ENDE Primärer Nameserver TEIL 2 ##################################################################################################### -### Hier ALLES Aktivieren bei Secondary Nameserver ###################################################################################### -# $tmp1 = substr($row["ns"],0,-1); -# $tmp2 = substr($row["origin"],0,-1); + //## Hier ALLES Aktivieren bei Secondary Nameserver ###################################################################################### + // $tmp1 = substr($row["ns"],0,-1); + // $tmp2 = substr($row["origin"],0,-1); -# if (!isset($dnscache[$tmp1])) $nsip = hostname2ipfunktion($tmp1) ; -# else $nsip=$dnscache[$tmp1] ; + // if (!isset($dnscache[$tmp1])) $nsip = hostname2ipfunktion($tmp1) ; + // else $nsip=$dnscache[$tmp1] ; -# if ($nsip == $tmp1) -# { -# echo "$tmp2 $tmp1 Not a valid Nameserver"; -# echo "\n"; -# } -# else -# { -# $dnscache[$tmp1]=$nsip; -# $arr1[$x11]="zone \"".$tmp2."\" in { type slave; file \"".$tmp2."\"; masters {".$nsip."; }; };\n"; -# $x11=$x11+1; -# } -### ENDE Secondary Nameserver ########################################################################################################### - } + // if ($nsip == $tmp1) + // { + // echo "$tmp2 $tmp1 Not a valid Nameserver"; + // echo "\n"; + // } + // else + // { + // $dnscache[$tmp1]=$nsip; + // $arr1[$x11]="zone \"".$tmp2."\" in { type slave; file \"".$tmp2."\"; masters {".$nsip."; }; };\n"; + // $x11=$x11+1; + // } + //## ENDE Secondary Nameserver ########################################################################################################### +} -unlink ("/etc/bind/named.conf.local"); +unlink("/etc/bind/named.conf.local"); $fx = fopen("/etc/bind/named.conf.local", "a+"); foreach($arr1 as $values) fputs($fx, $values); fclose($fx); system("rndc reconfig >/dev/null 2>&1"); -### ANFANG Primärer Namerserver TEIL 2 ################################################################################################## +//## ANFANG Primärer Namerserver TEIL 2 ################################################################################################## $serialsearch=date("Ymd"); $resultx13 = mysql_query("SELECT origin,serial FROM dns_soa WHERE serial LIKE '$serialsearch%' ORDER BY origin ASC;"); while ($rowx13=mysql_fetch_array($resultx13)) { - $serial_ist=($rowx13["serial"]); - $zone=substr($rowx13["origin"],0,-1); -# echo "zone: ".$zone." ist: ".$serial_ist." vergleich: ".$serialvergleich[$zone]."\n"; - if ($serialvergleich[$zone] != $serial_ist) { - $reload=system("rndc reload $zone >/dev/null 2>&1"); - } + $serial_ist=($rowx13["serial"]); + $zone=substr($rowx13["origin"], 0, -1); + // echo "zone: ".$zone." ist: ".$serial_ist." vergleich: ".$serialvergleich[$zone]."\n"; + if ($serialvergleich[$zone] != $serial_ist) { + $reload=system("rndc reload $zone >/dev/null 2>&1"); + } } -### ENDE Primärer NamerserverTEIL 2 ###################################################################################################### -?> \ No newline at end of file +//## ENDE Primärer NamerserverTEIL 2 ###################################################################################################### +?> diff --git a/helper_scripts/dns_export_to_bind_retrans_daily.php b/helper_scripts/dns_export_to_bind_retrans_daily.php index 39faf14fe6dd55da98aba5cc19d05adbbe6ae451..a571367f690b760703d5dbe3e56bc56480c42378 100644 --- a/helper_scripts/dns_export_to_bind_retrans_daily.php +++ b/helper_scripts/dns_export_to_bind_retrans_daily.php @@ -2,13 +2,13 @@ $host="IP_ADDRESS"; $user="USERNAME"; $password="PASSWORD"; -mysql_connect($host,$user,$password) or die(mysql_error()); +mysql_connect($host, $user, $password) or die(mysql_error()); mysql_select_db("dbispconfig"); $result = ""; $result = mysql_query("SELECT origin FROM dns_soa ORDER BY origin ASC;"); while($row = mysql_fetch_array($result)) { - $zone=substr($row["origin"],0,-1); - system("rndc retransfer ".$zone); + $zone=substr($row["origin"], 0, -1); + system("rndc retransfer ".$zone); } -?> \ No newline at end of file +?> diff --git a/helper_scripts/mydns_to_powerdns_migration.php b/helper_scripts/mydns_to_powerdns_migration.php index 9c6526b972973cb407a03bd533fe05d92bd9ab8b..ffe9e4ae86aa846d4c988990fe370d265d9193fc 100644 --- a/helper_scripts/mydns_to_powerdns_migration.php +++ b/helper_scripts/mydns_to_powerdns_migration.php @@ -2,15 +2,15 @@ $host="localhost"; $user="root"; $password="MYSQL-ROOT-PASSWD"; -mysql_connect($host,$user,$password) or die(mysql_error()); +mysql_connect($host, $user, $password) or die(mysql_error()); mysql_select_db("dbispconfig"); $sql1 = mysql_query("SELECT id, substr(origin,1, LENGTH(origin)-1) AS origin, substr(ns,1, LENGTH(ns)-1) AS ns, substr(mbox,1, LENGTH(mbox)-1) AS mbox,ttl FROM dns_soa order by id asc;"); mysql_select_db("powerdns"); while($row1 = mysql_fetch_array($sql1)) { -mysql_query("INSERT INTO domains (id,name,type,ispconfig_id) values ('$row1[id]','$row1[origin]','NATIVE','$row1[id]');"); -mysql_query("INSERT INTO records (domain_id,name,content,ispconfig_id,type,ttl,prio,change_date) values ('$row1[id]','$row1[origin]','$row1[ns] $row1[mbox] 0','$row1[id]','SOA','$row1[ttl]','0','1260446221');"); + mysql_query("INSERT INTO domains (id,name,type,ispconfig_id) values ('$row1[id]','$row1[origin]','NATIVE','$row1[id]');"); + mysql_query("INSERT INTO records (domain_id,name,content,ispconfig_id,type,ttl,prio,change_date) values ('$row1[id]','$row1[origin]','$row1[ns] $row1[mbox] 0','$row1[id]','SOA','$row1[ttl]','0','1260446221');"); } mysql_select_db("dbispconfig"); @@ -18,44 +18,44 @@ $sql2 = mysql_query("SELECT id,zone,name,data,aux,ttl,type FROM dns_rr order by mysql_select_db("powerdns"); while($row2 = mysql_fetch_array($sql2)) { -if (strlen($row2['name'])) -{ -$file1=substr($row2['data'], -1); -if ($file1==".") -{ -$text = $row2['data']; -$laenge = strlen($row2['data'])-1; -$file2 = substr($text, 0,strlen($text)-1); -} -else -{ -$file2=$row2['data']; -} -mysql_select_db("dbispconfig"); -$sql3 = mysql_query("SELECT substr(origin,1, LENGTH(origin)-1) AS origin FROM dns_soa where id=$row2[zone];"); -$row3 = mysql_fetch_array($sql3); -mysql_select_db("powerdns"); -mysql_query("INSERT INTO records (domain_id,name,content,ispconfig_id,type,ttl,prio,change_date) values ('$row2[zone]','$row2[name].$row3[origin]','$file2','$row2[id]','$row2[type]','$row2[ttl]','$row2[aux]','1260446221');"); -} -else -{ -$file1=substr($row2['data'], -1); -if ($file1==".") -{ -$text = $row2['data']; -$laenge = strlen($row2['data'])-1; -$file2 = substr($text, 0,strlen($text)-1); -} -else -{ -$file2=$row2['data']; -} -mysql_select_db("dbispconfig"); -$sql3 = mysql_query("SELECT substr(origin,1, LENGTH(origin)-1) AS origin FROM dns_soa where id=$row2[zone];"); -$row3 = mysql_fetch_array($sql3); -mysql_select_db("powerdns"); -mysql_query("INSERT INTO records (domain_id,name,content,ispconfig_id,type,ttl,prio,change_date) values ('$row2[zone]','$row3[origin]','$file2','$row2[id]','$row2[type]','$row2[ttl]','$row2[aux]','1260446221');"); -} + if (strlen($row2['name'])) + { + $file1=substr($row2['data'], -1); + if ($file1==".") + { + $text = $row2['data']; + $laenge = strlen($row2['data'])-1; + $file2 = substr($text, 0, strlen($text)-1); + } + else + { + $file2=$row2['data']; + } + mysql_select_db("dbispconfig"); + $sql3 = mysql_query("SELECT substr(origin,1, LENGTH(origin)-1) AS origin FROM dns_soa where id=$row2[zone];"); + $row3 = mysql_fetch_array($sql3); + mysql_select_db("powerdns"); + mysql_query("INSERT INTO records (domain_id,name,content,ispconfig_id,type,ttl,prio,change_date) values ('$row2[zone]','$row2[name].$row3[origin]','$file2','$row2[id]','$row2[type]','$row2[ttl]','$row2[aux]','1260446221');"); + } + else + { + $file1=substr($row2['data'], -1); + if ($file1==".") + { + $text = $row2['data']; + $laenge = strlen($row2['data'])-1; + $file2 = substr($text, 0, strlen($text)-1); + } + else + { + $file2=$row2['data']; + } + mysql_select_db("dbispconfig"); + $sql3 = mysql_query("SELECT substr(origin,1, LENGTH(origin)-1) AS origin FROM dns_soa where id=$row2[zone];"); + $row3 = mysql_fetch_array($sql3); + mysql_select_db("powerdns"); + mysql_query("INSERT INTO records (domain_id,name,content,ispconfig_id,type,ttl,prio,change_date) values ('$row2[zone]','$row3[origin]','$file2','$row2[id]','$row2[type]','$row2[ttl]','$row2[aux]','1260446221');"); + } } mysql_select_db("powerdns"); @@ -63,8 +63,8 @@ $sql4 = mysql_query("SELECT records.id,records.content,records.type,domains.name while($row4 = mysql_fetch_array($sql4)) { -mysql_query("UPDATE records SET content = '$row4[content].$row4[name]' where id='$row4[id]';"); + mysql_query("UPDATE records SET content = '$row4[content].$row4[name]' where id='$row4[id]';"); } -?> \ No newline at end of file +?> diff --git a/helper_scripts/recreate_webalizer_stats.php b/helper_scripts/recreate_webalizer_stats.php index 2663bc26f6abdd33ff8092dd468b51892f672209..fbaef38097d01009ac947755644fbf20f17803c0 100644 --- a/helper_scripts/recreate_webalizer_stats.php +++ b/helper_scripts/recreate_webalizer_stats.php @@ -1,39 +1,39 @@ db->queryAllRecords($sql); foreach($records as $rec) { -$domain = escapeshellcmd($rec["domain"]); -$logdir = escapeshellcmd($rec["document_root"].'/log'); -$statsdir = escapeshellcmd($rec["document_root"].'/web/stats'); -$webalizer = '/usr/bin/webalizer'; - -$webalizer_conf_main = '/etc/webalizer/webalizer.conf'; -$webalizer_conf = escapeshellcmd($rec["document_root"].'/log/webalizer.conf'); -exec("rm -rf $webalizer_conf"); -if(!@is_file($webalizer_conf)) { -exec("cp $webalizer_conf_main $webalizer_conf"); - -setConfigVar($webalizer_conf, 'Incremental', 'yes'); -setConfigVar($webalizer_conf, 'IncrementalName', $logdir.'/webalizer.current'); -setConfigVar($webalizer_conf, 'HistoryName', $logdir.'/webalizer.hist'); -} + $domain = escapeshellcmd($rec["domain"]); + $logdir = escapeshellcmd($rec["document_root"].'/log'); + $statsdir = escapeshellcmd($rec["document_root"].'/web/stats'); + $webalizer = '/usr/bin/webalizer'; + + $webalizer_conf_main = '/etc/webalizer/webalizer.conf'; + $webalizer_conf = escapeshellcmd($rec["document_root"].'/log/webalizer.conf'); + exec("rm -rf $webalizer_conf"); + if(!@is_file($webalizer_conf)) { + exec("cp $webalizer_conf_main $webalizer_conf"); + + setConfigVar($webalizer_conf, 'Incremental', 'yes'); + setConfigVar($webalizer_conf, 'IncrementalName', $logdir.'/webalizer.current'); + setConfigVar($webalizer_conf, 'HistoryName', $logdir.'/webalizer.hist'); + } -if(!@is_dir($statsdir)) mkdir($statsdir); + if(!@is_dir($statsdir)) mkdir($statsdir); -echo "Remove stats dir $statsdir ...\n"; -exec("rm -rf $statsdir/*"); + echo "Remove stats dir $statsdir ...\n"; + exec("rm -rf $statsdir/*"); -echo "Re-Create stats for $domain...\n"; -exec("for logfile in $logdir/*access*; do\n$webalizer -c $webalizer_conf -n $domain -s $domain -r $domain -q -T -p -o $statsdir ".'$logfile'."\ndone"); -echo "done.\n"; + echo "Re-Create stats for $domain...\n"; + exec("for logfile in $logdir/*access*; do\n$webalizer -c $webalizer_conf -n $domain -s $domain -r $domain -q -T -p -o $statsdir ".'$logfile'."\ndone"); + echo "done.\n"; } die("finished.\n"); -?> \ No newline at end of file +?> diff --git a/install/autoupdate.php b/install/autoupdate.php index d89aa75bd65013e09a08f5f84ef59cb760f5c7c6..f9d0e62b2fc3dfaeeebf396560cadcb8246a619a 100644 --- a/install/autoupdate.php +++ b/install/autoupdate.php @@ -41,7 +41,7 @@ error_reporting(E_ALL|E_STRICT); if (!file_exists('autoupdate')) { //** The banner on the command line - echo "\n\n".str_repeat('-',80)."\n"; + echo "\n\n".str_repeat('-', 80)."\n"; echo " _____ ___________ _____ __ _ ____ |_ _/ ___| ___ \ / __ \ / _(_) /__ \ | | \ `--.| |_/ / | / \/ ___ _ __ | |_ _ __ _ _/ / @@ -50,19 +50,19 @@ if (!file_exists('autoupdate')) { \___/\____/\_| \____/\___/|_| |_|_| |_|\__, | \____/ __/ | |___/ "; - echo "\n".str_repeat('-',80)."\n"; + echo "\n".str_repeat('-', 80)."\n"; echo "\n\n>>This script is for internal use only! Please use update.php! \n\n"; exit; } //** Include the library with the basic installer functions -require_once('lib/install.lib.php'); +require_once 'lib/install.lib.php'; //** Include the library with the basic updater functions -require_once('lib/update.lib.php'); +require_once 'lib/update.lib.php'; //** Include the base class of the installer class -require_once('lib/installer_base.lib.php'); +require_once 'lib/installer_base.lib.php'; //** Ensure that current working directory is install directory $cur_dir = getcwd(); @@ -75,16 +75,16 @@ define('ISPC_INSTALL_ROOT', realpath(dirname(__FILE__).'/../')); //** Get distribution identifier $dist = get_distname(); -include_once("/usr/local/ispconfig/server/lib/config.inc.php"); +include_once "/usr/local/ispconfig/server/lib/config.inc.php"; $conf_old = $conf; unset($conf); if($dist['id'] == '') die('Linux distribution or version not recognized.'); //** Include the distribution-specific installer class library and configuration -if(is_file('dist/lib/'.$dist['baseid'].'.lib.php')) include_once('dist/lib/'.$dist['baseid'].'.lib.php'); -include_once('dist/lib/'.$dist['id'].'.lib.php'); -include_once('dist/conf/'.$dist['id'].'.conf.php'); +if(is_file('dist/lib/'.$dist['baseid'].'.lib.php')) include_once 'dist/lib/'.$dist['baseid'].'.lib.php'; +include_once 'dist/lib/'.$dist['id'].'.lib.php'; +include_once 'dist/conf/'.$dist['id'].'.conf.php'; //** Get hostname exec('hostname -f', $tmp_out); @@ -124,22 +124,22 @@ $inst->is_update = true; $inst->find_installed_apps(); //** Initialize the MySQL server connection -include_once('lib/mysql.lib.php'); +include_once 'lib/mysql.lib.php'; //** Database update is a bit brute force and should be rebuild later ;) /* * Try to read the DB-admin settings */ -$clientdb_host = ''; -$clientdb_user = ''; -$clientdb_password = ''; -include_once("/usr/local/ispconfig/server/lib/mysql_clientdb.conf"); +$clientdb_host = ''; +$clientdb_user = ''; +$clientdb_password = ''; +include_once "/usr/local/ispconfig/server/lib/mysql_clientdb.conf"; $conf["mysql"]["admin_user"] = $clientdb_user; $conf["mysql"]["admin_password"] = $clientdb_password; -$clientdb_host = ''; -$clientdb_user = ''; -$clientdb_password = ''; +$clientdb_host = ''; +$clientdb_user = ''; +$clientdb_password = ''; //** There is a error if user for mysql admin_password if empty if( empty($conf["mysql"]["admin_password"]) ) { @@ -147,7 +147,7 @@ if( empty($conf["mysql"]["admin_password"]) ) { } //** Test mysql root connection -if(!@mysql_connect($conf["mysql"]["host"],$conf["mysql"]["admin_user"],$conf["mysql"]["admin_password"])) { +if(!@mysql_connect($conf["mysql"]["host"], $conf["mysql"]["admin_user"], $conf["mysql"]["admin_password"])) { die("internal error - MYSQL-Root passord wrong"); } @@ -157,7 +157,7 @@ if(!@mysql_connect($conf["mysql"]["host"],$conf["mysql"]["admin_user"],$conf["my checkDbHealth(); /* - * Prepare the dump of the database + * Prepare the dump of the database */ prepareDBDump(); @@ -196,7 +196,7 @@ if($conf['services']['mail'] == true) { //** Configure postfix swriteln('Configuring Postfix'); $inst->configure_postfix('dont-create-certs'); - + //** Configure mailman swriteln('Configuring Mailman'); $inst->configure_mailman('update'); @@ -217,7 +217,7 @@ if($conf['services']['mail'] == true) { //** Configure PAM swriteln('Configuring PAM'); $inst->configure_pam(); - + //* Configure courier swriteln('Configuring Courier'); $inst->configure_courier(); @@ -261,7 +261,7 @@ if($conf['services']['web']) { //** Configure Apache swriteln('Configuring Apache'); $inst->configure_apache(); - + //** Configure vlogger swriteln('Configuring vlogger'); $inst->configure_vlogger(); @@ -270,7 +270,7 @@ if($conf['services']['web']) { swriteln('Configuring nginx'); $inst->configure_nginx(); } - + //** Configure apps vhost swriteln('Configuring Apps vhost'); $inst->configure_apps_vhost(); diff --git a/install/dist/conf/centos52.conf.php b/install/dist/conf/centos52.conf.php index 1221a74e6c1e8974f4c15950668c73687a8edd2b..12044d3ce07d36d42e166c961c4939b4d82ba01f 100644 --- a/install/dist/conf/centos52.conf.php +++ b/install/dist/conf/centos52.conf.php @@ -63,14 +63,14 @@ $conf['mysql']['admin_user'] = 'root'; $conf['mysql']['admin_password'] = ''; $conf['mysql']['charset'] = 'utf8'; $conf['mysql']['ispconfig_user'] = 'ispconfig'; -$conf['mysql']['ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['ispconfig_password'] = md5(uniqid(rand())); $conf['mysql']['master_slave_setup'] = 'n'; $conf['mysql']['master_host'] = ''; $conf['mysql']['master_database'] = 'dbispconfig'; $conf['mysql']['master_admin_user'] = 'root'; $conf['mysql']['master_admin_password'] = ''; $conf['mysql']['master_ispconfig_user'] = ''; -$conf['mysql']['master_ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['master_ispconfig_password'] = md5(uniqid(rand())); //* Apache $conf['apache']['installed'] = false; // will be detected automatically during installation diff --git a/install/dist/conf/centos53.conf.php b/install/dist/conf/centos53.conf.php index 1221a74e6c1e8974f4c15950668c73687a8edd2b..12044d3ce07d36d42e166c961c4939b4d82ba01f 100644 --- a/install/dist/conf/centos53.conf.php +++ b/install/dist/conf/centos53.conf.php @@ -63,14 +63,14 @@ $conf['mysql']['admin_user'] = 'root'; $conf['mysql']['admin_password'] = ''; $conf['mysql']['charset'] = 'utf8'; $conf['mysql']['ispconfig_user'] = 'ispconfig'; -$conf['mysql']['ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['ispconfig_password'] = md5(uniqid(rand())); $conf['mysql']['master_slave_setup'] = 'n'; $conf['mysql']['master_host'] = ''; $conf['mysql']['master_database'] = 'dbispconfig'; $conf['mysql']['master_admin_user'] = 'root'; $conf['mysql']['master_admin_password'] = ''; $conf['mysql']['master_ispconfig_user'] = ''; -$conf['mysql']['master_ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['master_ispconfig_password'] = md5(uniqid(rand())); //* Apache $conf['apache']['installed'] = false; // will be detected automatically during installation diff --git a/install/dist/conf/debian40.conf.php b/install/dist/conf/debian40.conf.php index 7bdd238498d554ca780edfdb43875b34b0ff7083..3e9fe350065472b2d0a13613e2ad40ed8961c625 100644 --- a/install/dist/conf/debian40.conf.php +++ b/install/dist/conf/debian40.conf.php @@ -65,14 +65,14 @@ $conf['mysql']['admin_user'] = 'root'; $conf['mysql']['admin_password'] = ''; $conf['mysql']['charset'] = 'utf8'; $conf['mysql']['ispconfig_user'] = 'ispconfig'; -$conf['mysql']['ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['ispconfig_password'] = md5(uniqid(rand())); $conf['mysql']['master_slave_setup'] = 'n'; $conf['mysql']['master_host'] = ''; $conf['mysql']['master_database'] = 'dbispconfig'; $conf['mysql']['master_admin_user'] = 'root'; $conf['mysql']['master_admin_password'] = ''; $conf['mysql']['master_ispconfig_user'] = ''; -$conf['mysql']['master_ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['master_ispconfig_password'] = md5(uniqid(rand())); //* Apache $conf['apache']['installed'] = false; // will be detected automatically during installation diff --git a/install/dist/conf/debian60.conf.php b/install/dist/conf/debian60.conf.php index 8eb3a2ca3ae0bcceab885d342a00b12975c2718a..a3819966b9dc640d42723450d3869f5905c64639 100644 --- a/install/dist/conf/debian60.conf.php +++ b/install/dist/conf/debian60.conf.php @@ -65,14 +65,14 @@ $conf['mysql']['admin_user'] = 'root'; $conf['mysql']['admin_password'] = ''; $conf['mysql']['charset'] = 'utf8'; $conf['mysql']['ispconfig_user'] = 'ispconfig'; -$conf['mysql']['ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['ispconfig_password'] = md5(uniqid(rand())); $conf['mysql']['master_slave_setup'] = 'n'; $conf['mysql']['master_host'] = ''; $conf['mysql']['master_database'] = 'dbispconfig'; $conf['mysql']['master_admin_user'] = 'root'; $conf['mysql']['master_admin_password'] = ''; $conf['mysql']['master_ispconfig_user'] = ''; -$conf['mysql']['master_ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['master_ispconfig_password'] = md5(uniqid(rand())); //* Apache $conf['apache']['installed'] = false; // will be detected automatically during installation @@ -223,4 +223,4 @@ $conf['cron']['crontab_dir'] = '/etc/cron.d'; $conf['cron']['wget'] = '/usr/bin/wget'; -?> \ No newline at end of file +?> diff --git a/install/dist/conf/fedora9.conf.php b/install/dist/conf/fedora9.conf.php index c988d3f3cdfd1cf75ba8e86140e3033056e82379..80539a78593827e76bb7828ee684833f557b9dd7 100644 --- a/install/dist/conf/fedora9.conf.php +++ b/install/dist/conf/fedora9.conf.php @@ -63,14 +63,14 @@ $conf['mysql']['admin_user'] = 'root'; $conf['mysql']['admin_password'] = ''; $conf['mysql']['charset'] = 'utf8'; $conf['mysql']['ispconfig_user'] = 'ispconfig'; -$conf['mysql']['ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['ispconfig_password'] = md5(uniqid(rand())); $conf['mysql']['master_slave_setup'] = 'n'; $conf['mysql']['master_host'] = ''; $conf['mysql']['master_database'] = 'dbispconfig'; $conf['mysql']['master_admin_user'] = 'root'; $conf['mysql']['master_admin_password'] = ''; $conf['mysql']['master_ispconfig_user'] = ''; -$conf['mysql']['master_ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['master_ispconfig_password'] = md5(uniqid(rand())); //* Apache $conf['apache']['installed'] = false; // will be detected automatically during installation diff --git a/install/dist/conf/gentoo.conf.php b/install/dist/conf/gentoo.conf.php index 2a0471a5205088cea6ee54bd8d9659e1c3c044cd..2955cfa71dd391743f705449ea6849428005a367 100644 --- a/install/dist/conf/gentoo.conf.php +++ b/install/dist/conf/gentoo.conf.php @@ -63,14 +63,14 @@ $conf['mysql']['admin_user'] = 'root'; $conf['mysql']['admin_password'] = ''; $conf['mysql']['charset'] = 'utf8'; $conf['mysql']['ispconfig_user'] = 'ispconfig'; -$conf['mysql']['ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['ispconfig_password'] = md5(uniqid(rand())); $conf['mysql']['master_slave_setup'] = 'n'; $conf['mysql']['master_host'] = ''; $conf['mysql']['master_database'] = 'dbispconfig'; $conf['mysql']['master_admin_user'] = 'root'; $conf['mysql']['master_admin_password'] = ''; $conf['mysql']['master_ispconfig_user'] = ''; -$conf['mysql']['master_ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['master_ispconfig_password'] = md5(uniqid(rand())); //* SuPHP $conf['suphp']['config_file'] = '/etc/suphp.conf'; @@ -85,7 +85,7 @@ $conf['apache']['config_dir'] = '/etc/apache2'; $conf['apache']['config_file'] = $conf['apache']['config_dir'] .'/httpd.conf'; $conf['apache']['ssl_dir'] = '/etc/ssl/apache2'; $conf['apache']['vhost_conf_dir'] = $conf['apache']['config_dir'] . '/vhosts.d'; -$conf['apache']['vhost_conf_enabled_dir'] = $conf['apache']['vhost_conf_dir']; +$conf['apache']['vhost_conf_enabled_dir'] = $conf['apache']['vhost_conf_dir']; $conf['apache']['vhost_default'] = '00_default_vhost.conf'; $conf['apache']['vhost_port'] = '8080'; $conf['apache']['php_ini_path_apache'] = '/etc/php/apache2-php5/php.ini'; @@ -154,7 +154,7 @@ $conf['dovecot']['init_script'] = 'dovecot'; //* SASL $conf['saslauthd']['installed'] = false; // will be detected automatically during installation $conf['saslauthd']['config_file'] = '/etc/conf.d/saslauthd'; -$conf['saslauthd']['config_dir'] = '/etc/sasl2'; +$conf['saslauthd']['config_dir'] = '/etc/sasl2'; $conf['saslauthd']['init_script'] = 'saslauthd'; //* Amavisd diff --git a/install/dist/conf/opensuse110.conf.php b/install/dist/conf/opensuse110.conf.php index fd8ef65439bb1d36adcaf19751291a2610ddff1e..e389c3b2a0ea727d619b453c477ef0a8f0964122 100644 --- a/install/dist/conf/opensuse110.conf.php +++ b/install/dist/conf/opensuse110.conf.php @@ -63,14 +63,14 @@ $conf['mysql']['admin_user'] = 'root'; $conf['mysql']['admin_password'] = ''; $conf['mysql']['charset'] = 'utf8'; $conf['mysql']['ispconfig_user'] = 'ispconfig'; -$conf['mysql']['ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['ispconfig_password'] = md5(uniqid(rand())); $conf['mysql']['master_slave_setup'] = 'n'; $conf['mysql']['master_host'] = ''; $conf['mysql']['master_database'] = 'dbispconfig'; $conf['mysql']['master_admin_user'] = 'root'; $conf['mysql']['master_admin_password'] = ''; $conf['mysql']['master_ispconfig_user'] = ''; -$conf['mysql']['master_ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['master_ispconfig_password'] = md5(uniqid(rand())); //* Apache $conf['apache']['installed'] = false; // will be detected automatically during installation diff --git a/install/dist/conf/opensuse112.conf.php b/install/dist/conf/opensuse112.conf.php index 96a37d6a57561a02127faf1e5eb310029d317bad..fa0504652e9e75d908186507a6c69c67c271f4b9 100644 --- a/install/dist/conf/opensuse112.conf.php +++ b/install/dist/conf/opensuse112.conf.php @@ -63,14 +63,14 @@ $conf['mysql']['admin_user'] = 'root'; $conf['mysql']['admin_password'] = ''; $conf['mysql']['charset'] = 'utf8'; $conf['mysql']['ispconfig_user'] = 'ispconfig'; -$conf['mysql']['ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['ispconfig_password'] = md5(uniqid(rand())); $conf['mysql']['master_slave_setup'] = 'n'; $conf['mysql']['master_host'] = ''; $conf['mysql']['master_database'] = 'dbispconfig'; $conf['mysql']['master_admin_user'] = 'root'; $conf['mysql']['master_admin_password'] = ''; $conf['mysql']['master_ispconfig_user'] = ''; -$conf['mysql']['master_ispconfig_password'] = md5 (uniqid (rand())); +$conf['mysql']['master_ispconfig_password'] = md5(uniqid(rand())); //* Apache $conf['apache']['installed'] = false; // will be detected automatically during installation diff --git a/install/dist/lib/centos52.lib.php b/install/dist/lib/centos52.lib.php index a7e4f945c29e6b9f6682f6654e976984bbd4f802..f4aa4dfe9d676663b31ab348e4b82de150b94793 100644 --- a/install/dist/lib/centos52.lib.php +++ b/install/dist/lib/centos52.lib.php @@ -58,26 +58,26 @@ class installer extends installer_dist { } } } - + $config_dir = $conf['mailman']['config_dir'].'/'; $full_file_name = $config_dir.'virtual_to_transport.sh'; - + //* Backup exiting virtual_to_transport.sh script if(is_file($full_file_name)) { copy($full_file_name, $config_dir.'virtual_to_transport.sh~'); } - - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name); - } else { - copy('tpl/mailman-virtual_to_transport.sh',$full_file_name); - } - chgrp($full_file_name,'mailman'); - chmod($full_file_name,0750); - + + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name); + } else { + copy('tpl/mailman-virtual_to_transport.sh', $full_file_name); + } + chgrp($full_file_name, 'mailman'); + chmod($full_file_name, 0750); + if(!is_file('/var/lib/mailman/data/transport-mailman')) touch('/var/lib/mailman/data/transport-mailman'); exec('/usr/sbin/postmap /var/lib/mailman/data/transport-mailman'); - + exec('/usr/lib/mailman/bin/genaliases 2>/dev/null'); $virtual_domains = ''; @@ -87,13 +87,13 @@ class installer extends installer_dist { $domainAll = $this->db->queryAllRecords("SELECT domain FROM mail_mailinglist GROUP BY domain"); if(is_array($domainAll)) { - foreach($domainAll as $domain) - { - if ($domainAll[0]['domain'] == $domain['domain']) - $virtual_domains .= "'".$domain['domain']."'"; - else - $virtual_domains .= ", '".$domain['domain']."'"; - } + foreach($domainAll as $domain) + { + if ($domainAll[0]['domain'] == $domain['domain']) + $virtual_domains .= "'".$domain['domain']."'"; + else + $virtual_domains .= ", '".$domain['domain']."'"; + } } } else @@ -109,55 +109,55 @@ class installer extends installer_dist { public function configure_amavis() { global $conf; - + // amavisd user config file $configfile = 'fedora_amavisd_conf'; - if(is_file($conf["amavis"]["config_dir"].'/amavisd.conf')) copy($conf["amavis"]["config_dir"].'/amavisd.conf',$conf["amavis"]["config_dir"].'/amavisd.conf~'); + if(is_file($conf["amavis"]["config_dir"].'/amavisd.conf')) copy($conf["amavis"]["config_dir"].'/amavisd.conf', $conf["amavis"]["config_dir"].'/amavisd.conf~'); if(is_file($conf["amavis"]["config_dir"].'/amavisd.conf~')) exec('chmod 400 '.$conf["amavis"]["config_dir"].'/amavisd.conf~'); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/".$configfile.".master"); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_port}',$conf["mysql"]["port"],$content); - $content = str_replace('{mysql_server_ip}',$conf['mysql']['ip'],$content); - $content = str_replace('{hostname}',$conf['hostname'],$content); - $content = str_replace('/var/spool/amavisd/clamd.sock','/tmp/clamd.socket',$content); - wf($conf["amavis"]["config_dir"].'/amavisd.conf',$content); - - + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_port}', $conf["mysql"]["port"], $content); + $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content); + $content = str_replace('{hostname}', $conf['hostname'], $content); + $content = str_replace('/var/spool/amavisd/clamd.sock', '/tmp/clamd.socket', $content); + wf($conf["amavis"]["config_dir"].'/amavisd.conf', $content); + + // Adding the amavisd commands to the postfix configuration $postconf_commands = array ( 'content_filter = amavis:[127.0.0.1]:10024', 'receive_override_options = no_address_mappings' ); - + // Make a backup copy of the main.cf file - copy($conf["postfix"]["config_dir"].'/main.cf',$conf["postfix"]["config_dir"].'/main.cf~2'); - + copy($conf["postfix"]["config_dir"].'/main.cf', $conf["postfix"]["config_dir"].'/main.cf~2'); + // Executing the postconf commands foreach($postconf_commands as $cmd) { $command = "postconf -e '$cmd'"; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + // Append the configuration for amavisd to the master.cf file - if(is_file($conf["postfix"]["config_dir"].'/master.cf')) copy($conf["postfix"]["config_dir"].'/master.cf',$conf["postfix"]["config_dir"].'/master.cf~'); + if(is_file($conf["postfix"]["config_dir"].'/master.cf')) copy($conf["postfix"]["config_dir"].'/master.cf', $conf["postfix"]["config_dir"].'/master.cf~'); $content = rf($conf["postfix"]["config_dir"].'/master.cf'); // Only add the content if we had not addded it before - if(!stristr($content,"127.0.0.1:10025")) { + if(!stristr($content, "127.0.0.1:10025")) { unset($content); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/master_cf_amavis.master', "tpl/master_cf_amavis.master"); - af($conf["postfix"]["config_dir"].'/master.cf',$content); + af($conf["postfix"]["config_dir"].'/master.cf', $content); } unset($content); - - removeLine('/etc/sysconfig/freshclam','FRESHCLAM_DELAY=disabled-warn # REMOVE ME',1); - replaceLine('/etc/freshclam.conf','Example','# Example',1); - - + + removeLine('/etc/sysconfig/freshclam', 'FRESHCLAM_DELAY=disabled-warn # REMOVE ME', 1); + replaceLine('/etc/freshclam.conf', 'Example', '# Example', 1); + + } } -?> \ No newline at end of file +?> diff --git a/install/dist/lib/centos53.lib.php b/install/dist/lib/centos53.lib.php index 91f1746c784d77f1b92c85b5da1bc562e222e9ff..93083b518865b19fd624f6354959f19e25760d33 100644 --- a/install/dist/lib/centos53.lib.php +++ b/install/dist/lib/centos53.lib.php @@ -58,26 +58,26 @@ class installer extends installer_dist { } } } - + $config_dir = $conf['mailman']['config_dir'].'/'; $full_file_name = $config_dir.'virtual_to_transport.sh'; - + //* Backup exiting virtual_to_transport.sh script if(is_file($full_file_name)) { copy($full_file_name, $config_dir.'virtual_to_transport.sh~'); } - - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name); - } else { - copy('tpl/mailman-virtual_to_transport.sh',$full_file_name); - } - chgrp($full_file_name,'mailman'); - chmod($full_file_name,0750); - + + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name); + } else { + copy('tpl/mailman-virtual_to_transport.sh', $full_file_name); + } + chgrp($full_file_name, 'mailman'); + chmod($full_file_name, 0750); + if(!is_file('/var/lib/mailman/data/transport-mailman')) touch('/var/lib/mailman/data/transport-mailman'); exec('/usr/sbin/postmap /var/lib/mailman/data/transport-mailman'); - + exec('/usr/lib/mailman/bin/genaliases 2>/dev/null'); $virtual_domains = ''; @@ -87,13 +87,13 @@ class installer extends installer_dist { $domainAll = $this->db->queryAllRecords("SELECT domain FROM mail_mailinglist GROUP BY domain"); if(is_array($domainAll)) { - foreach($domainAll as $domain) - { - if ($domainAll[0]['domain'] == $domain['domain']) - $virtual_domains .= "'".$domain['domain']."'"; - else - $virtual_domains .= ", '".$domain['domain']."'"; - } + foreach($domainAll as $domain) + { + if ($domainAll[0]['domain'] == $domain['domain']) + $virtual_domains .= "'".$domain['domain']."'"; + else + $virtual_domains .= ", '".$domain['domain']."'"; + } } } else @@ -109,56 +109,56 @@ class installer extends installer_dist { public function configure_amavis() { global $conf; - + // amavisd user config file $configfile = 'fedora_amavisd_conf'; - if(is_file($conf["amavis"]["config_dir"].'/amavisd.conf')) copy($conf["amavis"]["config_dir"].'/amavisd.conf',$conf["amavis"]["config_dir"].'/amavisd.conf~'); + if(is_file($conf["amavis"]["config_dir"].'/amavisd.conf')) copy($conf["amavis"]["config_dir"].'/amavisd.conf', $conf["amavis"]["config_dir"].'/amavisd.conf~'); if(is_file($conf["amavis"]["config_dir"].'/amavisd.conf~')) exec('chmod 400 '.$conf["amavis"]["config_dir"].'/amavisd.conf~'); if(!is_dir($conf["amavis"]["config_dir"])) mkdir($conf["amavis"]["config_dir"]); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/".$configfile.".master"); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_port}',$conf["mysql"]["port"],$content); - $content = str_replace('{mysql_server_ip}',$conf['mysql']['ip'],$content); - $content = str_replace('{hostname}',$conf['hostname'],$content); - $content = str_replace('/var/spool/amavisd/clamd.sock','/var/run/clamav/clamd.sock',$content); - wf($conf["amavis"]["config_dir"].'/amavisd.conf',$content); - - + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_port}', $conf["mysql"]["port"], $content); + $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content); + $content = str_replace('{hostname}', $conf['hostname'], $content); + $content = str_replace('/var/spool/amavisd/clamd.sock', '/var/run/clamav/clamd.sock', $content); + wf($conf["amavis"]["config_dir"].'/amavisd.conf', $content); + + // Adding the amavisd commands to the postfix configuration $postconf_commands = array ( 'content_filter = amavis:[127.0.0.1]:10024', 'receive_override_options = no_address_mappings' ); - + // Make a backup copy of the main.cf file - copy($conf["postfix"]["config_dir"].'/main.cf',$conf["postfix"]["config_dir"].'/main.cf~2'); - + copy($conf["postfix"]["config_dir"].'/main.cf', $conf["postfix"]["config_dir"].'/main.cf~2'); + // Executing the postconf commands foreach($postconf_commands as $cmd) { $command = "postconf -e '$cmd'"; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + // Append the configuration for amavisd to the master.cf file - if(is_file($conf["postfix"]["config_dir"].'/master.cf')) copy($conf["postfix"]["config_dir"].'/master.cf',$conf["postfix"]["config_dir"].'/master.cf~'); + if(is_file($conf["postfix"]["config_dir"].'/master.cf')) copy($conf["postfix"]["config_dir"].'/master.cf', $conf["postfix"]["config_dir"].'/master.cf~'); $content = rf($conf["postfix"]["config_dir"].'/master.cf'); // Only add the content if we had not addded it before - if(!stristr($content,"127.0.0.1:10025")) { + if(!stristr($content, "127.0.0.1:10025")) { unset($content); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/master_cf_amavis.master', "tpl/master_cf_amavis.master"); - af($conf["postfix"]["config_dir"].'/master.cf',$content); + af($conf["postfix"]["config_dir"].'/master.cf', $content); } unset($content); - - removeLine('/etc/sysconfig/freshclam','FRESHCLAM_DELAY=disabled-warn # REMOVE ME',1); - replaceLine('/etc/freshclam.conf','Example','# Example',1); - - + + removeLine('/etc/sysconfig/freshclam', 'FRESHCLAM_DELAY=disabled-warn # REMOVE ME', 1); + replaceLine('/etc/freshclam.conf', 'Example', '# Example', 1); + + } } -?> \ No newline at end of file +?> diff --git a/install/dist/lib/debian40.lib.php b/install/dist/lib/debian40.lib.php index cf8e864e6b00227b6730ef61a6c7aea8595dfe8f..b13b98c654b6437b1c67fb4f18981370e61da3d8 100644 --- a/install/dist/lib/debian40.lib.php +++ b/install/dist/lib/debian40.lib.php @@ -33,4 +33,4 @@ class installer extends installer_base { } -?> \ No newline at end of file +?> diff --git a/install/dist/lib/debian60.lib.php b/install/dist/lib/debian60.lib.php index e1be29132be2ea226f984492330d9580ec6da05b..b3887cbd235513c726f07ba3315822359ac7d2b4 100644 --- a/install/dist/lib/debian60.lib.php +++ b/install/dist/lib/debian60.lib.php @@ -29,13 +29,13 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class installer extends installer_base { - + public function configure_dovecot() - { + { global $conf; - + $config_dir = $conf['dovecot']['config_dir']; - + //* Configure master.cf and add a line for deliver if(is_file($config_dir.'/master.cf')){ copy($config_dir.'/master.cf', $config_dir.'/master.cf~2'); @@ -45,14 +45,14 @@ class installer extends installer_base { } $content = rf($conf["postfix"]["config_dir"].'/master.cf'); // Only add the content if we had not addded it before - if(!stristr($content,"dovecot/deliver")) { + if(!stristr($content, "dovecot/deliver")) { $deliver_content = 'dovecot unix - n n - - pipe'."\n".' flags=DRhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${user}@${nexthop}'; - af($conf["postfix"]["config_dir"].'/master.cf',$deliver_content); + af($conf["postfix"]["config_dir"].'/master.cf', $deliver_content); } unset($content); unset($deliver_content); - - + + //* Reconfigure postfix to use dovecot authentication // Adding the amavisd commands to the postfix configuration $postconf_commands = array ( @@ -61,44 +61,44 @@ class installer extends installer_base { 'smtpd_sasl_type = dovecot', 'smtpd_sasl_path = private/auth' ); - + // Make a backup copy of the main.cf file - copy($conf["postfix"]["config_dir"].'/main.cf',$conf["postfix"]["config_dir"].'/main.cf~3'); - + copy($conf["postfix"]["config_dir"].'/main.cf', $conf["postfix"]["config_dir"].'/main.cf~3'); + // Executing the postconf commands foreach($postconf_commands as $cmd) { $command = "postconf -e '$cmd'"; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + //* copy dovecot.conf $configfile = 'dovecot.conf'; if(is_file($config_dir.'/'.$configfile)){ copy($config_dir.'/'.$configfile, $config_dir.'/'.$configfile.'~'); } - + //* Get the dovecot version - exec('dovecot --version',$tmp); - $parts = explode('.',trim($tmp[0])); + exec('dovecot --version', $tmp); + $parts = explode('.', trim($tmp[0])); $dovecot_version = $parts[0]; unset($tmp); unset($parts); - + //* Copy dovecot configuration file if($dovecot_version == 2) { - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian6_dovecot2.conf.master')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian6_dovecot2.conf.master', $config_dir.'/'.$configfile); - } else { - copy('tpl/debian6_dovecot2.conf.master',$config_dir.'/'.$configfile); - } + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian6_dovecot2.conf.master')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian6_dovecot2.conf.master', $config_dir.'/'.$configfile); + } else { + copy('tpl/debian6_dovecot2.conf.master', $config_dir.'/'.$configfile); + } } else { - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian6_dovecot.conf.master')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian6_dovecot.conf.master', $config_dir.'/'.$configfile); - } else { - copy('tpl/debian6_dovecot.conf.master',$config_dir.'/'.$configfile); - } + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian6_dovecot.conf.master')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian6_dovecot.conf.master', $config_dir.'/'.$configfile); + } else { + copy('tpl/debian6_dovecot.conf.master', $config_dir.'/'.$configfile); + } } - + //* dovecot-sql.conf $configfile = 'dovecot-sql.conf'; if(is_file($config_dir.'/'.$configfile)){ @@ -106,32 +106,33 @@ class installer extends installer_base { chmod($config_dir.'/'.$configfile.'~', 0400); } $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian6_dovecot-sql.conf.master', 'tpl/debian6_dovecot-sql.conf.master'); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); wf($config_dir.'/'.$configfile, $content); - + chmod($config_dir.'/'.$configfile, 0600); chown($config_dir.'/'.$configfile, 'root'); chgrp($config_dir.'/'.$configfile, 'root'); } - + public function configure_apache() { global $conf; - - if(file_exists('/etc/apache2/mods-available/fcgid.conf')) replaceLine('/etc/apache2/mods-available/fcgid.conf','MaxRequestLen','MaxRequestLen 15728640',0,1); - + + if(file_exists('/etc/apache2/mods-available/fcgid.conf')) replaceLine('/etc/apache2/mods-available/fcgid.conf', 'MaxRequestLen', 'MaxRequestLen 15728640', 0, 1); + parent::configure_apache(); } - public function configure_fail2ban() { - /* + public function configure_fail2ban() { + /* copy('tpl/dovecot-pop3imap.conf.master',"/etc/fail2ban/filter.d/dovecot-pop3imap.conf"); copy('tpl/dovecot_fail2ban_jail.local.master','/etc/fail2ban/jail.local'); */ - } + } + } ?> diff --git a/install/dist/lib/fedora.lib.php b/install/dist/lib/fedora.lib.php index 99fd2af543647419cf628cfcb695350bf08cf058..2ec1cf0faea2a8f9e3ce99be0a275c3b64ae2176 100644 --- a/install/dist/lib/fedora.lib.php +++ b/install/dist/lib/fedora.lib.php @@ -58,7 +58,7 @@ class installer_dist extends installer_base { } } } - + if(!is_file('/var/lib/mailman/data/transport-mailman')) touch('/var/lib/mailman/data/transport-mailman'); exec('/usr/sbin/postmap /var/lib/mailman/data/transport-mailman'); @@ -69,13 +69,13 @@ class installer_dist extends installer_base { $domainAll = $this->db->queryAllRecords("SELECT domain FROM mail_mailinglist GROUP BY domain"); if(is_array($domainAll)) { - foreach($domainAll as $domain) - { - if ($domainAll[0]['domain'] == $domain['domain']) - $virtual_domains .= "'".$domain['domain']."'"; - else - $virtual_domains .= ", '".$domain['domain']."'"; - } + foreach($domainAll as $domain) + { + if ($domainAll[0]['domain'] == $domain['domain']) + $virtual_domains .= "'".$domain['domain']."'"; + else + $virtual_domains .= ", '".$domain['domain']."'"; + } } } else @@ -87,77 +87,77 @@ class installer_dist extends installer_base { $content = str_replace('{virtual_domains}', $virtual_domains, $content); wf($full_file_name, $content); - + //* Write virtual_to_transport.sh script $config_dir = $conf['mailman']['config_dir'].'/'; $full_file_name = $config_dir.'virtual_to_transport.sh'; - + //* Backup exiting virtual_to_transport.sh script if(is_file($full_file_name)) { copy($full_file_name, $config_dir.'virtual_to_transport.sh~'); } - + if(is_dir('/etc/mailman')) { - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name); - } else { - copy('tpl/mailman-virtual_to_transport.sh',$full_file_name); - } - chgrp($full_file_name,'mailman'); - chmod($full_file_name,0750); + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name); + } else { + copy('tpl/mailman-virtual_to_transport.sh', $full_file_name); + } + chgrp($full_file_name, 'mailman'); + chmod($full_file_name, 0750); } - + //* Create aliasaes exec('/usr/lib/mailman/bin/genaliases 2>/dev/null'); - + } - + function configure_postfix($options = '') - { - global $conf; + { + global $conf; $cf = $conf['postfix']; $config_dir = $cf['config_dir']; - + if(!is_dir($config_dir)){ - $this->error("The postfix configuration directory '$config_dir' does not exist."); - } - + $this->error("The postfix configuration directory '$config_dir' does not exist."); + } + //* mysql-virtual_domains.cf - $this->process_postfix_config('mysql-virtual_domains.cf'); + $this->process_postfix_config('mysql-virtual_domains.cf'); //* mysql-virtual_forwardings.cf - $this->process_postfix_config('mysql-virtual_forwardings.cf'); + $this->process_postfix_config('mysql-virtual_forwardings.cf'); //* mysql-virtual_mailboxes.cf - $this->process_postfix_config('mysql-virtual_mailboxes.cf'); + $this->process_postfix_config('mysql-virtual_mailboxes.cf'); //* mysql-virtual_email2email.cf - $this->process_postfix_config('mysql-virtual_email2email.cf'); + $this->process_postfix_config('mysql-virtual_email2email.cf'); //* mysql-virtual_transports.cf - $this->process_postfix_config('mysql-virtual_transports.cf'); + $this->process_postfix_config('mysql-virtual_transports.cf'); //* mysql-virtual_recipient.cf - $this->process_postfix_config('mysql-virtual_recipient.cf'); + $this->process_postfix_config('mysql-virtual_recipient.cf'); //* mysql-virtual_sender.cf - $this->process_postfix_config('mysql-virtual_sender.cf'); + $this->process_postfix_config('mysql-virtual_sender.cf'); //* mysql-virtual_client.cf - $this->process_postfix_config('mysql-virtual_client.cf'); - + $this->process_postfix_config('mysql-virtual_client.cf'); + //* mysql-virtual_relaydomains.cf - $this->process_postfix_config('mysql-virtual_relaydomains.cf'); - + $this->process_postfix_config('mysql-virtual_relaydomains.cf'); + //* mysql-virtual_relayrecipientmaps.cf - $this->process_postfix_config('mysql-virtual_relayrecipientmaps.cf'); + $this->process_postfix_config('mysql-virtual_relayrecipientmaps.cf'); //* Changing mode and group of the new created config files. caselog('chmod o= '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null', - __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed'); - caselog('chgrp '.$cf['group'].' '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null', - __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed'); - + __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed'); + caselog('chgrp '.$cf['group'].' '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null', + __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed'); + //* Creating virtual mail user and group $command = 'groupadd -g '.$cf['vmail_groupid'].' '.$cf['vmail_groupname']; if(!is_group($cf['vmail_groupname'])) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); @@ -173,7 +173,7 @@ class installer_dist extends installer_base { //* If there are RBL's defined, format the list and add them to smtp_recipient_restrictions to prevent removeal after an update $rbl_list = ''; if (@isset($server_ini_array['mail']['realtime_blackhole_list']) && $server_ini_array['mail']['realtime_blackhole_list'] != '') { - $rbl_hosts = explode(",",str_replace(" ", "", $server_ini_array['mail']['realtime_blackhole_list'])); + $rbl_hosts = explode(",", str_replace(" ", "", $server_ini_array['mail']['realtime_blackhole_list'])); foreach ($rbl_hosts as $key => $value) { $rbl_list .= ", reject_rbl_client ". $value; } @@ -182,130 +182,130 @@ class installer_dist extends installer_base { unset($server_ini_array); //* These postconf commands will be executed on installation and update - $postconf_placeholders = array('{config_dir}' => $config_dir, - '{vmail_mailbox_base}' => $cf['vmail_mailbox_base'], - '{vmail_userid}' => $cf['vmail_userid'], - '{vmail_groupid}' => $cf['vmail_groupid'], - '{rbl_list}' => $rbl_list); - - $postconf_tpl = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_postfix.conf.master', 'tpl/fedora_postfix.conf.master'); - $postconf_tpl = strtr($postconf_tpl, $postconf_placeholders); - $postconf_commands = array_filter(explode("\n", $postconf_tpl)); // read and remove empty lines - + $postconf_placeholders = array('{config_dir}' => $config_dir, + '{vmail_mailbox_base}' => $cf['vmail_mailbox_base'], + '{vmail_userid}' => $cf['vmail_userid'], + '{vmail_groupid}' => $cf['vmail_groupid'], + '{rbl_list}' => $rbl_list); + + $postconf_tpl = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_postfix.conf.master', 'tpl/fedora_postfix.conf.master'); + $postconf_tpl = strtr($postconf_tpl, $postconf_placeholders); + $postconf_commands = array_filter(explode("\n", $postconf_tpl)); // read and remove empty lines + //* These postconf commands will be executed on installation only if($this->is_update == false) { - $postconf_commands = array_merge($postconf_commands,array( - 'myhostname = '.$conf['hostname'], - 'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain', - 'mynetworks = 127.0.0.0/8 [::1]/128' - )); + $postconf_commands = array_merge($postconf_commands, array( + 'myhostname = '.$conf['hostname'], + 'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain', + 'mynetworks = 127.0.0.0/8 [::1]/128' + )); } - + //* Create the header and body check files touch($config_dir.'/header_checks'); touch($config_dir.'/mime_header_checks'); touch($config_dir.'/nested_header_checks'); touch($config_dir.'/body_checks'); - + //* Create the mailman files if(!is_dir('/var/lib/mailman/data')) exec('mkdir -p /var/lib/mailman/data'); //if(!is_file('/var/lib/mailman/data/aliases')) touch('/var/lib/mailman/data/aliases'); if(is_file('/var/lib/mailman/data/aliases')) unlink('/var/lib/mailman/data/aliases'); - if(!is_link('/var/lib/mailman/data/aliases')) symlink('/etc/mailman/aliases','/var/lib/mailman/data/aliases'); + if(!is_link('/var/lib/mailman/data/aliases')) symlink('/etc/mailman/aliases', '/var/lib/mailman/data/aliases'); exec('postalias /var/lib/mailman/data/aliases'); if(!is_file('/var/lib/mailman/data/virtual-mailman')) touch('/var/lib/mailman/data/virtual-mailman'); exec('postmap /var/lib/mailman/data/virtual-mailman'); if(!is_file('/var/lib/mailman/data/transport-mailman')) touch('/var/lib/mailman/data/transport-mailman'); exec('/usr/sbin/postmap /var/lib/mailman/data/transport-mailman'); - + //* Make a backup copy of the main.cf file copy($config_dir.'/main.cf', $config_dir.'/main.cf~'); - + //* Executing the postconf commands foreach($postconf_commands as $cmd) { $command = "postconf -e '$cmd'"; caselog($command." &> /dev/null", __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command); } - - if(!stristr($options,'dont-create-certs')) { + + if(!stristr($options, 'dont-create-certs')) { //* Create the SSL certificate $command = 'cd '.$config_dir.'; ' - .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:2048 -nodes -keyout smtpd.key -keyform PEM -days 365 -x509'; + .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:2048 -nodes -keyout smtpd.key -keyform PEM -days 365 -x509'; exec($command); - + $command = 'chmod o= '.$config_dir.'/smtpd.key'; caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command); } - + //** We have to change the permissions of the courier authdaemon directory to make it accessible for maildrop. $command = 'chmod 755 /var/spool/authdaemon'; caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command); - + //* Changing maildrop lines in posfix master.cf if(is_file($config_dir.'/master.cf')){ - copy($config_dir.'/master.cf', $config_dir.'/master.cf~'); - } + copy($config_dir.'/master.cf', $config_dir.'/master.cf~'); + } if(is_file($config_dir.'/master.cf~')){ - exec('chmod 400 '.$config_dir.'/master.cf~'); - } + exec('chmod 400 '.$config_dir.'/master.cf~'); + } $configfile = $config_dir.'/master.cf'; $content = rf($configfile); // if postfix package is from fedora or centios main repo - $content = str_replace('# flags=DRhu user=vmail argv=/usr/local/bin/maildrop -d ${recipient}', - ' flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d ${recipient} ${extension} ${recipient} ${user} ${nexthop} ${sender}', - $content); - + $content = str_replace('# flags=DRhu user=vmail argv=/usr/local/bin/maildrop -d ${recipient}', + ' flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d ${recipient} ${extension} ${recipient} ${user} ${nexthop} ${sender}', + $content); + // If postfix package is from centos plus repo - $content = str_replace('# flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}', - ' flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d ${recipient} ${extension} ${recipient} ${user} ${nexthop} ${sender}', - $content); - - $content = str_replace(' flags=DRhu user=vmail argv=/usr/local/bin/maildrop -d ${recipient}', - ' flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d ${recipient} ${extension} ${recipient} ${user} ${nexthop} ${sender}', - $content); - - - $content = str_replace('#maildrop unix - n n - - pipe', - 'maildrop unix - n n - - pipe', - $content); - + $content = str_replace('# flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}', + ' flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d ${recipient} ${extension} ${recipient} ${user} ${nexthop} ${sender}', + $content); + + $content = str_replace(' flags=DRhu user=vmail argv=/usr/local/bin/maildrop -d ${recipient}', + ' flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d ${recipient} ${extension} ${recipient} ${user} ${nexthop} ${sender}', + $content); + + + $content = str_replace('#maildrop unix - n n - - pipe', + 'maildrop unix - n n - - pipe', + $content); + wf($configfile, $content); - + //* Writing the Maildrop mailfilter file $configfile = 'mailfilter'; if(is_file($cf['vmail_mailbox_base'].'/.'.$configfile)){ - copy($cf['vmail_mailbox_base'].'/.'.$configfile, $cf['vmail_mailbox_base'].'/.'.$configfile.'~'); - } + copy($cf['vmail_mailbox_base'].'/.'.$configfile, $cf['vmail_mailbox_base'].'/.'.$configfile.'~'); + } $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/$configfile.master"); $content = str_replace('{dist_postfix_vmail_mailbox_base}', $cf['vmail_mailbox_base'], $content); wf($cf['vmail_mailbox_base'].'/.'.$configfile, $content); - + //* Create the directory for the custom mailfilters $command = 'mkdir '.$cf['vmail_mailbox_base'].'/mailfilters'; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* Chmod and chown the .mailfilter file $command = 'chown -R '.$cf['vmail_username'].':'.$cf['vmail_groupname'].' '.$cf['vmail_mailbox_base'].'/.mailfilter'; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + $command = 'chmod -R 600 '.$cf['vmail_mailbox_base'].'/.mailfilter'; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + } - + public function configure_saslauthd() { global $conf; - + $configfile = 'tpl/fedora_saslauthd_smtpd_conf.master'; $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_saslauthd_smtpd_conf.master', $configfile); - wf('/usr/lib/sasl2/smtpd.conf',$content); - if(is_dir('/usr/lib64')) wf('/usr/lib64/sasl/smtpd.conf',$content); - if(is_dir('/usr/lib64')) wf('/usr/lib64/sasl2/smtpd.conf',$content); - + wf('/usr/lib/sasl2/smtpd.conf', $content); + if(is_dir('/usr/lib64')) wf('/usr/lib64/sasl/smtpd.conf', $content); + if(is_dir('/usr/lib64')) wf('/usr/lib64/sasl2/smtpd.conf', $content); + } - + public function configure_pam() - { + { global $conf; $pam = $conf['pam']; //* configure pam for SMTP authentication agains the ispconfig database @@ -323,68 +323,68 @@ class installer_dist extends installer_base { if(is_file("$pam/smtp")) exec("chmod o= $pam/smtp"); //exec("chmod 660 $pam/smtp"); //exec("chown root:root $pam/smtp"); - + } - + public function configure_courier() - { + { global $conf; $config_dir = $conf['courier']['config_dir']; //* authmysqlrc $configfile = 'authmysqlrc'; if(is_file("$config_dir/$configfile")){ - copy("$config_dir/$configfile", "$config_dir/$configfile~"); - } + copy("$config_dir/$configfile", "$config_dir/$configfile~"); + } exec("chmod 400 $config_dir/$configfile~"); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/$configfile.master"); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); wf("$config_dir/$configfile", $content); - + exec("chmod 660 $config_dir/$configfile"); exec("chown root:root $config_dir/$configfile"); - + //* authdaemonrc $configfile = $conf['courier']['config_dir'].'/authdaemonrc'; if(is_file($configfile)){ - copy($configfile, $configfile.'~'); - } + copy($configfile, $configfile.'~'); + } if(is_file($configfile.'~')){ - exec('chmod 400 '.$configfile.'~'); - } + exec('chmod 400 '.$configfile.'~'); + } $content = rf($configfile); $content = str_replace('authmodulelist=', 'authmodulelist="authmysql"', $content); wf($configfile, $content); } - + public function configure_dovecot() - { + { global $conf; - + $config_dir = $conf['dovecot']['config_dir']; - + //* Use /etc/dovecot as config dir if exists if(is_dir('/etc/dovecot')) $config_dir = '/etc/dovecot'; - + //* Configure master.cf and add a line for deliver if(is_file($config_dir.'/master.cf')){ - copy($config_dir.'/master.cf', $config_dir.'/master.cf~2'); - } + copy($config_dir.'/master.cf', $config_dir.'/master.cf~2'); + } if(is_file($config_dir.'/master.cf~')){ - exec('chmod 400 '.$config_dir.'/master.cf~2'); - } + exec('chmod 400 '.$config_dir.'/master.cf~2'); + } $content = rf($conf["postfix"]["config_dir"].'/master.cf'); // Only add the content if we had not addded it before - if(!stristr($content,"dovecot/deliver")) { + if(!stristr($content, "dovecot/deliver")) { $deliver_content = 'dovecot unix - n n - - pipe'."\n".' flags=DROhu user=vmail:vmail argv=/usr/libexec/dovecot/deliver -f ${sender} -d ${user}@${nexthop}'; - af($conf["postfix"]["config_dir"].'/master.cf',$deliver_content); + af($conf["postfix"]["config_dir"].'/master.cf', $deliver_content); } unset($content); unset($deliver_content); - - + + //* Reconfigure postfix to use dovecot authentication // Adding the amavisd commands to the postfix configuration $postconf_commands = array ( @@ -394,119 +394,119 @@ class installer_dist extends installer_base { 'smtpd_sasl_path = private/auth', 'receive_override_options = no_address_mappings' ); - + // Make a backup copy of the main.cf file - copy($conf["postfix"]["config_dir"].'/main.cf',$conf["postfix"]["config_dir"].'/main.cf~3'); - + copy($conf["postfix"]["config_dir"].'/main.cf', $conf["postfix"]["config_dir"].'/main.cf~3'); + // Executing the postconf commands foreach($postconf_commands as $cmd) { $command = "postconf -e '$cmd'"; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + //* backup dovecot.conf $configfile = 'dovecot.conf'; if(is_file("$config_dir/$configfile")){ - copy("$config_dir/$configfile", "$config_dir/$configfile~"); - } - + copy("$config_dir/$configfile", "$config_dir/$configfile~"); + } + //* Get the dovecot version - exec('dovecot --version',$tmp); - $parts = explode('.',trim($tmp[0])); + exec('dovecot --version', $tmp); + $parts = explode('.', trim($tmp[0])); $dovecot_version = $parts[0]; unset($tmp); unset($parts); - + //* Copy dovecot configuration file if($dovecot_version == 2) { - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_dovecot2.conf.master')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_dovecot2.conf.master', $config_dir.'/'.$configfile); - } else { - copy('tpl/fedora_dovecot2.conf.master',$config_dir.'/'.$configfile); - } + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_dovecot2.conf.master')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_dovecot2.conf.master', $config_dir.'/'.$configfile); + } else { + copy('tpl/fedora_dovecot2.conf.master', $config_dir.'/'.$configfile); + } } else { - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_dovecot.conf.master')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_dovecot.conf.master', $config_dir.'/'.$configfile); - } else { - copy('tpl/fedora_dovecot.conf.master',$config_dir.'/'.$configfile); - } + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_dovecot.conf.master')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_dovecot.conf.master', $config_dir.'/'.$configfile); + } else { + copy('tpl/fedora_dovecot.conf.master', $config_dir.'/'.$configfile); + } } //* dovecot-sql.conf $configfile = 'dovecot-sql.conf'; if(is_file("$config_dir/$configfile")){ - copy("$config_dir/$configfile", "$config_dir/$configfile~"); + copy("$config_dir/$configfile", "$config_dir/$configfile~"); exec("chmod 400 $config_dir/$configfile~"); - } - + } + $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_dovecot-sql.conf.master', "tpl/fedora_dovecot-sql.conf.master"); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); wf("$config_dir/$configfile", $content); - + exec("chmod 600 $config_dir/$configfile"); exec("chown root:root $config_dir/$configfile"); } - + public function configure_amavis() { global $conf; - + // amavisd user config file $configfile = 'fedora_amavisd_conf'; - if(is_file($conf["amavis"]["config_dir"].'/amavisd.conf')) copy($conf["amavis"]["config_dir"].'/amavisd.conf',$conf["amavis"]["config_dir"].'/amavisd.conf~'); + if(is_file($conf["amavis"]["config_dir"].'/amavisd.conf')) copy($conf["amavis"]["config_dir"].'/amavisd.conf', $conf["amavis"]["config_dir"].'/amavisd.conf~'); if(is_file($conf["amavis"]["config_dir"].'/amavisd.conf~')) exec('chmod 400 '.$conf["amavis"]["config_dir"].'/amavisd.conf~'); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/".$configfile.".master"); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_port}',$conf["mysql"]["port"],$content); - $content = str_replace('{mysql_server_ip}',$conf['mysql']['ip'],$content); - $content = str_replace('{hostname}',$conf['hostname'],$content); - wf($conf["amavis"]["config_dir"].'/amavisd.conf',$content); - - + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_port}', $conf["mysql"]["port"], $content); + $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content); + $content = str_replace('{hostname}', $conf['hostname'], $content); + wf($conf["amavis"]["config_dir"].'/amavisd.conf', $content); + + // Adding the amavisd commands to the postfix configuration $postconf_commands = array ( 'content_filter = amavis:[127.0.0.1]:10024', 'receive_override_options = no_address_mappings' ); - + // Make a backup copy of the main.cf file - copy($conf["postfix"]["config_dir"].'/main.cf',$conf["postfix"]["config_dir"].'/main.cf~2'); - + copy($conf["postfix"]["config_dir"].'/main.cf', $conf["postfix"]["config_dir"].'/main.cf~2'); + // Executing the postconf commands foreach($postconf_commands as $cmd) { $command = "postconf -e '$cmd'"; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + // Append the configuration for amavisd to the master.cf file - if(is_file($conf["postfix"]["config_dir"].'/master.cf')) copy($conf["postfix"]["config_dir"].'/master.cf',$conf["postfix"]["config_dir"].'/master.cf~'); + if(is_file($conf["postfix"]["config_dir"].'/master.cf')) copy($conf["postfix"]["config_dir"].'/master.cf', $conf["postfix"]["config_dir"].'/master.cf~'); $content = rf($conf["postfix"]["config_dir"].'/master.cf'); // Only add the content if we had not addded it before - if(!stristr($content,"127.0.0.1:10025")) { + if(!stristr($content, "127.0.0.1:10025")) { unset($content); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/master_cf_amavis.master', "tpl/master_cf_amavis.master"); - af($conf["postfix"]["config_dir"].'/master.cf',$content); + af($conf["postfix"]["config_dir"].'/master.cf', $content); } unset($content); - - removeLine('/etc/sysconfig/freshclam','FRESHCLAM_DELAY=disabled-warn # REMOVE ME',1); - replaceLine('/etc/freshclam.conf','Example','# Example',1); - + + removeLine('/etc/sysconfig/freshclam', 'FRESHCLAM_DELAY=disabled-warn # REMOVE ME', 1); + replaceLine('/etc/freshclam.conf', 'Example', '# Example', 1); + // Add the clamav user to the vscan group //exec('groupmod --add-user clamav vscan'); - - + + } - + public function configure_spamassassin() - { + { global $conf; - + //* Enable spamasasssin on debian and ubuntu /* $configfile = '/etc/default/spamassassin'; @@ -518,40 +518,40 @@ class installer_dist extends installer_base { wf($configfile, $content); */ } - + public function configure_getmail() - { + { global $conf; - + $config_dir = $conf['getmail']['config_dir']; - + if(!is_dir($config_dir)) exec("mkdir -p ".escapeshellcmd($config_dir)); $command = "useradd -d $config_dir getmail"; if(!is_user('getmail')) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + $command = "chown -R getmail $config_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + $command = "chmod -R 700 $config_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - - + + public function configure_pureftpd() - { + { global $conf; - + $config_dir = $conf['pureftpd']['config_dir']; //* configure pam for SMTP authentication agains the ispconfig database $configfile = 'pureftpd-mysql.conf'; if(is_file("$config_dir/$configfile")){ - copy("$config_dir/$configfile", "$config_dir/$configfile~"); - } + copy("$config_dir/$configfile", "$config_dir/$configfile~"); + } if(is_file("$config_dir/$configfile~")){ - exec("chmod 400 $config_dir/$configfile~"); - } + exec("chmod 400 $config_dir/$configfile~"); + } $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/pureftpd_mysql.conf.master', 'tpl/pureftpd_mysql.conf.master'); $content = str_replace('{mysql_server_ispconfig_user}', $conf["mysql"]["ispconfig_user"], $content); $content = str_replace('{mysql_server_ispconfig_password}', $conf["mysql"]["ispconfig_password"], $content); @@ -561,45 +561,45 @@ class installer_dist extends installer_base { wf("$config_dir/$configfile", $content); exec("chmod 600 $config_dir/$configfile"); exec("chown root:root $config_dir/$configfile"); - + // copy our customized copy of pureftpd.conf to the pure-ftpd config directory if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_pureftpd_conf.master')) { - exec("cp " . $conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_pureftpd_conf.master ' . "$config_dir/pure-ftpd.conf"); - }else { - exec("cp tpl/fedora_pureftpd_conf.master $config_dir/pure-ftpd.conf"); - } - + exec("cp " . $conf['ispconfig_install_dir'].'/server/conf-custom/install/fedora_pureftpd_conf.master ' . "$config_dir/pure-ftpd.conf"); + }else { + exec("cp tpl/fedora_pureftpd_conf.master $config_dir/pure-ftpd.conf"); + } + } - + public function configure_mydns() - { + { global $conf; - + // configure mydns $configfile = 'mydns.conf'; - if(is_file($conf["mydns"]["config_dir"].'/'.$configfile)) copy($conf["mydns"]["config_dir"].'/'.$configfile,$conf["mydns"]["config_dir"].'/'.$configfile.'~'); + if(is_file($conf["mydns"]["config_dir"].'/'.$configfile)) copy($conf["mydns"]["config_dir"].'/'.$configfile, $conf["mydns"]["config_dir"].'/'.$configfile.'~'); if(is_file($conf["mydns"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["mydns"]["config_dir"].'/'.$configfile.'~'); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/".$configfile.".master"); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_host}',$conf["mysql"]["host"],$content); - $content = str_replace('{server_id}',$conf["server_id"],$content); - wf($conf["mydns"]["config_dir"].'/'.$configfile,$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_host}', $conf["mysql"]["host"], $content); + $content = str_replace('{server_id}', $conf["server_id"], $content); + wf($conf["mydns"]["config_dir"].'/'.$configfile, $content); exec('chmod 600 '.$conf["mydns"]["config_dir"].'/'.$configfile); exec('chown root:root '.$conf["mydns"]["config_dir"].'/'.$configfile); - + } - + public function configure_bind() { global $conf; - + // add the include line at the end of named.conf. - replaceLine('/etc/named.conf','include "/etc/named.conf.local";','include "/etc/named.conf.local";',0,1); + replaceLine('/etc/named.conf', 'include "/etc/named.conf.local";', 'include "/etc/named.conf.local";', 0, 1); //* Check if the zonefile directory has a slash at the end $content=$conf['bind']['bind_zonefiles_dir']; - if(substr($content,-1,1) != '/') { + if(substr($content, -1, 1) != '/') { $content .= '/'; } @@ -611,37 +611,37 @@ class installer_dist extends installer_base { //* Chown the slave subdirectory to $conf['bind']['bind_user'] exec('chown '.$conf['bind']['bind_user'].':'.$conf['bind']['bind_group'].' '.$content); exec('chmod 770 '.$content); - + } - + public function configure_apache() - { + { global $conf; - + if($conf['apache']['installed'] == false) return; if(is_file('/etc/suphp.conf')) { //replaceLine('/etc/suphp.conf','php=php:/usr/bin','x-httpd-suphp=php:/usr/bin/php-cgi',0); - replaceLine('/etc/suphp.conf','docroot=','docroot=/var/www',0); - replaceLine('/etc/suphp.conf','umask=0077','umask=0022',0); + replaceLine('/etc/suphp.conf', 'docroot=', 'docroot=/var/www', 0); + replaceLine('/etc/suphp.conf', 'umask=0077', 'umask=0022', 0); } - + //* Create the logging directory for the vhost logfiles exec('mkdir -p /var/log/ispconfig/httpd'); - + // Sites enabled and avaulable dirs exec('mkdir -p '.$conf['apache']['vhost_conf_enabled_dir']); exec('mkdir -p '.$conf['apache']['vhost_conf_dir']); - + $content = rf('/etc/httpd/conf/httpd.conf'); - if(!stristr($content,'Include /etc/httpd/conf/sites-enabled/')) { - af('/etc/httpd/conf/httpd.conf',"\nNameVirtualHost *:80\nNameVirtualHost *:443\nInclude /etc/httpd/conf/sites-enabled/\n\n"); + if(!stristr($content, 'Include /etc/httpd/conf/sites-enabled/')) { + af('/etc/httpd/conf/httpd.conf', "\nNameVirtualHost *:80\nNameVirtualHost *:443\nInclude /etc/httpd/conf/sites-enabled/\n\n"); } unset($content); - + //* Copy the ISPConfig configuration include - $vhost_conf_dir = $conf['apache']['vhost_conf_dir']; - $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir']; - + $vhost_conf_dir = $conf['apache']['vhost_conf_dir']; + $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir']; + // copy('tpl/apache_ispconfig.conf.master',$vhost_conf_dir.'/ispconfig.conf'); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig.conf.master', 'tpl/apache_ispconfig.conf.master'); $records = $this->db->queryAllRecords('SELECT * FROM '.$conf['mysql']['master_database'].'.server_ip WHERE server_id = '.$conf['server_id']." AND virtualhost = 'y'"); @@ -653,7 +653,7 @@ class installer_dist extends installer_base { } else { $ip_address = $rec['ip_address']; } - $ports = explode(',',$rec['virtualhost_port']); + $ports = explode(',', $rec['virtualhost_port']); if(is_array($ports)) { foreach($ports as $port) { $port = intval($port); @@ -664,138 +664,138 @@ class installer_dist extends installer_base { } } } - + $content .= "\n"; - wf($vhost_conf_dir.'/ispconfig.conf',$content); - + wf($vhost_conf_dir.'/ispconfig.conf', $content); + if(!@is_link($vhost_conf_enabled_dir."/000-ispconfig.conf")) { exec("ln -s ".$vhost_conf_dir."/ispconfig.conf ".$vhost_conf_enabled_dir."/000-ispconfig.conf"); } - + //* make sure that webalizer finds its config file when it is directly in /etc if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) { exec('mkdir /etc/webalizer'); exec('ln -s /etc/webalizer.conf /etc/webalizer/webalizer.conf'); } - + if(is_file('/etc/webalizer/webalizer.conf')) { // Change webalizer mode to incremental - replaceLine('/etc/webalizer/webalizer.conf','#IncrementalName','IncrementalName webalizer.current',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#Incremental','Incremental yes',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#HistoryName','HistoryName webalizer.hist',0,0); + replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental yes', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName webalizer.hist', 0, 0); } - + //* add a sshusers group $command = 'groupadd sshusers'; if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + } - + public function configure_nginx(){ global $conf; - + if($conf['nginx']['installed'] == false) return; //* Create the logging directory for the vhost logfiles if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true); - + // Sites enabled and avaulable dirs exec('mkdir -p '.$conf['nginx']['vhost_conf_enabled_dir']); exec('mkdir -p '.$conf['nginx']['vhost_conf_dir']); - wf('/etc/nginx/conf.d/ispconfig_vhosts.conf',"include /etc/nginx/sites-enabled/*.vhost;"); + wf('/etc/nginx/conf.d/ispconfig_vhosts.conf', "include /etc/nginx/sites-enabled/*.vhost;"); //* make sure that webalizer finds its config file when it is directly in /etc if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) { mkdir('/etc/webalizer'); - symlink('/etc/webalizer.conf','/etc/webalizer/webalizer.conf'); + symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf'); } if(is_file('/etc/webalizer/webalizer.conf')) { // Change webalizer mode to incremental - replaceLine('/etc/webalizer/webalizer.conf','#IncrementalName','IncrementalName webalizer.current',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#Incremental','Incremental yes',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#HistoryName','HistoryName webalizer.hist',0,0); + replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental yes', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName webalizer.hist', 0, 0); } - + // Check the awsatst script if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools'); - if(!file_exists('/usr/share/awstats/tools/awstats_buildstaticpages.pl') && file_exists('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl')) symlink('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl','/usr/share/awstats/tools/awstats_buildstaticpages.pl'); - if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local','LogFormat=4','LogFormat=1',0,1); - + if(!file_exists('/usr/share/awstats/tools/awstats_buildstaticpages.pl') && file_exists('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl')) symlink('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl', '/usr/share/awstats/tools/awstats_buildstaticpages.pl'); + if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local', 'LogFormat=4', 'LogFormat=1', 0, 1); + //* add a sshusers group $command = 'groupadd sshusers'; if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + public function configure_firewall() { global $conf; - + $dist_init_scripts = $conf['init_scripts']; - + if(is_dir("/etc/Bastille.backup")) caselog("rm -rf /etc/Bastille.backup", __FILE__, __LINE__); if(is_dir("/etc/Bastille")) caselog("mv -f /etc/Bastille /etc/Bastille.backup", __FILE__, __LINE__); - @mkdir("/etc/Bastille", octdec($directory_mode)); - if(is_dir("/etc/Bastille.backup/firewall.d")) caselog("cp -pfr /etc/Bastille.backup/firewall.d /etc/Bastille/", __FILE__, __LINE__); - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master')) { - caselog("cp -f " . $conf['ispconfig_install_dir']."/server/conf-custom/install/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg", __FILE__, __LINE__); - } else { - caselog("cp -f tpl/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg", __FILE__, __LINE__); - } - caselog("chmod 644 /etc/Bastille/bastille-firewall.cfg", __FILE__, __LINE__); - $content = rf("/etc/Bastille/bastille-firewall.cfg"); - $content = str_replace("{DNS_SERVERS}", "", $content); + @mkdir("/etc/Bastille", octdec($directory_mode)); + if(is_dir("/etc/Bastille.backup/firewall.d")) caselog("cp -pfr /etc/Bastille.backup/firewall.d /etc/Bastille/", __FILE__, __LINE__); + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master')) { + caselog("cp -f " . $conf['ispconfig_install_dir']."/server/conf-custom/install/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg", __FILE__, __LINE__); + } else { + caselog("cp -f tpl/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg", __FILE__, __LINE__); + } + caselog("chmod 644 /etc/Bastille/bastille-firewall.cfg", __FILE__, __LINE__); + $content = rf("/etc/Bastille/bastille-firewall.cfg"); + $content = str_replace("{DNS_SERVERS}", "", $content); + + $tcp_public_services = ''; + $udp_public_services = ''; - $tcp_public_services = ''; - $udp_public_services = ''; - $row = $this->db->queryOneRecord('SELECT * FROM '.$conf["mysql"]["database"].'.firewall WHERE server_id = '.intval($conf['server_id'])); - - if(trim($row["tcp_port"]) != '' || trim($row["udp_port"]) != ''){ - $tcp_public_services = trim(str_replace(',',' ',$row["tcp_port"])); - $udp_public_services = trim(str_replace(',',' ',$row["udp_port"])); - } else { - $tcp_public_services = '21 22 25 53 80 110 443 3306 8080 10000'; - $udp_public_services = '53'; - } + + if(trim($row["tcp_port"]) != '' || trim($row["udp_port"]) != ''){ + $tcp_public_services = trim(str_replace(',', ' ', $row["tcp_port"])); + $udp_public_services = trim(str_replace(',', ' ', $row["udp_port"])); + } else { + $tcp_public_services = '21 22 25 53 80 110 443 3306 8080 10000'; + $udp_public_services = '53'; + } if(!stristr($tcp_public_services, $conf['apache']['vhost_port'])) { $tcp_public_services .= ' '.intval($conf['apache']['vhost_port']); if($row["tcp_port"] != '') $this->db->query("UPDATE firewall SET tcp_port = tcp_port + ',".intval($conf['apache']['vhost_port'])."' WHERE server_id = ".intval($conf['server_id'])); } - - $content = str_replace("{TCP_PUBLIC_SERVICES}", $tcp_public_services, $content); - $content = str_replace("{UDP_PUBLIC_SERVICES}", $udp_public_services, $content); - wf("/etc/Bastille/bastille-firewall.cfg", $content); + $content = str_replace("{TCP_PUBLIC_SERVICES}", $tcp_public_services, $content); + $content = str_replace("{UDP_PUBLIC_SERVICES}", $udp_public_services, $content); + + wf("/etc/Bastille/bastille-firewall.cfg", $content); + + if(is_file($dist_init_scripts."/bastille-firewall")) caselog("mv -f $dist_init_scripts/bastille-firewall $dist_init_scripts/bastille-firewall.backup", __FILE__, __LINE__); + caselog("cp -f apps/bastille-firewall $dist_init_scripts", __FILE__, __LINE__); + caselog("chmod 700 $dist_init_scripts/bastille-firewall", __FILE__, __LINE__); - if(is_file($dist_init_scripts."/bastille-firewall")) caselog("mv -f $dist_init_scripts/bastille-firewall $dist_init_scripts/bastille-firewall.backup", __FILE__, __LINE__); - caselog("cp -f apps/bastille-firewall $dist_init_scripts", __FILE__, __LINE__); - caselog("chmod 700 $dist_init_scripts/bastille-firewall", __FILE__, __LINE__); + if(is_file("/sbin/bastille-ipchains")) caselog("mv -f /sbin/bastille-ipchains /sbin/bastille-ipchains.backup", __FILE__, __LINE__); + caselog("cp -f apps/bastille-ipchains /sbin", __FILE__, __LINE__); + caselog("chmod 700 /sbin/bastille-ipchains", __FILE__, __LINE__); - if(is_file("/sbin/bastille-ipchains")) caselog("mv -f /sbin/bastille-ipchains /sbin/bastille-ipchains.backup", __FILE__, __LINE__); - caselog("cp -f apps/bastille-ipchains /sbin", __FILE__, __LINE__); - caselog("chmod 700 /sbin/bastille-ipchains", __FILE__, __LINE__); + if(is_file("/sbin/bastille-netfilter")) caselog("mv -f /sbin/bastille-netfilter /sbin/bastille-netfilter.backup", __FILE__, __LINE__); + caselog("cp -f apps/bastille-netfilter /sbin", __FILE__, __LINE__); + caselog("chmod 700 /sbin/bastille-netfilter", __FILE__, __LINE__); - if(is_file("/sbin/bastille-netfilter")) caselog("mv -f /sbin/bastille-netfilter /sbin/bastille-netfilter.backup", __FILE__, __LINE__); - caselog("cp -f apps/bastille-netfilter /sbin", __FILE__, __LINE__); - caselog("chmod 700 /sbin/bastille-netfilter", __FILE__, __LINE__); - if(!@is_dir('/var/lock/subsys')) caselog("mkdir /var/lock/subsys", __FILE__, __LINE__); - exec("which ipchains &> /dev/null", $ipchains_location, $ret_val); - if(!is_file("/sbin/ipchains") && !is_link("/sbin/ipchains") && $ret_val == 0) phpcaselog(@symlink(shell_exec("which ipchains"), "/sbin/ipchains"), 'create symlink', __FILE__, __LINE__); - unset($ipchains_location); - exec("which iptables &> /dev/null", $iptables_location, $ret_val); - if(!is_file("/sbin/iptables") && !is_link("/sbin/iptables") && $ret_val == 0) phpcaselog(@symlink(trim(shell_exec("which iptables")), "/sbin/iptables"), 'create symlink', __FILE__, __LINE__); - unset($iptables_location); + exec("which ipchains &> /dev/null", $ipchains_location, $ret_val); + if(!is_file("/sbin/ipchains") && !is_link("/sbin/ipchains") && $ret_val == 0) phpcaselog(@symlink(shell_exec("which ipchains"), "/sbin/ipchains"), 'create symlink', __FILE__, __LINE__); + unset($ipchains_location); + exec("which iptables &> /dev/null", $iptables_location, $ret_val); + if(!is_file("/sbin/iptables") && !is_link("/sbin/iptables") && $ret_val == 0) phpcaselog(@symlink(trim(shell_exec("which iptables")), "/sbin/iptables"), 'create symlink', __FILE__, __LINE__); + unset($iptables_location); } - - + + public function install_ispconfig() - { + { global $conf; - + $install_dir = $conf['ispconfig_install_dir']; //* Create the ISPConfig installation directory @@ -803,68 +803,68 @@ class installer_dist extends installer_base { $command = "mkdir $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + //* Create a ISPConfig user and group $command = 'groupadd ispconfig'; if(!is_group('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + $command = "useradd -g ispconfig -d $install_dir ispconfig"; if(!is_user('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* copy the ISPConfig interface part $command = "cp -rf ../interface $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* copy the ISPConfig server part $command = "cp -rf ../server $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* Create a symlink, so ISPConfig is accessible via web // Replaced by a separate vhost definition for port 8080 // $command = "ln -s $install_dir/interface/web/ /var/www/ispconfig"; // caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* Create the config file for ISPConfig interface $configfile = 'config.inc.php'; if(is_file($install_dir.'/interface/lib/'.$configfile)){ - copy("$install_dir/interface/lib/$configfile", "$install_dir/interface/lib/$configfile~"); - } + copy("$install_dir/interface/lib/$configfile", "$install_dir/interface/lib/$configfile~"); + } $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/$configfile.master"); $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); - + $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content); $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content); $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content); $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content); - + $content = str_replace('{server_id}', $conf['server_id'], $content); $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content); $content = str_replace('{language}', $conf['language'], $content); $content = str_replace('{timezone}', $conf['timezone'], $content); $content = str_replace('{theme}', $conf['theme'], $content); $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content); - + wf("$install_dir/interface/lib/$configfile", $content); - + //* Create the config file for ISPConfig server $configfile = 'config.inc.php'; if(is_file($install_dir.'/server/lib/'.$configfile)){ - copy("$install_dir/server/lib/$configfile", "$install_dir/interface/lib/$configfile~"); - } + copy("$install_dir/server/lib/$configfile", "$install_dir/interface/lib/$configfile~"); + } $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/$configfile.master"); $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); - + $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content); $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content); $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content); $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content); - + $content = str_replace('{server_id}', $conf['server_id'], $content); $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content); $content = str_replace('{language}', $conf['language'], $content); @@ -873,24 +873,24 @@ class installer_dist extends installer_base { $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content); wf("$install_dir/server/lib/$configfile", $content); - + //* Create the config file for remote-actions (but only, if it does not exist, because // the value is a autoinc-value and so changed by the remoteaction_core_module if (!file_exists($install_dir.'/server/lib/remote_action.inc.php')) { $content = ''; wf($install_dir.'/server/lib/remote_action.inc.php', $content); } - - + + //* Enable the server modules and plugins. // TODO: Implement a selector which modules and plugins shall be enabled. $dir = $install_dir.'/server/mods-available/'; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { - if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') { - include_once($install_dir.'/server/mods-available/'.$file); - $module_name = substr($file,0,-8); + if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') { + include_once $install_dir.'/server/mods-available/'.$file; + $module_name = substr($file, 0, -8); $tmp = new $module_name; if($tmp->onInstall()) { if(!@is_link($install_dir.'/server/mods-enabled/'.$file)) @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-enabled/'.$file); @@ -904,16 +904,16 @@ class installer_dist extends installer_base { closedir($dh); } } - + $dir = $install_dir.'/server/plugins-available/'; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { if($conf['apache']['installed'] == true && $file == 'nginx_plugin.inc.php') continue; if($conf['nginx']['installed'] == true && $file == 'apache2_plugin.inc.php') continue; - if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') { - include_once($install_dir.'/server/plugins-available/'.$file); - $plugin_name = substr($file,0,-8); + if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') { + include_once $install_dir.'/server/plugins-available/'.$file; + $plugin_name = substr($file, 0, -8); $tmp = new $plugin_name; if($tmp->onInstall()) { if(!@is_link($install_dir.'/server/plugins-enabled/'.$file)) @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-enabled/'.$file); @@ -927,7 +927,7 @@ class installer_dist extends installer_base { closedir($dh); } } - + // Update the server config $mail_server_enabled = ($conf['services']['mail'])?1:0; $web_server_enabled = ($conf['services']['web'])?1:0; @@ -936,14 +936,14 @@ class installer_dist extends installer_base { $db_server_enabled = ($conf['services']['db'])?1:0; $vserver_server_enabled = ($conf['services']['vserver'])?1:0; $sql = "UPDATE `server` SET mail_server = '$mail_server_enabled', web_server = '$web_server_enabled', dns_server = '$dns_server_enabled', file_server = '$file_server_enabled', db_server = '$db_server_enabled', vserver_server = '$vserver_server_enabled' WHERE server_id = ".intval($conf['server_id']); - + if($conf['mysql']['master_slave_setup'] == 'y') { $this->dbmaster->query($sql); $this->db->query($sql); } else { $this->db->query($sql); } - + //* Chmod the files $command = "chmod -R 750 $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); @@ -951,48 +951,48 @@ class installer_dist extends installer_base { //* chown the files to the ispconfig user and group $command = "chown -R ispconfig:ispconfig $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* Make the global language file directory group writable exec("chmod -R 770 $install_dir/interface/lib/lang"); - + //* Make the temp directory for language file exports writable exec("chmod -R 770 $install_dir/interface/web/temp"); - + //* Make all interface language file directories group writable $handle = @opendir($install_dir.'/interface/web'); - while ($file = @readdir ($handle)) { - if ($file != '.' && $file != '..') { - if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) { + while ($file = @readdir($handle)) { + if ($file != '.' && $file != '..') { + if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) { $handle2 = opendir($install_dir.'/interface/web'.'/'.$file.'/lib/lang'); - chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang',0770); - while ($lang_file = @readdir ($handle2)) { + chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang', 0770); + while ($lang_file = @readdir($handle2)) { if ($lang_file != '.' && $lang_file != '..') { - chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file,0770); + chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file, 0770); } } } } } - + //* Make the APS directories group writable exec("chmod -R 770 $install_dir/interface/web/sites/aps_meta_packages"); exec("chmod -R 770 $install_dir/server/aps_packages"); - + //* make sure that the server config file (not the interface one) is only readable by the root user chmod($install_dir.'/server/lib/config.inc.php', 0600); chown($install_dir.'/server/lib/config.inc.php', 'root'); chgrp($install_dir.'/server/lib/config.inc.php', 'root'); - + //* Make sure thet the interface config file is readable by user ispconfig only chmod($install_dir.'/interface/lib/config.inc.php', 0600); chown($install_dir.'/interface/lib/config.inc.php', 'ispconfig'); chgrp($install_dir.'/interface/lib/config.inc.php', 'ispconfig'); - + if(@is_file("$install_dir/server/lib/mysql_clientdb.conf")) { exec("chmod 600 $install_dir/server/lib/mysql_clientdb.conf"); exec("chown root:root $install_dir/server/lib/mysql_clientdb.conf"); } - + // TODO: FIXME: add the www-data user to the ispconfig group. This is just for testing // and must be fixed as this will allow the apache user to read the ispconfig files. // Later this must run as own apache server or via suexec! @@ -1008,38 +1008,38 @@ class installer_dist extends installer_base { $command = 'usermod -a -G ispconfig '.$conf['nginx']['user']; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); //if(is_user('ispapps')){ - // Allow the ispapps vhost access to /etc/squirrelmail - //$command = 'usermod -a -G '.$conf['apache']['group'].' ispapps'; - //caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); + // Allow the ispapps vhost access to /etc/squirrelmail + //$command = 'usermod -a -G '.$conf['apache']['group'].' ispapps'; + //caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); //} if(is_group('ispapps')){ $command = 'usermod -a -G ispapps '.$conf['nginx']['user']; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } } - + //* Make the shell scripts executable $command = "chmod +x $install_dir/server/scripts/*.sh"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + if($conf['apache']['installed'] == true && $this->install_ispconfig_interface == true){ //* Copy the ISPConfig vhost for the controlpanel // TODO: These are missing! should they be "vhost_dist_*_dir" ? $vhost_conf_dir = $conf['apache']['vhost_conf_dir']; $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir']; - - + + // Dont just copy over the virtualhost template but add some custom settings $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig.vhost.master', "tpl/apache_ispconfig.vhost.master"); $content = str_replace('{vhost_port}', $conf['apache']['vhost_port'], $content); - + // comment out the listen directive if port is 80 or 443 if($conf['apache']['vhost_port'] == 80 or $conf['apache']['vhost_port'] == 443) { $content = str_replace('{vhost_port_listen}', '#', $content); } else { $content = str_replace('{vhost_port_listen}', '', $content); } - + if(is_file('/usr/local/ispconfig/interface/ssl/ispserver.crt') && is_file('/usr/local/ispconfig/interface/ssl/ispserver.key')) { $content = str_replace('{ssl_comment}', '', $content); } else { @@ -1050,39 +1050,39 @@ class installer_dist extends installer_base { } else { $content = str_replace('{ssl_bundle_comment}', '#', $content); } - + wf("$vhost_conf_dir/ispconfig.vhost", $content); - + //copy('tpl/apache_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost"); //* and create the symlink //if($this->is_update == false) { - if(@is_link("$vhost_conf_enabled_dir/ispconfig.vhost")) unlink("$vhost_conf_enabled_dir/ispconfig.vhost"); - if(!@is_link("$vhost_conf_enabled_dir/000-ispconfig.vhost")) { - exec("ln -s $vhost_conf_dir/ispconfig.vhost $vhost_conf_enabled_dir/000-ispconfig.vhost"); - } - - /* + if(@is_link("$vhost_conf_enabled_dir/ispconfig.vhost")) unlink("$vhost_conf_enabled_dir/ispconfig.vhost"); + if(!@is_link("$vhost_conf_enabled_dir/000-ispconfig.vhost")) { + exec("ln -s $vhost_conf_dir/ispconfig.vhost $vhost_conf_enabled_dir/000-ispconfig.vhost"); + } + + /* exec('mkdir -p /var/www/php-fcgi-scripts/ispconfig'); exec('cp tpl/apache_ispconfig_fcgi_starter.master /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter'); exec('chmod +x /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter'); exec('ln -s /usr/local/ispconfig/interface/web /var/www/ispconfig'); exec('chown -R ispconfig:ispconfig /var/www/php-fcgi-scripts/ispconfig'); - + replaceLine('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter','PHPRC=','PHPRC=/etc/',0,0); */ - //if(!is_file('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter')) { - $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig_fcgi_starter.master', 'tpl/apache_ispconfig_fcgi_starter.master'); - $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content); - $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content); - if(!is_dir('/var/www/php-fcgi-scripts/ispconfig')) exec('mkdir -p /var/www/php-fcgi-scripts/ispconfig'); - wf('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter', $content); - exec('chmod +x /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter'); - if(!is_link('/var/www/ispconfig')) exec('ln -s /usr/local/ispconfig/interface/web /var/www/ispconfig'); - exec('chown -R ispconfig:ispconfig /var/www/php-fcgi-scripts/ispconfig'); - //} + //if(!is_file('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter')) { + $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig_fcgi_starter.master', 'tpl/apache_ispconfig_fcgi_starter.master'); + $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content); + $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content); + if(!is_dir('/var/www/php-fcgi-scripts/ispconfig')) exec('mkdir -p /var/www/php-fcgi-scripts/ispconfig'); + wf('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter', $content); + exec('chmod +x /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter'); + if(!is_link('/var/www/ispconfig')) exec('ln -s /usr/local/ispconfig/interface/web /var/www/ispconfig'); + exec('chown -R ispconfig:ispconfig /var/www/php-fcgi-scripts/ispconfig'); + //} //} } - + if($conf['nginx']['installed'] == true && $this->install_ispconfig_interface == true){ //* Copy the ISPConfig vhost for the controlpanel $vhost_conf_dir = $conf['nginx']['vhost_conf_dir']; @@ -1091,7 +1091,7 @@ class installer_dist extends installer_base { // Dont just copy over the virtualhost template but add some custom settings $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/nginx_ispconfig.vhost.master', 'tpl/nginx_ispconfig.vhost.master'); $content = str_replace('{vhost_port}', $conf['nginx']['vhost_port'], $content); - + if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) { $content = str_replace('{ssl_on}', ' on', $content); $content = str_replace('{ssl_comment}', '', $content); @@ -1101,19 +1101,19 @@ class installer_dist extends installer_base { $content = str_replace('{ssl_comment}', '#', $content); $content = str_replace('{fastcgi_ssl}', 'off', $content); } - + $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']); - if(substr($socket_dir,-1) != '/') $socket_dir .= '/'; + if(substr($socket_dir, -1) != '/') $socket_dir .= '/'; if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir); $fpm_socket = $socket_dir.'ispconfig.sock'; - + //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content); $content = str_replace('{fpm_socket}', $fpm_socket, $content); wf($vhost_conf_dir.'/ispconfig.vhost', $content); - + unset($content); - + // PHP-FPM // Dont just copy over the php-fpm pool template but add some custom settings $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/php_fpm_pool.conf.master', 'tpl/php_fpm_pool.conf.master'); @@ -1129,18 +1129,18 @@ class installer_dist extends installer_base { if($this->is_update == false) { if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost'); if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) { - symlink($vhost_conf_dir.'/ispconfig.vhost',$vhost_conf_enabled_dir.'/000-ispconfig.vhost'); + symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost'); } } - + // create symlink from /usr/share/phpmyadmin to /usr/share/phpMyAdmin, if it is installed - if(!@file_exists('/usr/share/phpmyadmin') && @is_dir('/usr/share/phpMyAdmin')) symlink('/usr/share/phpMyAdmin/','/usr/share/phpmyadmin'); + if(!@file_exists('/usr/share/phpmyadmin') && @is_dir('/usr/share/phpMyAdmin')) symlink('/usr/share/phpMyAdmin/', '/usr/share/phpmyadmin'); } - + // Make the Clamav log files readable by ISPConfig //exec('chmod +r /var/log/clamav/clamav.log'); //exec('chmod +r /var/log/clamav/freshclam.log'); - + //* Install the update script if(is_file('/usr/local/bin/ispconfig_update_from_svn.sh')) unlink('/usr/local/bin/ispconfig_update_from_svn.sh'); exec('chown root /usr/local/ispconfig/server/scripts/update_from_svn.sh'); @@ -1151,98 +1151,98 @@ class installer_dist extends installer_base { exec('chmod 700 /usr/local/ispconfig/server/scripts/ispconfig_update.sh'); if(!is_link('/usr/local/bin/ispconfig_update_from_svn.sh')) exec('ln -s /usr/local/ispconfig/server/scripts/ispconfig_update.sh /usr/local/bin/ispconfig_update_from_svn.sh'); if(!is_link('/usr/local/bin/ispconfig_update.sh')) exec('ln -s /usr/local/ispconfig/server/scripts/ispconfig_update.sh /usr/local/bin/ispconfig_update.sh'); - + // set the fast cgi starter script to executable // exec('chmod 755 '.$install_dir.'/interface/bin/php-fcgi'); - + //* Make the logs readable for the ispconfig user if(@is_file('/var/log/maillog')) exec('chmod +r /var/log/maillog'); //if(@is_file('/var/log/mail.warn')) exec('chmod +r /var/log/mail.warn'); //if(@is_file('/var/log/mail.err')) exec('chmod +r /var/log/mail.err'); if(@is_file('/var/log/messages')) exec('chmod +r /var/log/messages'); - + //To enable apache to read the directories // exec('chmod a+rx /usr/local/ispconfig'); // exec('chmod -R 751 /usr/local/ispconfig/interface'); // exec('chmod a+rx /usr/local/ispconfig/interface/web'); - + //* Create the ispconfig log directory if(!is_dir($conf['ispconfig_log_dir'])) mkdir($conf['ispconfig_log_dir']); if(!is_file($conf['ispconfig_log_dir'].'/ispconfig.log')) exec('touch '.$conf['ispconfig_log_dir'].'/ispconfig.log'); - + if(is_user('getmail')) { exec('mv /usr/local/ispconfig/server/scripts/run-getmail.sh /usr/local/bin/run-getmail.sh'); exec('chown getmail /usr/local/bin/run-getmail.sh'); exec('chmod 744 /usr/local/bin/run-getmail.sh'); } - + // Edit the file Edit the file /etc/sudoers and comment out the requiregetty line, otherwise the backup function will fail - replaceLine('/etc/sudoers','Defaults requiretty','#Defaults requiretty',0,0); - + replaceLine('/etc/sudoers', 'Defaults requiretty', '#Defaults requiretty', 0, 0); + if(is_dir($install_dir.'/interface/invoices')) { exec('chmod -R 770 '.escapeshellarg($install_dir.'/interface/invoices')); exec('chown -R ispconfig:ispconfig '.escapeshellarg($install_dir.'/interface/invoices')); } - + //* Create the ispconfig auth log file and set uid/gid if(!is_file($conf['ispconfig_log_dir'].'/auth.log')) { touch($conf['ispconfig_log_dir'].'/auth.log'); } exec('chown ispconfig:ispconfig '. $conf['ispconfig_log_dir'].'/auth.log'); exec('chmod 660 '. $conf['ispconfig_log_dir'].'/auth.log'); - + //* Remove Domain module as its functions are available in the client module now if(@is_dir('/usr/local/ispconfig/interface/web/domain')) exec('rm -rf /usr/local/ispconfig/interface/web/domain'); - + } - + public function configure_dbserver() { global $conf; - + //* If this server shall act as database server for client DB's, we configure this here $install_dir = $conf['ispconfig_install_dir']; - - // Create a file with the database login details which + + // Create a file with the database login details which // are used to create the client databases. - + if(!is_dir("$install_dir/server/lib")) { $command = "mkdir $install_dir/server/lib"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/mysql_clientdb.conf.master', "tpl/mysql_clientdb.conf.master"); - $content = str_replace('{hostname}',$conf['mysql']['host'],$content); - $content = str_replace('{username}',$conf['mysql']['admin_user'],$content); - $content = str_replace('{password}',$conf['mysql']['admin_password'], $content); - wf("$install_dir/server/lib/mysql_clientdb.conf",$content); + $content = str_replace('{hostname}', $conf['mysql']['host'], $content); + $content = str_replace('{username}', $conf['mysql']['admin_user'], $content); + $content = str_replace('{password}', $conf['mysql']['admin_password'], $content); + wf("$install_dir/server/lib/mysql_clientdb.conf", $content); exec('chmod 600 '."$install_dir/server/lib/mysql_clientdb.conf"); exec('chown root:root '."$install_dir/server/lib/mysql_clientdb.conf"); - + } - + public function install_crontab() - { + { global $conf; - + //* Root Crontab exec('crontab -u root -l > crontab.txt'); $existing_root_cron_jobs = file('crontab.txt'); - + // remove existing ispconfig cronjobs, in case the syntax has changed foreach($existing_root_cron_jobs as $key => $val) { - if(stristr($val,'/usr/local/ispconfig')) unset($existing_root_cron_jobs[$key]); + if(stristr($val, '/usr/local/ispconfig')) unset($existing_root_cron_jobs[$key]); } - + $root_cron_jobs = array( '* * * * * /usr/local/ispconfig/server/server.sh &> /dev/null', '30 00 * * * /usr/local/ispconfig/server/cron_daily.sh &> /dev/null' ); - + if ($conf['nginx']['installed'] == true) { $root_cron_jobs[] = "0 0 * * * /usr/local/ispconfig/server/scripts/create_daily_nginx_access_logs.sh &> /dev/null"; } - + foreach($root_cron_jobs as $cron_job) { if(!in_array($cron_job."\n", $existing_root_cron_jobs)) { $existing_root_cron_jobs[] = $cron_job."\n"; @@ -1251,22 +1251,22 @@ class installer_dist extends installer_base { file_put_contents('crontab.txt', $existing_root_cron_jobs); exec('crontab -u root crontab.txt &> /dev/null'); unlink('crontab.txt'); - + //* Getmail crontab if(is_user('getmail')) { - $cf = $conf['getmail']; + $cf = $conf['getmail']; exec('crontab -u getmail -l > crontab.txt'); $existing_cron_jobs = file('crontab.txt'); - + $cron_jobs = array( - '*/5 * * * * /usr/local/bin/run-getmail.sh > /dev/null 2>> /dev/null' - ); - + '*/5 * * * * /usr/local/bin/run-getmail.sh > /dev/null 2>> /dev/null' + ); + // remove existing ispconfig cronjobs, in case the syntax has changed foreach($existing_cron_jobs as $key => $val) { - if(stristr($val,'getmail')) unset($existing_cron_jobs[$key]); + if(stristr($val, 'getmail')) unset($existing_cron_jobs[$key]); } - + foreach($cron_jobs as $cron_job) { if(!in_array($cron_job."\n", $existing_cron_jobs)) { $existing_cron_jobs[] = $cron_job."\n"; @@ -1276,7 +1276,7 @@ class installer_dist extends installer_base { exec('crontab -u getmail crontab.txt &> /dev/null'); unlink('crontab.txt'); } - + exec('touch /var/log/ispconfig/cron.log'); exec('chmod 660 /var/log/ispconfig/cron.log'); } diff --git a/install/dist/lib/fedora9.lib.php b/install/dist/lib/fedora9.lib.php index da77b423aecf247618a2647aa4b2663d64651ad4..aeda9b9fd1c6b83d7388fc91bde429a6e4dd5b81 100644 --- a/install/dist/lib/fedora9.lib.php +++ b/install/dist/lib/fedora9.lib.php @@ -33,4 +33,4 @@ class installer extends installer_dist { } -?> \ No newline at end of file +?> diff --git a/install/dist/lib/gentoo.lib.php b/install/dist/lib/gentoo.lib.php index 853208896f2807ac42757990cf5678774af90518..f9b5a8bc423812b9f499174d651b81f594d652e4 100644 --- a/install/dist/lib/gentoo.lib.php +++ b/install/dist/lib/gentoo.lib.php @@ -28,47 +28,47 @@ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -class installer extends installer_base +class installer extends installer_base { public function configure_jailkit() - { - global $conf; - + { + global $conf; + if (is_dir($conf['jailkit']['config_dir'])) { $jkinit_content = $this->get_template_file($conf['jailkit']['jk_init'], true); //* get contents $this->write_config_file($conf['jailkit']['config_dir'] . '/' . $conf['jailkit']['jk_init'], $jkinit_content); - + $jkchroot_content = $this->get_template_file($conf['jailkit']['jk_chrootsh'], true); //* get contents $this->write_config_file($conf['jailkit']['config_dir'] . '/' . $conf['jailkit']['jk_chrootsh'], $jkchroot_content); } - + $command = 'chown root:root /var/www'; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - } - + } + public function configure_postfix($options = '') - { - global $conf; - - $cf = $conf['postfix']; + { + global $conf; + + $cf = $conf['postfix']; $config_dir = $cf['config_dir']; - + if(!is_dir($config_dir)){ - $this->error("The postfix configuration directory '$config_dir' does not exist."); - } - - //* Install virtual mappings - foreach (glob('tpl/mysql-virtual_*.master') as $filename) { - $this->process_postfix_config( basename($filename, '.master') ); - } - + $this->error("The postfix configuration directory '$config_dir' does not exist."); + } + + //* Install virtual mappings + foreach (glob('tpl/mysql-virtual_*.master') as $filename) { + $this->process_postfix_config( basename($filename, '.master') ); + } + //* Changing mode and group of the new created config files. caselog('chmod o= '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null', - __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed'); - caselog('chgrp '.$cf['group'].' '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null', - __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed'); - + __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed'); + caselog('chgrp '.$cf['group'].' '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null', + __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed'); + //* Creating virtual mail user and group $command = 'groupadd -g '.$cf['vmail_groupid'].' '.$cf['vmail_groupname']; if (!is_group($cf['vmail_groupname'])) { @@ -77,198 +77,198 @@ class installer extends installer_base $command = 'useradd -g '.$cf['vmail_groupname'].' -u '.$cf['vmail_userid'].' '.$cf['vmail_username'].' -d '.$cf['vmail_mailbox_base'].' -m'; if (!is_user($cf['vmail_username'])) { - caselog("$command &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); + caselog("$command &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } //* These postconf commands will be executed on installation and update - $postconf_placeholders = array('{config_dir}' => $config_dir, - '{vmail_mailbox_base}' => $cf['vmail_mailbox_base'], - '{vmail_userid}' => $cf['vmail_userid'], - '{vmail_groupid}' => $cf['vmail_groupid'], - '{rbl_list}' => $rbl_list); - - $postconf_tpl = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/gentoo_postfix.conf.master', 'tpl/gentoo_postfix.conf.master'); - $postconf_tpl = strtr($postconf_tpl, $postconf_placeholders); - $postconf_commands = array_filter(explode("\n", $postconf_tpl)); // read and remove empty lines - + $postconf_placeholders = array('{config_dir}' => $config_dir, + '{vmail_mailbox_base}' => $cf['vmail_mailbox_base'], + '{vmail_userid}' => $cf['vmail_userid'], + '{vmail_groupid}' => $cf['vmail_groupid'], + '{rbl_list}' => $rbl_list); + + $postconf_tpl = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/gentoo_postfix.conf.master', 'tpl/gentoo_postfix.conf.master'); + $postconf_tpl = strtr($postconf_tpl, $postconf_placeholders); + $postconf_commands = array_filter(explode("\n", $postconf_tpl)); // read and remove empty lines + //* These postconf commands will be executed on installation only if($this->is_update == false) { - $postconf_commands = array_merge($postconf_commands,array( - 'myhostname = '.$conf['hostname'], - 'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain', - 'mynetworks = 127.0.0.0/8 [::1]/128' - )); + $postconf_commands = array_merge($postconf_commands, array( + 'myhostname = '.$conf['hostname'], + 'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain', + 'mynetworks = 127.0.0.0/8 [::1]/128' + )); } - + //* Create the header and body check files touch($config_dir.'/header_checks'); touch($config_dir.'/mime_header_checks'); touch($config_dir.'/nested_header_checks'); touch($config_dir.'/body_checks'); - - + + //* Make a backup copy of the main.cf file copy($config_dir.'/main.cf', $config_dir.'/main.cf~'); - + //* Executing the postconf commands foreach($postconf_commands as $cmd) { $command = "postconf -e '$cmd'"; caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command); } - + //* Create the SSL certificate - if (!stristr($options,'dont-create-certs')) + if (!stristr($options, 'dont-create-certs')) { $command = 'cd '.$config_dir.'; ' - .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:2048 -nodes -keyout smtpd.key -keyform PEM -days 365 -x509'; + .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:2048 -nodes -keyout smtpd.key -keyform PEM -days 365 -x509'; exec($command); - + $command = 'chmod o= '.$config_dir.'/smtpd.key'; caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command); } - + //* We have to change the permissions of the courier authdaemon directory to make it accessible for maildrop. $command = 'chmod 755 /var/lib/courier/authdaemon/'; if (is_dir('/var/lib/courier/authdaemon')) { caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command); } - + //* Changing maildrop lines in posfix master.cf $configfile = $config_dir.'/master.cf'; $content = rf($configfile); - $content = preg_replace('/^#?maildrop/m', 'maildrop', $content); - $content = preg_replace('/^#?(\s+)flags=DRhu user=vmail argv=\/usr\/bin\/maildrop -d/m', - '$1flags=DRhu user=vmail argv=/usr/bin/maildrop -d vmail \${extension} \${recipient} \${user} \${nexthop} \${sender}', - $content); - + $content = preg_replace('/^#?maildrop/m', 'maildrop', $content); + $content = preg_replace('/^#?(\s+)flags=DRhu user=vmail argv=\/usr\/bin\/maildrop -d/m', + '$1flags=DRhu user=vmail argv=/usr/bin/maildrop -d vmail \${extension} \${recipient} \${user} \${nexthop} \${sender}', + $content); + $this->write_config_file($configfile, $content); - + //* Writing the Maildrop mailfilter file $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailfilter.master', 'tpl/mailfilter.master'); $content = str_replace('{dist_postfix_vmail_mailbox_base}', $cf['vmail_mailbox_base'], $content); - + $this->write_config_file($cf['vmail_mailbox_base'].'/.mailfilter', $content); - + //* Create the directory for the custom mailfilters - if (!is_dir($cf['vmail_mailbox_base'].'/mailfilters')) + if (!is_dir($cf['vmail_mailbox_base'].'/mailfilters')) { $command = 'mkdir '.$cf['vmail_mailbox_base'].'/mailfilters'; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + //* Chmod and chown the .mailfilter file $command = 'chown -R '.$cf['vmail_username'].':'.$cf['vmail_groupname'].' '.$cf['vmail_mailbox_base'].'/.mailfilter'; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + $command = 'chmod -R 600 '.$cf['vmail_mailbox_base'].'/.mailfilter'; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + } - - public function configure_saslauthd() + + public function configure_saslauthd() { global $conf; - + $content = $this->get_template_file('sasl_smtpd.conf', true, true); //* get contents & insert db cred $this->write_config_file($conf['saslauthd']['config_dir'].'/smtpd.conf', $content); - + //* Edit the file saslauthd config file $content = rf($conf['saslauthd']['config_file']); $content = preg_replace('/(?<=\n)SASLAUTHD_OPTS="\$\{SASLAUTHD_OPTS\}[^"]+"/', 'SASLAUTHD_OPTS="${SASLAUTHD_OPTS} -a pam -r -c -s 128 -t 30 -n 5"', $content); - + $this->write_config_file($conf['saslauthd']['config_file'], $content); } - + public function configure_courier() - { - global $conf; - + { + global $conf; + //* authmysqlrc $content = $this->get_template_file('authmysqlrc', true, true); //* get contents & insert db cred $this->write_config_file($conf['courier']['config_dir'].'/authmysqlrc', $content); - + //* authdaemonrc $configfile = $conf['courier']['config_dir'].'/authdaemonrc'; $content = rf($configfile); $content = preg_replace('/(?<=\n)authmodulelist="[^"]+"/', "authmodulelist=\"authmysql\"", $content); $this->write_config_file($configfile, $content); - + //* create certificates $command = 'mkimapdcert'; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + $command = 'mkpop3dcert'; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - } - - public function configure_dovecot() - { - global $conf; - - $config_dir = $conf['dovecot']['config_dir']; - - $configfile = $conf['postfix']['config_dir'].'/master.cf'; - - if(is_file($configfile)) { + } + + public function configure_dovecot() + { + global $conf; + + $config_dir = $conf['dovecot']['config_dir']; + + $configfile = $conf['postfix']['config_dir'].'/master.cf'; + + if(is_file($configfile)) { copy($configfile, $configfile.'~2'); } if(is_file($configfile.'~2')) { chmod($configfile.'~2', 0400); } - - //* Configure master.cf and add a line for deliver + + //* Configure master.cf and add a line for deliver $content = rf($configfile); - - if(!stristr($content,'dovecot/deliver')) { + + if(!stristr($content, 'dovecot/deliver')) { $deliver_content = 'dovecot unix - n n - - pipe'."\n".' flags=DROhu user=vmail:vmail argv=/usr/libexec/dovecot/deliver -f ${sender} -d ${user}@${nexthop}'; - af($conf['postfix']['config_dir'].'/master.cf',$deliver_content); + af($conf['postfix']['config_dir'].'/master.cf', $deliver_content); } unset($content); unset($deliver_content); unset($configfile); - + //* Reconfigure postfix to use dovecot authentication $postconf_commands = array ( - 'dovecot_destination_recipient_limit = 1', - 'virtual_transport = dovecot', - 'smtpd_sasl_type = dovecot', - 'smtpd_sasl_path = private/auth' + 'dovecot_destination_recipient_limit = 1', + 'virtual_transport = dovecot', + 'smtpd_sasl_type = dovecot', + 'smtpd_sasl_path = private/auth' ); - + //* Make a backup copy of the main.cf file - copy($conf['postfix']['config_dir'].'/main.cf',$conf['postfix']['config_dir'].'/main.cf~3'); - - //* Executing the postconf commands - foreach($postconf_commands as $cmd) + copy($conf['postfix']['config_dir'].'/main.cf', $conf['postfix']['config_dir'].'/main.cf~3'); + + //* Executing the postconf commands + foreach($postconf_commands as $cmd) { $command = "postconf -e '$cmd'"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + //* copy dovecot.conf $configfile = $config_dir.'/dovecot.conf'; $content = $this->get_template_file('dovecot.conf', true); $this->write_config_file($configfile, $content); - + //* dovecot-sql.conf $configfile = $config_dir.'/dovecot-sql.conf'; $content = $this->get_template_file('debian_dovecot-sql.conf', true, true); $this->write_config_file($configfile, $content); - } - + } + public function configure_spamassassin() - { + { return true; - } - + } + public function configure_getmail() - { + { global $conf; - + $config_dir = $conf['getmail']['config_dir']; - + if (!is_dir($config_dir)) { exec('mkdir -p '.escapeshellcmd($config_dir)); } @@ -277,86 +277,86 @@ class installer extends installer_base if (!is_user('getmail')) { caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + $command = "chown -R getmail $config_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + $command = "chmod -R 700 $config_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* Getmail will be run from cron. In order to have access to cron the getmail user needs to be part of the cron group. $command = "gpasswd -a getmail " . $conf['cron']['group']; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - - public function configure_amavis() - { + + public function configure_amavis() + { global $conf; - + //* Amavisd-new user config file $conf_file = 'amavisd-ispconfig.conf'; $conf_path = dirname($conf['amavis']['config_file']) . '/' . $conf_file; - + $content = $this->get_template_file($conf_file, true, true); //* get contents & insert db cred $this->write_config_file($conf_path, $content); - + //* Activate config directory in default file $amavis_conf = rf($conf['amavis']['config_file']); - if (stripos($amavis_conf, $conf_path) === false) + if (stripos($amavis_conf, $conf_path) === false) { $amavis_conf = preg_replace('/^(1;.*)$/m', "include_config_files('$conf_path');\n$1", $amavis_conf); $this->write_config_file($conf['amavis']['config_file'], $amavis_conf); } - + //* Adding the amavisd commands to the postfix configuration $postconf_commands = array ( 'content_filter = amavis:[127.0.0.1]:10024', 'receive_override_options = no_address_mappings' ); - - foreach($postconf_commands as $cmd) { + + foreach($postconf_commands as $cmd) { $command = "postconf -e '$cmd'"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + //* Append the configuration for amavisd to the master.cf file $content = rf($conf['postfix']['config_dir'].'/master.cf'); - - if(!stristr($content,'127.0.0.1:10025')) //* Only add the content if we had not addded it before - { + + if(!stristr($content, '127.0.0.1:10025')) //* Only add the content if we had not addded it before + { unset($content); $content = $this->get_template_file('master_cf_amavis', true); af($conf['postfix']['config_dir'].'/master.cf', $content); } unset($content); - + //* Add the clamav user to the amavis group exec('usermod -a -G amavis clamav'); - } - - public function configure_pureftpd() - { + } + + public function configure_pureftpd() + { global $conf; - + //* configure pure-ftpd for MySQL authentication against the ispconfig database $content = $this->get_template_file('pureftpd_mysql.conf', true, true); //* get contents & insert db cred $content = str_replace('{server_id}', $conf['server_id'], $content); - + $this->write_config_file($conf['pureftpd']['mysql_config_file'], $content, 600, 'root', 'root'); - + //* enable pure-ftpd and server settings $content = rf($conf["pureftpd"]["config_file"]); - + $content = preg_replace('/#?IS_CONFIGURED="(?:yes|no)"/', 'IS_CONFIGURED="yes"', $content); $content = str_replace('AUTH="-l unix"', 'AUTH="-l mysql:'.$conf['pureftpd']['mysql_config_file'].'"', $content); - + //* Logging defaults to syslog's ftp facility. Override this behaviour for better compatibility with debian/ubuntu //* and specify the format. $logdir = '/var/log/pure-ftpd'; if (!is_dir($logdir)) { mkdir($logdir, 0755, true); } - + /** * @link http://download.pureftpd.org/pub/pure-ftpd/doc/README * -b brokenclientscompatibility @@ -364,45 +364,47 @@ class installer extends installer_base * -E noanonymous * -O altlog : * -Z customerproof (Add safe guards against common customer mistakes ie. like chmod 0 on their own files) - * -D displaydotfiles + * -D displaydotfiles * -H dontresolve */ + + $content = preg_replace('/MISC_OTHER="[^"]+"/', 'MISC_OTHER="-b -A -E -Z -D -H -O clf:'.$logdir.'/transfer.log"', $content); - + $this->write_config_file($conf['pureftpd']['config_file'], $content); - } - - public function configure_powerdns() + } + + public function configure_powerdns() { global $conf; - + //* Create the database if(!$this->db->query('CREATE DATABASE IF NOT EXISTS '.$conf['powerdns']['database'].' DEFAULT CHARACTER SET '.$conf['mysql']['charset'])) { $this->error('Unable to create MySQL database: '.$conf['powerdns']['database'].'.'); } - + //* Create the ISPConfig database user in the local database - $query = 'GRANT ALL ON `'.$conf['powerdns']['database'].'` . * TO \''.$conf['mysql']['ispconfig_user'].'\'@\'localhost\';'; + $query = 'GRANT ALL ON `'.$conf['powerdns']['database'].'` . * TO \''.$conf['mysql']['ispconfig_user'].'\'@\'localhost\';'; if(!$this->db->query($query)) { $this->error('Unable to create user for powerdns database Error: '.$this->db->errorMessage); } - + //* Reload database privelages $this->db->query('FLUSH PRIVILEGES;'); - + //* load the powerdns databse dump if($conf['mysql']['admin_password'] == '') { - caselog("mysql --default-character-set=".$conf['mysql']['charset']." -h '".$conf['mysql']['host']."' -u '".$conf['mysql']['admin_user']."' '".$conf['powerdns']['database']."' < '".ISPC_INSTALL_ROOT."/install/sql/powerdns.sql' &> /dev/null", - __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql'); + caselog("mysql --default-character-set=".$conf['mysql']['charset']." -h '".$conf['mysql']['host']."' -u '".$conf['mysql']['admin_user']."' '".$conf['powerdns']['database']."' < '".ISPC_INSTALL_ROOT."/install/sql/powerdns.sql' &> /dev/null", + __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql'); } else { - caselog("mysql --default-character-set=".$conf['mysql']['charset']." -h '".$conf['mysql']['host']."' -u '".$conf['mysql']['admin_user']."' -p'".$conf['mysql']['admin_password']."' '".$conf['powerdns']['database']."' < '".ISPC_INSTALL_ROOT."/install/sql/powerdns.sql' &> /dev/null", - __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql'); + caselog("mysql --default-character-set=".$conf['mysql']['charset']." -h '".$conf['mysql']['host']."' -u '".$conf['mysql']['admin_user']."' -p'".$conf['mysql']['admin_password']."' '".$conf['powerdns']['database']."' < '".ISPC_INSTALL_ROOT."/install/sql/powerdns.sql' &> /dev/null", + __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql'); } - + //* Create the powerdns config file $content = $this->get_template_file('pdns.local', true, true); //* get contents & insert db cred $content = str_replace('{powerdns_database}', $conf['powerdns']['database'], $content); - + $this->write_config_file($conf["powerdns"]["config_dir"].'/'.$conf["powerdns"]["config_file"], $content, 600, 'root', 'root'); //* Create symlink to init script to start the correct config file @@ -410,26 +412,26 @@ class installer extends installer_base symlink($conf['init_scripts'].'/pdns', $conf['init_scripts'].'/'.$conf['powerdns']['init_script']); } } - + public function configure_bind() { global $conf; - //* Check if the zonefile directory has a slash at the end - $content=$conf['bind']['bind_zonefiles_dir']; - if(substr($content,-1,1) != '/') { - $content .= '/'; + //* Check if the zonefile directory has a slash at the end + $content=$conf['bind']['bind_zonefiles_dir']; + if(substr($content, -1, 1) != '/') { + $content .= '/'; } - + //* New default format of named.conf uses views. Check which version the system is using and include our zones file. $named_conf = rf($conf['bind']['named_conf_path']); - if (stripos($named_conf, 'include "'.$conf['bind']['named_conf_local_path'].'";') === false) + if (stripos($named_conf, 'include "'.$conf['bind']['named_conf_local_path'].'";') === false) { preg_match_all("/(?<=\n)view \"(?:public|internal)\" in \{.*\n\};/Us", $named_conf, $views); if (count($views[0]) == 2) { foreach ($views[0] as $view) { $named_conf = str_replace($view, substr($view, 0, -2)."include \"{$conf['bind']['named_conf_local_path']}\";\n};", $named_conf); } - + wf($conf['bind']['named_conf_path'], $named_conf); } else { @@ -437,48 +439,48 @@ class installer extends installer_base } } } - + public function configure_apache() - { + { global $conf; - + if($conf['apache']['installed'] == false) return; //* Create the logging directory for the vhost logfiles if (!is_dir($conf['ispconfig_log_dir'].'/httpd')) { mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true); } - - if (is_file($conf['suphp']['config_file'])) + + if (is_file($conf['suphp']['config_file'])) { $content = rf($conf['suphp']['config_file']); - + if (!preg_match('|^x-httpd-suphp=php:/usr/bin/php-cgi$|m', $content)) { - $content = preg_replace('/;Handler for php-scripts/',";Handler for php-scripts\nx-httpd-suphp=php:/usr/bin/php-cgi", $content); - $content = preg_replace('/;?umask=\d+/','umask=0022', $content); + $content = preg_replace('/;Handler for php-scripts/', ";Handler for php-scripts\nx-httpd-suphp=php:/usr/bin/php-cgi", $content); + $content = preg_replace('/;?umask=\d+/', 'umask=0022', $content); } - + $this->write_config_file($conf['suphp']['config_file'], $content); } - + //* Enable ISPConfig default vhost settings $default_vhost_path = $conf['apache']['vhost_conf_dir'].'/'.$conf['apache']['vhost_default']; - if (is_file($default_vhost_path)) + if (is_file($default_vhost_path)) { $content = rf($default_vhost_path); - + $content = preg_replace('/^#?\s*NameVirtualHost.*$/m', 'NameVirtualHost *:80', $content); $content = preg_replace('/]+>/', '', $content); - + $this->write_config_file($default_vhost_path, $content); } - + //* Generate default ssl certificates if (!is_dir($conf['apache']['ssl_dir'])) { mkdir($conf['apache']['ssl_dir']); } - - if ($conf['services']['mail'] == true) + + if ($conf['services']['mail'] == true) { copy($conf['postfix']['config_dir']."/smtpd.key", $conf['apache']['ssl_dir']."/server.key"); copy($conf['postfix']['config_dir']."/smtpd.cert", $conf['apache']['ssl_dir']."/server.crt"); @@ -489,76 +491,76 @@ class installer extends installer_base exec("openssl req -new -outform PEM -out {$conf['apache']['ssl_dir']}/server.crt -newkey rsa:2048 -nodes -keyout {$conf['apache']['ssl_dir']}/server.key -keyform PEM -days 365 -x509"); } } - - - + + + //* Copy the ISPConfig configuration include $content = $this->get_template_file('apache_ispconfig.conf', true); - + $records = $this->db->queryAllRecords("SELECT * FROM server_ip WHERE server_id = ".$conf["server_id"]." AND virtualhost = 'y'"); - if(is_array($records) && count($records) > 0) + if(is_array($records) && count($records) > 0) { foreach($records as $rec) { $content .= "NameVirtualHost ".$rec["ip_address"].":80\n"; $content .= "NameVirtualHost ".$rec["ip_address"].":443\n"; } } - + $this->write_config_file($conf['apache']['vhost_conf_dir'].'/000-ispconfig.conf', $content); - + //* Gentoo by default does not include .vhost files. Add include line to config file. $content = rf($conf['apache']['config_file']); if ( strpos($content, 'Include /etc/apache2/vhosts.d/*.vhost') === false ) { - $content = preg_replace('|(Include /etc/apache2/vhosts.d/\*.conf)|',"$1\nInclude /etc/apache2/vhosts.d/*.vhost", $content); + $content = preg_replace('|(Include /etc/apache2/vhosts.d/\*.conf)|', "$1\nInclude /etc/apache2/vhosts.d/*.vhost", $content); } - + $this->write_config_file($conf['apache']['config_file'], $content); - + //* make sure that webalizer finds its config file when it is directly in /etc - if(is_file('/etc/webalizer.conf') && !is_dir('/etc/webalizer')) + if(is_file('/etc/webalizer.conf') && !is_dir('/etc/webalizer')) { mkdir('/etc/webalizer', 0755); symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf'); } - - if(is_file('/etc/webalizer/webalizer.conf')) //* Change webalizer mode to incremental - { - replaceLine('/etc/webalizer/webalizer.conf','#IncrementalName','IncrementalName webalizer.current',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#Incremental','Incremental yes',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#HistoryName','HistoryName webalizer.hist',0,0); + + if(is_file('/etc/webalizer/webalizer.conf')) //* Change webalizer mode to incremental + { + replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental yes', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName webalizer.hist', 0, 0); } - + //* add a sshusers group - if (!is_group('sshusers')) + if (!is_group('sshusers')) { $command = 'groupadd sshusers'; caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - } - - public function configure_apps_vhost() + } + + public function configure_apps_vhost() { global $conf; - + //* Create the ispconfig apps vhost user and group if($conf['apache']['installed'] == true){ $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']); $apps_vhost_group = escapeshellcmd($conf['web']['apps_vhost_group']); $install_dir = escapeshellcmd($conf['web']['website_basedir'].'/apps'); - + $command = 'groupadd '.$apps_vhost_user; if ( !is_group($apps_vhost_group) ) { caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + $command = "useradd -g '$apps_vhost_group' -d $install_dir $apps_vhost_group"; if ( !is_user($apps_vhost_user) ) { caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + $command = 'adduser '.$conf['apache']['user'].' '.$apps_vhost_group; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + if(!@is_dir($install_dir)){ mkdir($install_dir, 0755, true); } else { @@ -566,41 +568,41 @@ class installer extends installer_base } chown($install_dir, $apps_vhost_user); chgrp($install_dir, $apps_vhost_group); - + //* Copy the apps vhost file $vhost_conf_dir = $conf['apache']['vhost_conf_dir']; $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir']; $apps_vhost_servername = ($conf['web']['apps_vhost_servername'] == '') ? '' : 'ServerName '.$conf['web']['apps_vhost_servername']; - + //* Dont just copy over the virtualhost template but add some custom settings $content = $this->get_template_file('apache_apps.vhost', true); - + $content = str_replace('{apps_vhost_ip}', $conf['web']['apps_vhost_ip'], $content); $content = str_replace('{apps_vhost_port}', $conf['web']['apps_vhost_port'], $content); $content = str_replace('{apps_vhost_dir}', $conf['web']['website_basedir'].'/apps', $content); $content = str_replace('{website_basedir}', $conf['web']['website_basedir'], $content); $content = str_replace('{apps_vhost_servername}', $apps_vhost_servername, $content); - + //* comment out the listen directive if port is 80 or 443 if($conf['web']['apps_vhost_ip'] == 80 or $conf['web']['apps_vhost_ip'] == 443) { $content = str_replace('{vhost_port_listen}', '#', $content); } else { $content = str_replace('{vhost_port_listen}', '', $content); } - + $this->write_config_file("$vhost_conf_dir/apps.vhost", $content); - - //if ( !is_file($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter') ) + + //if ( !is_file($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter') ) //{ - $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_apps_fcgi_starter.master', 'tpl/apache_apps_fcgi_starter.master'); - $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content); - $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content); - mkdir($conf['web']['website_basedir'].'/php-fcgi-scripts/apps', 0755, true); - //copy('tpl/apache_apps_fcgi_starter.master',$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter'); - wf($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter', $content); - exec('chmod +x '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter'); - exec('chown -R ispapps:ispapps '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps'); - + $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_apps_fcgi_starter.master', 'tpl/apache_apps_fcgi_starter.master'); + $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content); + $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content); + mkdir($conf['web']['website_basedir'].'/php-fcgi-scripts/apps', 0755, true); + //copy('tpl/apache_apps_fcgi_starter.master',$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter'); + wf($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter', $content); + exec('chmod +x '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter'); + exec('chown -R ispapps:ispapps '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps'); + //} } if($conf['nginx']['installed'] == true){ @@ -633,15 +635,15 @@ class installer extends installer_base // Dont just copy over the virtualhost template but add some custom settings $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/nginx_apps.vhost.master', 'tpl/nginx_apps.vhost.master'); - + if($conf['web']['apps_vhost_ip'] == '_default_'){ $apps_vhost_ip = ''; } else { $apps_vhost_ip = $conf['web']['apps_vhost_ip'].':'; } - + $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']); - if(substr($socket_dir,-1) != '/') $socket_dir .= '/'; + if(substr($socket_dir, -1) != '/') $socket_dir .= '/'; if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir); $fpm_socket = $socket_dir.'apps.sock'; $cgi_socket = escapeshellcmd($conf['nginx']['cgi_socket']); @@ -655,7 +657,7 @@ class installer extends installer_base $content = str_replace('{cgi_socket}', $cgi_socket, $content); wf($vhost_conf_dir.'/apps.vhost', $content); - + // PHP-FPM // Dont just copy over the php-fpm pool template but add some custom settings $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apps_php_fpm_pool.conf.master', 'tpl/apps_php_fpm_pool.conf.master'); @@ -670,84 +672,84 @@ class installer extends installer_base //* and create the symlink if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost'); if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) { - symlink($vhost_conf_dir.'/apps.vhost',$vhost_conf_enabled_dir.'/000-apps.vhost'); + symlink($vhost_conf_dir.'/apps.vhost', $vhost_conf_enabled_dir.'/000-apps.vhost'); } - + } } - - public function install_ispconfig() - { + + public function install_ispconfig() + { global $conf; - + $install_dir = $conf['ispconfig_install_dir']; - - //* Create the ISPConfig installation directory - if(!is_dir($install_dir)) + + //* Create the ISPConfig installation directory + if(!is_dir($install_dir)) { $command = "mkdir $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + //* Create a ISPConfig user and group - if (!is_group('ispconfig')) + if (!is_group('ispconfig')) { $command = 'groupadd ispconfig'; caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - - if (!is_user('ispconfig')) + + if (!is_user('ispconfig')) { $command = "useradd -g ispconfig -d $install_dir ispconfig"; caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + //* copy the ISPConfig interface part $command = "cp -rf ../interface $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* copy the ISPConfig server part $command = "cp -rf ../server $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - - + + //* Create the config file for ISPConfig interface $configfile = 'config.inc.php'; $content = $this->get_template_file($configfile, true, true); //* get contents & insert db cred - + $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content); $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content); $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content); $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content); - + $content = str_replace('{server_id}', $conf['server_id'], $content); $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content); $content = str_replace('{language}', $conf['language'], $content); $content = str_replace('{timezone}', $conf['timezone'], $content); $content = str_replace('{theme}', $conf['theme'], $content); $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content); - + $this->write_config_file("$install_dir/interface/lib/$configfile", $content); - + //* Create the config file for ISPConfig server $this->write_config_file("$install_dir/server/lib/$configfile", $content); - + //* Create the config file for remote-actions (but only, if it does not exist, because // the value is a autoinc-value and so changed by the remoteaction_core_module if (!file_exists($install_dir.'/server/lib/remote_action.inc.php')) { $content = ''; wf($install_dir.'/server/lib/remote_action.inc.php', $content); } - - // Enable the server modules and plugins. + + // Enable the server modules and plugins. // TODO: Implement a selector which modules and plugins shall be enabled. $dir = $install_dir.'/server/mods-available/'; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { - if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') { - include_once($install_dir.'/server/mods-available/'.$file); - $module_name = substr($file,0,-8); + if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') { + include_once $install_dir.'/server/mods-available/'.$file; + $module_name = substr($file, 0, -8); $tmp = new $module_name; if($tmp->onInstall()) { if(!@is_link($install_dir.'/server/mods-enabled/'.$file)) { @@ -774,11 +776,11 @@ class installer extends installer_base while (($file = readdir($dh)) !== false) { if($conf['apache']['installed'] == true && $file == 'nginx_plugin.inc.php') continue; if($conf['nginx']['installed'] == true && $file == 'apache2_plugin.inc.php') continue; - if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') { - include_once($install_dir.'/server/plugins-available/'.$file); - $plugin_name = substr($file,0,-8); + if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') { + include_once $install_dir.'/server/plugins-available/'.$file; + $plugin_name = substr($file, 0, -8); $tmp = new $plugin_name; - if(method_exists($tmp,'onInstall') && $tmp->onInstall()) { + if(method_exists($tmp, 'onInstall') && $tmp->onInstall()) { if(!@is_link($install_dir.'/server/plugins-enabled/'.$file)) { @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-enabled/'.$file); } @@ -794,7 +796,7 @@ class installer extends installer_base closedir($dh); } } - + //* Update the server config $mail_server_enabled = ($conf['services']['mail'])?1:0; $web_server_enabled = ($conf['services']['web'])?1:0; @@ -802,16 +804,16 @@ class installer extends installer_base $file_server_enabled = ($conf['services']['file'])?1:0; $db_server_enabled = ($conf['services']['db'])?1:0; $vserver_server_enabled = ($conf['services']['vserver'])?1:0; - - $sql = "UPDATE `server` SET mail_server = '$mail_server_enabled', web_server = '$web_server_enabled', dns_server = '$dns_server_enabled', file_server = '$file_server_enabled', db_server = '$db_server_enabled', vserver_server = '$vserver_server_enabled' WHERE server_id = ".intval($conf['server_id']); - + + $sql = "UPDATE `server` SET mail_server = '$mail_server_enabled', web_server = '$web_server_enabled', dns_server = '$dns_server_enabled', file_server = '$file_server_enabled', db_server = '$db_server_enabled', vserver_server = '$vserver_server_enabled' WHERE server_id = ".intval($conf['server_id']); + if($conf['mysql']['master_slave_setup'] == 'y') { $this->dbmaster->query($sql); $this->db->query($sql); } else { $this->db->query($sql); } - + //* Chmod the files $command = "chmod -R 750 $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); @@ -819,40 +821,40 @@ class installer extends installer_base //* chown the files to the ispconfig user and group $command = "chown -R ispconfig:ispconfig $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* Make the global language file directory group writable exec("chmod -R 770 $install_dir/interface/lib/lang"); - + //* Make the temp directory for language file exports writable if(is_dir($install_dir.'/interface/web/temp')) { exec("chmod -R 770 $install_dir/interface/web/temp"); } - - //* Make all interface language file directories group writable + + //* Make all interface language file directories group writable $handle = @opendir($install_dir.'/interface/web'); - while ($file = @readdir ($handle)) { - if ($file != '.' && $file != '..') { - if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) { + while ($file = @readdir($handle)) { + if ($file != '.' && $file != '..') { + if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) { $handle2 = opendir($install_dir.'/interface/web'.'/'.$file.'/lib/lang'); - chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang',0770); - while ($lang_file = @readdir ($handle2)) { + chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang', 0770); + while ($lang_file = @readdir($handle2)) { if ($lang_file != '.' && $lang_file != '..') { - chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file,0770); + chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file, 0770); } } } } } - + //* Make the APS directories group writable exec("chmod -R 770 $install_dir/interface/web/sites/aps_meta_packages"); exec("chmod -R 770 $install_dir/server/aps_packages"); - - //* make sure that the server config file (not the interface one) is only readable by the root user + + //* make sure that the server config file (not the interface one) is only readable by the root user chmod($install_dir.'/server/lib/config.inc.php', 0600); chown($install_dir.'/server/lib/config.inc.php', 'root'); chgrp($install_dir.'/server/lib/config.inc.php', 'root'); - + //* Make sure thet the interface config file is readable by user ispconfig only chmod($install_dir.'/interface/lib/config.inc.php', 0600); chown($install_dir.'/interface/lib/config.inc.php', 'ispconfig'); @@ -867,12 +869,12 @@ class installer extends installer_base chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root'); chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root'); } - + if(is_dir($install_dir.'/interface/invoices')) { exec('chmod -R 770 '.escapeshellarg($install_dir.'/interface/invoices')); exec('chown -R ispconfig:ispconfig '.escapeshellarg($install_dir.'/interface/invoices')); } - + // TODO: FIXME: add the www-data user to the ispconfig group. This is just for testing // and must be fixed as this will allow the apache user to read the ispconfig files. // Later this must run as own apache server or via suexec! @@ -892,23 +894,23 @@ class installer extends installer_base caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } } - + //* Make the shell scripts executable $command = "chmod +x $install_dir/server/scripts/*.sh"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + if($conf['apache']['installed'] == true && $this->install_ispconfig_interface == true){ //* Copy the ISPConfig vhost for the controlpanel $content = $this->get_template_file("apache_ispconfig.vhost", true); $content = str_replace('{vhost_port}', $conf['apache']['vhost_port'], $content); - + //* comment out the listen directive if port is 80 or 443 if ($conf['apache']['vhost_port'] == 80 or $conf['apache']['vhost_port'] == 443) { $content = str_replace('{vhost_port_listen}', '#', $content); } else { $content = str_replace('{vhost_port_listen}', '', $content); } - + if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) { $content = str_replace('{ssl_comment}', '', $content); } else { @@ -919,10 +921,10 @@ class installer extends installer_base } else { $content = str_replace('{ssl_bundle_comment}', '#', $content); } - + $vhost_path = $conf['apache']['vhost_conf_dir'].'/ispconfig.vhost'; $this->write_config_file($vhost_path, $content); - + if(!is_file('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter')) { $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig_fcgi_starter.master', 'tpl/apache_ispconfig_fcgi_starter.master'); $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content); @@ -931,7 +933,7 @@ class installer extends installer_base wf('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter', $content); exec('chmod +x /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter'); chmod('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter', 0755); - @symlink($install_dir.'/interface/web','/var/www/ispconfig'); + @symlink($install_dir.'/interface/web', '/var/www/ispconfig'); exec('chown -R ispconfig:ispconfig /var/www/php-fcgi-scripts/ispconfig'); } } @@ -944,7 +946,7 @@ class installer extends installer_base // Dont just copy over the virtualhost template but add some custom settings $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/nginx_ispconfig.vhost.master', 'tpl/nginx_ispconfig.vhost.master'); $content = str_replace('{vhost_port}', $conf['nginx']['vhost_port'], $content); - + if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) { $content = str_replace('{ssl_on}', ' on', $content); $content = str_replace('{ssl_comment}', '', $content); @@ -954,19 +956,19 @@ class installer extends installer_base $content = str_replace('{ssl_comment}', '#', $content); $content = str_replace('{fastcgi_ssl}', 'off', $content); } - + $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']); - if(substr($socket_dir,-1) != '/') $socket_dir .= '/'; + if(substr($socket_dir, -1) != '/') $socket_dir .= '/'; if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir); $fpm_socket = $socket_dir.'ispconfig.sock'; - + //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content); $content = str_replace('{fpm_socket}', $fpm_socket, $content); wf($vhost_conf_dir.'/ispconfig.vhost', $content); - + unset($content); - + // PHP-FPM // Dont just copy over the php-fpm pool template but add some custom settings $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/php_fpm_pool.conf.master', 'tpl/php_fpm_pool.conf.master'); @@ -982,31 +984,31 @@ class installer extends installer_base if($this->is_update == false) { if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost'); if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) { - symlink($vhost_conf_dir.'/ispconfig.vhost',$vhost_conf_enabled_dir.'/000-ispconfig.vhost'); + symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost'); } } } - + //* Install the update script if (is_file('/usr/local/bin/ispconfig_update_from_svn.sh')) { unlink('/usr/local/bin/ispconfig_update_from_svn.sh'); } - + chown($install_dir.'/server/scripts/update_from_svn.sh', 'root'); chmod($install_dir.'/server/scripts/update_from_svn.sh', 0700); chown($install_dir.'/server/scripts/update_from_tgz.sh', 'root'); chmod($install_dir.'/server/scripts/update_from_tgz.sh', 0700); chown($install_dir.'/server/scripts/ispconfig_update.sh', 'root'); chmod($install_dir.'/server/scripts/ispconfig_update.sh', 0700); - + if (!is_link('/usr/local/bin/ispconfig_update_from_svn.sh')) { symlink($install_dir.'/server/scripts/ispconfig_update.sh', '/usr/local/bin/ispconfig_update_from_svn.sh'); } - + if (!is_link('/usr/local/bin/ispconfig_update.sh')) { symlink($install_dir.'/server/scripts/ispconfig_update.sh', '/usr/local/bin/ispconfig_update.sh'); } - + //* Make the logs readable for the ispconfig user if (is_file('/var/log/maillog')) { exec('chmod +r /var/log/maillog'); @@ -1020,7 +1022,7 @@ class installer extends installer_base if (is_file('/var/log/clamav/freshclam.log')) { exec('chmod +r /var/log/clamav/freshclam.log'); } - + //* Create the ispconfig log directory if (!is_dir($conf['ispconfig_log_dir'])) { mkdir($conf['ispconfig_log_dir']); @@ -1028,25 +1030,26 @@ class installer extends installer_base if (!is_file($conf['ispconfig_log_dir'].'/ispconfig.log')) { touch($conf['ispconfig_log_dir'].'/ispconfig.log'); } - + //* Create the ispconfig auth log file and set uid/gid if(!is_file($conf['ispconfig_log_dir'].'/auth.log')) { touch($conf['ispconfig_log_dir'].'/auth.log'); } exec('chown ispconfig:ispconfig '. $conf['ispconfig_log_dir'].'/auth.log'); exec('chmod 660 '. $conf['ispconfig_log_dir'].'/auth.log'); - + rename($install_dir.'/server/scripts/run-getmail.sh', '/usr/local/bin/run-getmail.sh'); - + if (is_user('getmail')) { chown('/usr/local/bin/run-getmail.sh', 'getmail'); } chmod('/usr/local/bin/run-getmail.sh', 0744); - + //* Remove Domain module as its functions are available in the client module now if(@is_dir('/usr/local/ispconfig/interface/web/domain')) exec('rm -rf /usr/local/ispconfig/interface/web/domain'); - - } + + } + } ?> diff --git a/install/dist/lib/opensuse.lib.php b/install/dist/lib/opensuse.lib.php index e087772e46990e97ff02439daa57870a42408368..e104f4abe22699c7e5896a9689d23b04a96c6399 100644 --- a/install/dist/lib/opensuse.lib.php +++ b/install/dist/lib/opensuse.lib.php @@ -58,7 +58,7 @@ class installer_dist extends installer_base { } } } - + if(!is_file('/var/lib/mailman/data/transport-mailman')) touch('/var/lib/mailman/data/transport-mailman'); exec('/usr/sbin/postmap /var/lib/mailman/data/transport-mailman'); @@ -69,13 +69,13 @@ class installer_dist extends installer_base { $domainAll = $this->db->queryAllRecords("SELECT domain FROM mail_mailinglist GROUP BY domain"); if(is_array($domainAll)) { - foreach($domainAll as $domain) - { - if ($domainAll[0]['domain'] == $domain['domain']) - $virtual_domains .= "'".$domain['domain']."'"; - else - $virtual_domains .= ", '".$domain['domain']."'"; - } + foreach($domainAll as $domain) + { + if ($domainAll[0]['domain'] == $domain['domain']) + $virtual_domains .= "'".$domain['domain']."'"; + else + $virtual_domains .= ", '".$domain['domain']."'"; + } } } else @@ -87,78 +87,78 @@ class installer_dist extends installer_base { $content = str_replace('{virtual_domains}', $virtual_domains, $content); wf($full_file_name, $content); - + //* Write virtual_to_transport.sh script $config_dir = $conf['mailman']['config_dir'].'/'; $full_file_name = $config_dir.'virtual_to_transport.sh'; - + //* Backup exiting virtual_to_transport.sh script if(is_file($full_file_name)) { copy($full_file_name, $config_dir.'virtual_to_transport.sh~'); } - + if(is_dir('/etc/mailman')) { if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name); - } else { - copy('tpl/mailman-virtual_to_transport.sh',$full_file_name); - } - chgrp($full_file_name,'mailman'); - chmod($full_file_name,0750); - } - + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name); + } else { + copy('tpl/mailman-virtual_to_transport.sh', $full_file_name); + } + chgrp($full_file_name, 'mailman'); + chmod($full_file_name, 0750); + } + //* Create aliasaes exec('/usr/lib/mailman/bin/genaliases 2>/dev/null'); } - + function configure_postfix($options = '') - { - global $conf; + { + global $conf; $cf = $conf['postfix']; $config_dir = $cf['config_dir']; - + if(!is_dir($config_dir)){ - $this->error("The postfix configuration directory '$config_dir' does not exist."); - } - + $this->error("The postfix configuration directory '$config_dir' does not exist."); + } + //* mysql-virtual_domains.cf - $this->process_postfix_config('mysql-virtual_domains.cf'); + $this->process_postfix_config('mysql-virtual_domains.cf'); //* mysql-virtual_forwardings.cf - $this->process_postfix_config('mysql-virtual_forwardings.cf'); + $this->process_postfix_config('mysql-virtual_forwardings.cf'); //* mysql-virtual_mailboxes.cf - $this->process_postfix_config('mysql-virtual_mailboxes.cf'); + $this->process_postfix_config('mysql-virtual_mailboxes.cf'); //* mysql-virtual_email2email.cf - $this->process_postfix_config('mysql-virtual_email2email.cf'); + $this->process_postfix_config('mysql-virtual_email2email.cf'); //* mysql-virtual_transports.cf - $this->process_postfix_config('mysql-virtual_transports.cf'); + $this->process_postfix_config('mysql-virtual_transports.cf'); //* mysql-virtual_recipient.cf - $this->process_postfix_config('mysql-virtual_recipient.cf'); + $this->process_postfix_config('mysql-virtual_recipient.cf'); //* mysql-virtual_sender.cf - $this->process_postfix_config('mysql-virtual_sender.cf'); + $this->process_postfix_config('mysql-virtual_sender.cf'); //* mysql-virtual_client.cf - $this->process_postfix_config('mysql-virtual_client.cf'); - + $this->process_postfix_config('mysql-virtual_client.cf'); + //* mysql-virtual_relaydomains.cf - $this->process_postfix_config('mysql-virtual_relaydomains.cf'); - + $this->process_postfix_config('mysql-virtual_relaydomains.cf'); + //* mysql-virtual_relayrecipientmaps.cf - $this->process_postfix_config('mysql-virtual_relayrecipientmaps.cf'); + $this->process_postfix_config('mysql-virtual_relayrecipientmaps.cf'); //* Changing mode and group of the new created config files. caselog('chmod o= '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null', - __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed'); - caselog('chgrp '.$cf['group'].' '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null', - __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed'); - + __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed'); + caselog('chgrp '.$cf['group'].' '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null', + __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed'); + if(!is_dir($cf['vmail_mailbox_base'])) mkdir($cf['vmail_mailbox_base']); - + //* Creating virtual mail user and group if(is_group($cf['vmail_groupname'])) { $command = 'groupmod -g '.$cf['vmail_groupid'].' '.$cf['vmail_groupname']; @@ -167,7 +167,7 @@ class installer_dist extends installer_base { $command = 'groupadd -g '.$cf['vmail_groupid'].' '.$cf['vmail_groupname']; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + if(is_user($cf['vmail_username'])) { $command = 'usermod -g '.$cf['vmail_groupname'].' -u '.$cf['vmail_userid'].' -d '.$cf['vmail_mailbox_base'].' -s /bin/bash '.$cf['vmail_username']; caselog("$command &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); @@ -175,9 +175,9 @@ class installer_dist extends installer_base { $command = 'useradd -g '.$cf['vmail_groupname'].' -u '.$cf['vmail_userid'].' '.$cf['vmail_username'].' -d '.$cf['vmail_mailbox_base'].' -m'; caselog("$command &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + if($cf['vmail_mailbox_base'] != '' && strlen($cf['vmail_mailbox_base']) >= 10 && $this->is_update === false) exec('chown -R '.$cf['vmail_username'].':'.$cf['vmail_groupname'].' '.$cf['vmail_mailbox_base']); - + //* These postconf commands will be executed on installation and update $server_ini_rec = $this->db->queryOneRecord("SELECT config FROM server WHERE server_id = ".$conf['server_id']); $server_ini_array = ini_to_array(stripslashes($server_ini_rec['config'])); @@ -186,40 +186,40 @@ class installer_dist extends installer_base { //* If there are RBL's defined, format the list and add them to smtp_recipient_restrictions to prevent removeal after an update $rbl_list = ''; if (@isset($server_ini_array['mail']['realtime_blackhole_list']) && $server_ini_array['mail']['realtime_blackhole_list'] != '') { - $rbl_hosts = explode(",",str_replace(" ", "", $server_ini_array['mail']['realtime_blackhole_list'])); + $rbl_hosts = explode(",", str_replace(" ", "", $server_ini_array['mail']['realtime_blackhole_list'])); foreach ($rbl_hosts as $key => $value) { $rbl_list .= ", reject_rbl_client ". $value; } } unset($rbl_hosts); unset($server_ini_array); - + //* These postconf commands will be executed on installation and update - $postconf_placeholders = array('{config_dir}' => $config_dir, - '{vmail_mailbox_base}' => $cf['vmail_mailbox_base'], - '{vmail_userid}' => $cf['vmail_userid'], - '{vmail_groupid}' => $cf['vmail_groupid'], - '{rbl_list}' => $rbl_list); - - $postconf_tpl = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/opensuse_postfix.conf.master', 'tpl/opensuse_postfix.conf.master'); - $postconf_tpl = strtr($postconf_tpl, $postconf_placeholders); - $postconf_commands = array_filter(explode("\n", $postconf_tpl)); // read and remove empty lines - + $postconf_placeholders = array('{config_dir}' => $config_dir, + '{vmail_mailbox_base}' => $cf['vmail_mailbox_base'], + '{vmail_userid}' => $cf['vmail_userid'], + '{vmail_groupid}' => $cf['vmail_groupid'], + '{rbl_list}' => $rbl_list); + + $postconf_tpl = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/opensuse_postfix.conf.master', 'tpl/opensuse_postfix.conf.master'); + $postconf_tpl = strtr($postconf_tpl, $postconf_placeholders); + $postconf_commands = array_filter(explode("\n", $postconf_tpl)); // read and remove empty lines + //* These postconf commands will be executed on installation only if($this->is_update == false) { - $postconf_commands = array_merge($postconf_commands,array( - 'myhostname = '.$conf['hostname'], - 'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain', - 'mynetworks = 127.0.0.0/8 [::1]/128' - )); + $postconf_commands = array_merge($postconf_commands, array( + 'myhostname = '.$conf['hostname'], + 'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain', + 'mynetworks = 127.0.0.0/8 [::1]/128' + )); } - + //* Create the header and body check files touch($config_dir.'/header_checks'); touch($config_dir.'/mime_header_checks'); touch($config_dir.'/nested_header_checks'); touch($config_dir.'/body_checks'); - + //* Create the mailman files if(!is_dir('/var/lib/mailman/data')) exec('mkdir -p /var/lib/mailman/data'); if(!is_file('/var/lib/mailman/data/aliases')) touch('/var/lib/mailman/data/aliases'); @@ -228,78 +228,78 @@ class installer_dist extends installer_base { exec('postmap /var/lib/mailman/data/virtual-mailman'); if(!is_file('/var/lib/mailman/data/transport-mailman')) touch('/var/lib/mailman/data/transport-mailman'); exec('/usr/sbin/postmap /var/lib/mailman/data/transport-mailman'); - + //* Make a backup copy of the main.cf file copy($config_dir.'/main.cf', $config_dir.'/main.cf~'); - + //* Executing the postconf commands foreach($postconf_commands as $cmd) { $command = "postconf -e '$cmd'"; caselog($command." &> /dev/null", __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command); } - - if(!stristr($options,'dont-create-certs')) { + + if(!stristr($options, 'dont-create-certs')) { //* Create the SSL certificate $command = 'cd '.$config_dir.'; ' - .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:2048 -nodes -keyout smtpd.key -keyform PEM -days 365 -x509'; + .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:2048 -nodes -keyout smtpd.key -keyform PEM -days 365 -x509'; exec($command); - + $command = 'chmod o= '.$config_dir.'/smtpd.key'; caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command); } - + //** We have to change the permissions of the courier authdaemon directory to make it accessible for maildrop. $command = 'chmod 755 /var/run/authdaemon.courier-imap'; caselog($command.' &> /dev/null', __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command); - + //* Changing maildrop lines in posfix master.cf if(is_file($config_dir.'/master.cf')){ - copy($config_dir.'/master.cf', $config_dir.'/master.cf~'); - } + copy($config_dir.'/master.cf', $config_dir.'/master.cf~'); + } if(is_file($config_dir.'/master.cf~')){ - exec('chmod 400 '.$config_dir.'/master.cf~'); - } + exec('chmod 400 '.$config_dir.'/master.cf~'); + } $configfile = $config_dir.'/master.cf'; $content = rf($configfile); - - $content = str_replace(' flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}', - ' flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d ${recipient} ${extension} ${recipient} ${user} ${nexthop} ${sender}', - $content); - - $content = str_replace(' flags=DRhu user=vmail argv=/usr/local/bin/maildrop -d ${recipient}', - ' flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d ${recipient} ${extension} ${recipient} ${user} ${nexthop} ${sender}', - $content); - + + $content = str_replace(' flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}', + ' flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d ${recipient} ${extension} ${recipient} ${user} ${nexthop} ${sender}', + $content); + + $content = str_replace(' flags=DRhu user=vmail argv=/usr/local/bin/maildrop -d ${recipient}', + ' flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d ${recipient} ${extension} ${recipient} ${user} ${nexthop} ${sender}', + $content); + // enable tlsmanager - $content = str_replace('#tlsmgr unix - - n 1000? 1 tlsmgr','tlsmgr unix - - n 1000? 1 tlsmgr',$content); - + $content = str_replace('#tlsmgr unix - - n 1000? 1 tlsmgr', 'tlsmgr unix - - n 1000? 1 tlsmgr', $content); + wf($configfile, $content); - + //* Writing the Maildrop mailfilter file $configfile = 'mailfilter'; if(is_file($cf['vmail_mailbox_base'].'/.'.$configfile)){ - copy($cf['vmail_mailbox_base'].'/.'.$configfile, $cf['vmail_mailbox_base'].'/.'.$configfile.'~'); - } + copy($cf['vmail_mailbox_base'].'/.'.$configfile, $cf['vmail_mailbox_base'].'/.'.$configfile.'~'); + } $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/$configfile.master"); $content = str_replace('{dist_postfix_vmail_mailbox_base}', $cf['vmail_mailbox_base'], $content); wf($cf['vmail_mailbox_base'].'/.'.$configfile, $content); - + //* Create the directory for the custom mailfilters $command = 'mkdir '.$cf['vmail_mailbox_base'].'/mailfilters'; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* Chmod and chown the .mailfilter file $command = 'chown -R '.$cf['vmail_username'].':'.$cf['vmail_groupname'].' '.$cf['vmail_mailbox_base'].'/.mailfilter'; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + $command = 'chmod -R 600 '.$cf['vmail_mailbox_base'].'/.mailfilter'; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + } - + public function configure_saslauthd() { global $conf; - + /* $configfile = 'sasl_smtpd.conf'; if(is_file('/etc/sasl2/smtpd.conf')) copy('/etc/sasl2/smtpd.conf','/etc/sasl2/smtpd.conf~'); @@ -311,14 +311,14 @@ class installer_dist extends installer_base { $content = str_replace('{mysql_server_ip}',$conf['mysql']['ip'],$content); wf('/etc/sasl2/smtpd.conf',$content); */ - + // TODO: Chmod and chown on the config file - - + + /* // Create the spool directory exec('mkdir -p /var/spool/postfix/var/run/saslauthd'); - + // Edit the file /etc/default/saslauthd $configfile = $conf["saslauthd"]["config"]; if(is_file($configfile)) copy($configfile,$configfile.'~'); @@ -328,22 +328,22 @@ class installer_dist extends installer_base { $content = str_replace('OPTIONS="-c"','OPTIONS="-m /var/spool/postfix/var/run/saslauthd -r"',$content); wf($configfile,$content); */ - + // Edit the file /etc/init.d/saslauthd $configfile = $conf["init_scripts"].'/'.$conf["saslauthd"]["init_script"]; $content = rf($configfile); - $content = str_replace('/sbin/startproc $AUTHD_BIN -a $SASLAUTHD_AUTHMECH -n $SASLAUTHD_THREADS > /dev/null 2>&1','/sbin/startproc $AUTHD_BIN -r -a $SASLAUTHD_AUTHMECH -n $SASLAUTHD_THREADS > /dev/null 2>&1',$content); - $content = str_replace('/sbin/startproc $AUTHD_BIN $SASLAUTHD_PARAMS -a $SASLAUTHD_AUTHMECH -n $SASLAUTHD_THREADS > /dev/null 2>&1','/sbin/startproc $AUTHD_BIN $SASLAUTHD_PARAMS -r -a $SASLAUTHD_AUTHMECH -n $SASLAUTHD_THREADS > /dev/null 2>&1',$content); - - - if(is_file($configfile)) wf($configfile,$content); - - - + $content = str_replace('/sbin/startproc $AUTHD_BIN -a $SASLAUTHD_AUTHMECH -n $SASLAUTHD_THREADS > /dev/null 2>&1', '/sbin/startproc $AUTHD_BIN -r -a $SASLAUTHD_AUTHMECH -n $SASLAUTHD_THREADS > /dev/null 2>&1', $content); + $content = str_replace('/sbin/startproc $AUTHD_BIN $SASLAUTHD_PARAMS -a $SASLAUTHD_AUTHMECH -n $SASLAUTHD_THREADS > /dev/null 2>&1', '/sbin/startproc $AUTHD_BIN $SASLAUTHD_PARAMS -r -a $SASLAUTHD_AUTHMECH -n $SASLAUTHD_THREADS > /dev/null 2>&1', $content); + + + if(is_file($configfile)) wf($configfile, $content); + + + } - + public function configure_pam() - { + { global $conf; $pam = $conf['pam']; //* configure pam for SMTP authentication agains the ispconfig database @@ -361,65 +361,65 @@ class installer_dist extends installer_base { if(is_file("$pam/smtp")) exec("chmod o= $pam/smtp"); //exec("chmod 660 $pam/smtp"); //exec("chown root:root $pam/smtp"); - + } - + public function configure_courier() - { + { global $conf; $config_dir = $conf['courier']['config_dir']; //* authmysqlrc $configfile = 'authmysqlrc'; if(is_file("$config_dir/$configfile")){ - copy("$config_dir/$configfile", "$config_dir/$configfile~"); - } + copy("$config_dir/$configfile", "$config_dir/$configfile~"); + } exec("chmod 400 $config_dir/$configfile~"); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/$configfile.master"); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); wf("$config_dir/$configfile", $content); - + exec("chmod 660 $config_dir/$configfile"); exec("chown root:root $config_dir/$configfile"); - + //* authdaemonrc $configfile = $conf['courier']['config_dir'].'/authdaemonrc'; if(is_file($configfile)){ - copy($configfile, $configfile.'~'); - } + copy($configfile, $configfile.'~'); + } if(is_file($configfile.'~')){ - exec('chmod 400 '.$configfile.'~'); - } + exec('chmod 400 '.$configfile.'~'); + } $content = rf($configfile); $content = str_replace('authmodulelist=', 'authmodulelist="authmysql"', $content); wf($configfile, $content); } - + public function configure_dovecot() - { + { global $conf; - + $config_dir = $conf['dovecot']['config_dir']; - + //* Configure master.cf and add a line for deliver if(is_file($config_dir.'/master.cf')){ - copy($config_dir.'/master.cf', $config_dir.'/master.cf~2'); - } + copy($config_dir.'/master.cf', $config_dir.'/master.cf~2'); + } if(is_file($config_dir.'/master.cf~')){ - exec('chmod 400 '.$config_dir.'/master.cf~2'); - } + exec('chmod 400 '.$config_dir.'/master.cf~2'); + } $content = rf($conf["postfix"]["config_dir"].'/master.cf'); // Only add the content if we had not addded it before - if(!stristr($content,"dovecot/deliver")) { + if(!stristr($content, "dovecot/deliver")) { $deliver_content = 'dovecot unix - n n - - pipe'."\n".' flags=DROhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${user}@${nexthop}'; - af($conf["postfix"]["config_dir"].'/master.cf',$deliver_content); + af($conf["postfix"]["config_dir"].'/master.cf', $deliver_content); } unset($content); unset($deliver_content); - - + + //* Reconfigure postfix to use dovecot authentication // Adding the amavisd commands to the postfix configuration $postconf_commands = array ( @@ -429,115 +429,115 @@ class installer_dist extends installer_base { 'smtpd_sasl_path = private/auth', 'receive_override_options = no_address_mappings' ); - + // Make a backup copy of the main.cf file - copy($conf["postfix"]["config_dir"].'/main.cf',$conf["postfix"]["config_dir"].'/main.cf~3'); - + copy($conf["postfix"]["config_dir"].'/main.cf', $conf["postfix"]["config_dir"].'/main.cf~3'); + // Executing the postconf commands foreach($postconf_commands as $cmd) { $command = "postconf -e '$cmd'"; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + //* backup dovecot.conf $configfile = 'dovecot.conf'; if(is_file("$config_dir/$configfile")){ - copy("$config_dir/$configfile", "$config_dir/$configfile~"); - } - + copy("$config_dir/$configfile", "$config_dir/$configfile~"); + } + //* Get the dovecot version - exec('dovecot --version',$tmp); - $parts = explode('.',trim($tmp[0])); + exec('dovecot --version', $tmp); + $parts = explode('.', trim($tmp[0])); $dovecot_version = $parts[0]; unset($tmp); unset($parts); - + //* Copy dovecot configuration file if($dovecot_version == 2) { - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/opensuse_dovecot2.conf.master')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/opensuse_dovecot2.conf.master', $config_dir.'/'.$configfile); - } else { - copy('tpl/opensuse_dovecot2.conf.master',$config_dir.'/'.$configfile); - } + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/opensuse_dovecot2.conf.master')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/opensuse_dovecot2.conf.master', $config_dir.'/'.$configfile); + } else { + copy('tpl/opensuse_dovecot2.conf.master', $config_dir.'/'.$configfile); + } } else { - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/opensuse_dovecot.conf.master')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/opensuse_dovecot.conf.master', $config_dir.'/'.$configfile); - } else { - copy('tpl/opensuse_dovecot.conf.master',$config_dir.'/'.$configfile); - } + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/opensuse_dovecot.conf.master')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/opensuse_dovecot.conf.master', $config_dir.'/'.$configfile); + } else { + copy('tpl/opensuse_dovecot.conf.master', $config_dir.'/'.$configfile); + } } - + //* dovecot-sql.conf $configfile = 'dovecot-sql.conf'; if(is_file("$config_dir/$configfile")){ - copy("$config_dir/$configfile", "$config_dir/$configfile~"); + copy("$config_dir/$configfile", "$config_dir/$configfile~"); exec("chmod 400 $config_dir/$configfile~"); - } - + } + $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/opensuse_dovecot-sql.conf.master', "tpl/opensuse_dovecot-sql.conf.master"); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); wf("$config_dir/$configfile", $content); - + exec("chmod 600 $config_dir/$configfile"); exec("chown root:root $config_dir/$configfile"); } - + public function configure_amavis() { global $conf; - + // amavisd user config file $configfile = 'opensuse_amavisd_conf'; - if(is_file($conf["amavis"]["config_dir"].'/amavisd.conf')) @copy($conf["amavis"]["config_dir"].'/amavisd.conf',$conf["amavis"]["config_dir"].'/amavisd.conf~'); + if(is_file($conf["amavis"]["config_dir"].'/amavisd.conf')) @copy($conf["amavis"]["config_dir"].'/amavisd.conf', $conf["amavis"]["config_dir"].'/amavisd.conf~'); if(is_file($conf["amavis"]["config_dir"].'/amavisd.conf~')) exec('chmod 400 '.$conf["amavis"]["config_dir"].'/amavisd.conf~'); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/".$configfile.".master"); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_port}',$conf["mysql"]["port"],$content); - $content = str_replace('{mysql_server_ip}',$conf['mysql']['ip'],$content); - wf($conf["amavis"]["config_dir"].'/amavisd.conf',$content); - - + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_port}', $conf["mysql"]["port"], $content); + $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content); + wf($conf["amavis"]["config_dir"].'/amavisd.conf', $content); + + // Adding the amavisd commands to the postfix configuration $postconf_commands = array ( 'content_filter = amavis:[127.0.0.1]:10024', 'receive_override_options = no_address_mappings' ); - + // Make a backup copy of the main.cf file - copy($conf["postfix"]["config_dir"].'/main.cf',$conf["postfix"]["config_dir"].'/main.cf~2'); - + copy($conf["postfix"]["config_dir"].'/main.cf', $conf["postfix"]["config_dir"].'/main.cf~2'); + // Executing the postconf commands foreach($postconf_commands as $cmd) { $command = "postconf -e '$cmd'"; caselog($command." &> /dev/null", __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + // Append the configuration for amavisd to the master.cf file - if(is_file($conf["postfix"]["config_dir"].'/master.cf')) copy($conf["postfix"]["config_dir"].'/master.cf',$conf["postfix"]["config_dir"].'/master.cf~'); + if(is_file($conf["postfix"]["config_dir"].'/master.cf')) copy($conf["postfix"]["config_dir"].'/master.cf', $conf["postfix"]["config_dir"].'/master.cf~'); $content = rf($conf["postfix"]["config_dir"].'/master.cf'); // Only add the content if we had not addded it before - if(!stristr($content,"127.0.0.1:10025")) { + if(!stristr($content, "127.0.0.1:10025")) { unset($content); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/master_cf_amavis.master', "tpl/master_cf_amavis.master"); - af($conf["postfix"]["config_dir"].'/master.cf',$content); + af($conf["postfix"]["config_dir"].'/master.cf', $content); } unset($content); - + // Add the clamav user to the vscan group exec('groupmod --add-user clamav vscan'); - - + + } - + public function configure_spamassassin() - { + { global $conf; - + //* Enable spamasasssin on debian and ubuntu /* $configfile = '/etc/default/spamassassin'; @@ -549,40 +549,40 @@ class installer_dist extends installer_base { wf($configfile, $content); */ } - + public function configure_getmail() - { + { global $conf; - + $config_dir = $conf['getmail']['config_dir']; - + if(!is_dir($config_dir)) exec("mkdir -p ".escapeshellcmd($config_dir)); $command = "useradd -d $config_dir getmail"; if(!is_user('getmail')) caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + $command = "chown -R getmail $config_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + $command = "chmod -R 700 $config_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - - + + public function configure_pureftpd() - { + { global $conf; - + $config_dir = $conf['pureftpd']['config_dir']; //* configure pam for SMTP authentication agains the ispconfig database $configfile = 'db/mysql.conf'; if(is_file("$config_dir/$configfile")){ - copy("$config_dir/$configfile", "$config_dir/$configfile~"); - } + copy("$config_dir/$configfile", "$config_dir/$configfile~"); + } if(is_file("$config_dir/$configfile~")){ - exec("chmod 400 $config_dir/$configfile~"); - } + exec("chmod 400 $config_dir/$configfile~"); + } $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/pureftpd_mysql.conf.master', 'tpl/pureftpd_mysql.conf.master'); $content = str_replace('{mysql_server_ispconfig_user}', $conf["mysql"]["ispconfig_user"], $content); $content = str_replace('{mysql_server_ispconfig_password}', $conf["mysql"]["ispconfig_password"], $content); @@ -592,69 +592,69 @@ class installer_dist extends installer_base { wf("$config_dir/$configfile", $content); exec("chmod 600 $config_dir/$configfile"); exec("chown root:root $config_dir/$configfile"); - + // copy our customized copy of pureftpd.conf to the pure-ftpd config directory if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/opensuse_pureftpd_conf.master')) { - exec("cp " . $conf['ispconfig_install_dir']."/server/conf-custom/install/opensuse_pureftpd_conf.master $config_dir/pure-ftpd.conf"); - } else { - exec("cp tpl/opensuse_pureftpd_conf.master $config_dir/pure-ftpd.conf"); - } - + exec("cp " . $conf['ispconfig_install_dir']."/server/conf-custom/install/opensuse_pureftpd_conf.master $config_dir/pure-ftpd.conf"); + } else { + exec("cp tpl/opensuse_pureftpd_conf.master $config_dir/pure-ftpd.conf"); + } + } - + public function configure_mydns() - { + { global $conf; - + // configure pam for SMTP authentication agains the ispconfig database $configfile = 'mydns.conf'; - if(is_file($conf["mydns"]["config_dir"].'/'.$configfile)) copy($conf["mydns"]["config_dir"].'/'.$configfile,$conf["mydns"]["config_dir"].'/'.$configfile.'~'); + if(is_file($conf["mydns"]["config_dir"].'/'.$configfile)) copy($conf["mydns"]["config_dir"].'/'.$configfile, $conf["mydns"]["config_dir"].'/'.$configfile.'~'); if(is_file($conf["mydns"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["mydns"]["config_dir"].'/'.$configfile.'~'); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/".$configfile.".master"); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_host}',$conf["mysql"]["host"],$content); - $content = str_replace('{server_id}',$conf["server_id"],$content); - wf($conf["mydns"]["config_dir"].'/'.$configfile,$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_host}', $conf["mysql"]["host"], $content); + $content = str_replace('{server_id}', $conf["server_id"], $content); + wf($conf["mydns"]["config_dir"].'/'.$configfile, $content); exec('chmod 600 '.$conf["mydns"]["config_dir"].'/'.$configfile); exec('chown root:root '.$conf["mydns"]["config_dir"].'/'.$configfile); - + } - + public function configure_apache() - { + { global $conf; - + if($conf['apache']['installed'] == false) return; //* Create the logging directory for the vhost logfiles exec('mkdir -p /var/log/ispconfig/httpd'); - + //if(is_file('/etc/suphp.conf')) { - replaceLine('/etc/suphp.conf','php=php','x-httpd-suphp="php:/srv/www/cgi-bin/php5"',0,0); - replaceLine('/etc/suphp.conf','php="php','x-httpd-suphp="php:/srv/www/cgi-bin/php5"',0,0); - replaceLine('/etc/suphp.conf','docroot=','docroot=/srv/www',0,0); - replaceLine('/etc/suphp.conf','umask=0077','umask=0022',0); + replaceLine('/etc/suphp.conf', 'php=php', 'x-httpd-suphp="php:/srv/www/cgi-bin/php5"', 0, 0); + replaceLine('/etc/suphp.conf', 'php="php', 'x-httpd-suphp="php:/srv/www/cgi-bin/php5"', 0, 0); + replaceLine('/etc/suphp.conf', 'docroot=', 'docroot=/srv/www', 0, 0); + replaceLine('/etc/suphp.conf', 'umask=0077', 'umask=0022', 0); //} - + if(!file_exists('/srv/www/cgi-bin/php5') && file_exists('/srv/www/cgi-bin/php')) { - symlink('/srv/www/cgi-bin/php','/srv/www/cgi-bin/php5'); + symlink('/srv/www/cgi-bin/php', '/srv/www/cgi-bin/php5'); } - + // Sites enabled and available dirs exec('mkdir -p '.$conf['apache']['vhost_conf_enabled_dir']); exec('mkdir -p '.$conf['apache']['vhost_conf_dir']); - + $content = rf('/etc/apache2/httpd.conf'); - if(!stristr($content,'Include /etc/apache2/sites-enabled/')) { - af('/etc/apache2/httpd.conf',"\n\n Options FollowSymlinks\n\n\nInclude /etc/apache2/sites-enabled/\n\n"); + if(!stristr($content, 'Include /etc/apache2/sites-enabled/')) { + af('/etc/apache2/httpd.conf', "\n\n Options FollowSymlinks\n\n\nInclude /etc/apache2/sites-enabled/\n\n"); } unset($content); - + //* Copy the ISPConfig configuration include - $vhost_conf_dir = $conf['apache']['vhost_conf_dir']; - $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir']; - + $vhost_conf_dir = $conf['apache']['vhost_conf_dir']; + $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir']; + //copy('tpl/apache_ispconfig.conf.master',$vhost_conf_dir.'/ispconfig.conf'); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig.conf.master', 'tpl/apache_ispconfig.conf.master'); $records = $this->db->queryAllRecords('SELECT * FROM '.$conf['mysql']['master_database'].'.server_ip WHERE server_id = '.$conf['server_id']." AND virtualhost = 'y'"); @@ -666,7 +666,7 @@ class installer_dist extends installer_base { } else { $ip_address = $rec['ip_address']; } - $ports = explode(',',$rec['virtualhost_port']); + $ports = explode(',', $rec['virtualhost_port']); if(is_array($ports)) { foreach($ports as $port) { $port = intval($port); @@ -677,37 +677,37 @@ class installer_dist extends installer_base { } } } - + $content .= "\n"; - wf($vhost_conf_dir.'/ispconfig.conf',$content); - + wf($vhost_conf_dir.'/ispconfig.conf', $content); + if(!@is_link($vhost_conf_enabled_dir."/000-ispconfig.conf")) { exec("ln -s ".$vhost_conf_dir."/ispconfig.conf ".$vhost_conf_enabled_dir."/000-ispconfig.conf"); } - + //* make sure that webalizer finds its config file when it is directly in /etc if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) { exec('mkdir /etc/webalizer'); exec('ln -s /etc/webalizer.conf /etc/webalizer/webalizer.conf'); } - + if(is_file('/etc/webalizer/webalizer.conf')) { // Change webalizer mode to incremental - replaceLine('/etc/webalizer/webalizer.conf','#IncrementalName','IncrementalName webalizer.current',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#Incremental','Incremental yes',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#HistoryName','HistoryName webalizer.hist',0,0); + replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental yes', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName webalizer.hist', 0, 0); } - + //* add a sshusers group $command = 'groupadd sshusers'; if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + // create PHP-FPM pool dir exec('mkdir -p '.$conf['nginx']['php_fpm_pool_dir']); - + $content = rf('/etc/php5/fpm/php-fpm.conf'); if(stripos($content, 'include=/etc/php5/fpm/pool.d/*.conf') === false){ - af('/etc/php5/fpm/php-fpm.conf',"\ninclude=/etc/php5/fpm/pool.d/*.conf"); + af('/etc/php5/fpm/php-fpm.conf', "\ninclude=/etc/php5/fpm/pool.d/*.conf"); } unset($content); if(!@is_file($conf['nginx']['php_fpm_ini_path'])){ @@ -719,34 +719,34 @@ class installer_dist extends installer_base { exec('cp -f /etc/php5/apache2/php.ini '.$conf['nginx']['php_fpm_ini_path']); } } - + } - + public function configure_nginx(){ global $conf; - + if($conf['nginx']['installed'] == false) return; //* Create the logging directory for the vhost logfiles if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true); - + // Sites enabled and available dirs exec('mkdir -p '.$conf['nginx']['vhost_conf_enabled_dir']); exec('mkdir -p '.$conf['nginx']['vhost_conf_dir']); - + $content = rf('/etc/nginx/nginx.conf'); if(stripos($content, 'include /etc/nginx/sites-enabled/*.vhost;') === false){ $content = trim($content); - $content = substr($content,0,-1)."\n include /etc/nginx/sites-enabled/*.vhost;\n}"; - wf('/etc/nginx/nginx.conf',$content); + $content = substr($content, 0, -1)."\n include /etc/nginx/sites-enabled/*.vhost;\n}"; + wf('/etc/nginx/nginx.conf', $content); } unset($content); - + // create PHP-FPM pool dir exec('mkdir -p '.$conf['nginx']['php_fpm_pool_dir']); - + $content = rf('/etc/php5/fpm/php-fpm.conf'); if(stripos($content, 'include=/etc/php5/fpm/pool.d/*.conf') === false){ - af('/etc/php5/fpm/php-fpm.conf',"\ninclude=/etc/php5/fpm/pool.d/*.conf"); + af('/etc/php5/fpm/php-fpm.conf', "\ninclude=/etc/php5/fpm/pool.d/*.conf"); } unset($content); if(!@is_file($conf['nginx']['php_fpm_ini_path'])){ @@ -762,95 +762,95 @@ class installer_dist extends installer_base { //* make sure that webalizer finds its config file when it is directly in /etc if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) { mkdir('/etc/webalizer'); - symlink('/etc/webalizer.conf','/etc/webalizer/webalizer.conf'); + symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf'); } if(is_file('/etc/webalizer/webalizer.conf')) { // Change webalizer mode to incremental - replaceLine('/etc/webalizer/webalizer.conf','#IncrementalName','IncrementalName webalizer.current',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#Incremental','Incremental yes',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#HistoryName','HistoryName webalizer.hist',0,0); + replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental yes', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName webalizer.hist', 0, 0); } - + // Check the awsatst script if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools'); - if(!file_exists('/usr/share/awstats/tools/awstats_buildstaticpages.pl') && file_exists('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl')) symlink('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl','/usr/share/awstats/tools/awstats_buildstaticpages.pl'); - if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local','LogFormat=4','LogFormat=1',0,1); - + if(!file_exists('/usr/share/awstats/tools/awstats_buildstaticpages.pl') && file_exists('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl')) symlink('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl', '/usr/share/awstats/tools/awstats_buildstaticpages.pl'); + if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local', 'LogFormat=4', 'LogFormat=1', 0, 1); + //* add a sshusers group $command = 'groupadd sshusers'; if(!is_group('sshusers')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + public function configure_firewall() { global $conf; - + $dist_init_scripts = $conf['init_scripts']; - + if(is_dir("/etc/Bastille.backup")) caselog("rm -rf /etc/Bastille.backup", __FILE__, __LINE__); if(is_dir("/etc/Bastille")) caselog("mv -f /etc/Bastille /etc/Bastille.backup", __FILE__, __LINE__); - @mkdir("/etc/Bastille", octdec($directory_mode)); - if(is_dir("/etc/Bastille.backup/firewall.d")) caselog("cp -pfr /etc/Bastille.backup/firewall.d /etc/Bastille/", __FILE__, __LINE__); - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master')) { - caselog("cp -f " . $conf['ispconfig_install_dir']."/server/conf-custom/install/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg", __FILE__, __LINE__); - } else { - caselog("cp -f tpl/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg", __FILE__, __LINE__); - } - caselog("chmod 644 /etc/Bastille/bastille-firewall.cfg", __FILE__, __LINE__); - $content = rf("/etc/Bastille/bastille-firewall.cfg"); - $content = str_replace("{DNS_SERVERS}", "", $content); + @mkdir("/etc/Bastille", octdec($directory_mode)); + if(is_dir("/etc/Bastille.backup/firewall.d")) caselog("cp -pfr /etc/Bastille.backup/firewall.d /etc/Bastille/", __FILE__, __LINE__); + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master')) { + caselog("cp -f " . $conf['ispconfig_install_dir']."/server/conf-custom/install/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg", __FILE__, __LINE__); + } else { + caselog("cp -f tpl/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg", __FILE__, __LINE__); + } + caselog("chmod 644 /etc/Bastille/bastille-firewall.cfg", __FILE__, __LINE__); + $content = rf("/etc/Bastille/bastille-firewall.cfg"); + $content = str_replace("{DNS_SERVERS}", "", $content); + + $tcp_public_services = ''; + $udp_public_services = ''; - $tcp_public_services = ''; - $udp_public_services = ''; - $row = $this->db->queryOneRecord('SELECT * FROM '.$conf["mysql"]["database"].'.firewall WHERE server_id = '.intval($conf['server_id'])); - - if(trim($row["tcp_port"]) != '' || trim($row["udp_port"]) != ''){ - $tcp_public_services = trim(str_replace(',',' ',$row["tcp_port"])); - $udp_public_services = trim(str_replace(',',' ',$row["udp_port"])); - } else { - $tcp_public_services = '21 22 25 53 80 110 443 3306 8080 10000'; - $udp_public_services = '53'; - } - + + if(trim($row["tcp_port"]) != '' || trim($row["udp_port"]) != ''){ + $tcp_public_services = trim(str_replace(',', ' ', $row["tcp_port"])); + $udp_public_services = trim(str_replace(',', ' ', $row["udp_port"])); + } else { + $tcp_public_services = '21 22 25 53 80 110 443 3306 8080 10000'; + $udp_public_services = '53'; + } + if(!stristr($tcp_public_services, $conf['apache']['vhost_port'])) { $tcp_public_services .= ' '.intval($conf['apache']['vhost_port']); if($row["tcp_port"] != '') $this->db->query("UPDATE firewall SET tcp_port = tcp_port + ',".intval($conf['apache']['vhost_port'])."' WHERE server_id = ".intval($conf['server_id'])); } - $content = str_replace("{TCP_PUBLIC_SERVICES}", $tcp_public_services, $content); - $content = str_replace("{UDP_PUBLIC_SERVICES}", $udp_public_services, $content); - - wf("/etc/Bastille/bastille-firewall.cfg", $content); + $content = str_replace("{TCP_PUBLIC_SERVICES}", $tcp_public_services, $content); + $content = str_replace("{UDP_PUBLIC_SERVICES}", $udp_public_services, $content); + + wf("/etc/Bastille/bastille-firewall.cfg", $content); - if(is_file($dist_init_scripts."/bastille-firewall")) caselog("mv -f $dist_init_scripts/bastille-firewall $dist_init_scripts/bastille-firewall.backup", __FILE__, __LINE__); - caselog("cp -f apps/bastille-firewall $dist_init_scripts", __FILE__, __LINE__); - caselog("chmod 700 $dist_init_scripts/bastille-firewall", __FILE__, __LINE__); + if(is_file($dist_init_scripts."/bastille-firewall")) caselog("mv -f $dist_init_scripts/bastille-firewall $dist_init_scripts/bastille-firewall.backup", __FILE__, __LINE__); + caselog("cp -f apps/bastille-firewall $dist_init_scripts", __FILE__, __LINE__); + caselog("chmod 700 $dist_init_scripts/bastille-firewall", __FILE__, __LINE__); - if(is_file("/sbin/bastille-ipchains")) caselog("mv -f /sbin/bastille-ipchains /sbin/bastille-ipchains.backup", __FILE__, __LINE__); - caselog("cp -f apps/bastille-ipchains /sbin", __FILE__, __LINE__); - caselog("chmod 700 /sbin/bastille-ipchains", __FILE__, __LINE__); + if(is_file("/sbin/bastille-ipchains")) caselog("mv -f /sbin/bastille-ipchains /sbin/bastille-ipchains.backup", __FILE__, __LINE__); + caselog("cp -f apps/bastille-ipchains /sbin", __FILE__, __LINE__); + caselog("chmod 700 /sbin/bastille-ipchains", __FILE__, __LINE__); + + if(is_file("/sbin/bastille-netfilter")) caselog("mv -f /sbin/bastille-netfilter /sbin/bastille-netfilter.backup", __FILE__, __LINE__); + caselog("cp -f apps/bastille-netfilter /sbin", __FILE__, __LINE__); + caselog("chmod 700 /sbin/bastille-netfilter", __FILE__, __LINE__); - if(is_file("/sbin/bastille-netfilter")) caselog("mv -f /sbin/bastille-netfilter /sbin/bastille-netfilter.backup", __FILE__, __LINE__); - caselog("cp -f apps/bastille-netfilter /sbin", __FILE__, __LINE__); - caselog("chmod 700 /sbin/bastille-netfilter", __FILE__, __LINE__); - if(!@is_dir('/var/lock/subsys')) caselog("mkdir /var/lock/subsys", __FILE__, __LINE__); - exec("which ipchains &> /dev/null", $ipchains_location, $ret_val); - if(!is_file("/sbin/ipchains") && !is_link("/sbin/ipchains") && $ret_val == 0) phpcaselog(@symlink(shell_exec("which ipchains"), "/sbin/ipchains"), 'create symlink', __FILE__, __LINE__); - unset($ipchains_location); - exec("which iptables &> /dev/null", $iptables_location, $ret_val); - if(!is_file("/sbin/iptables") && !is_link("/sbin/iptables") && $ret_val == 0) phpcaselog(@symlink(trim(shell_exec("which iptables")), "/sbin/iptables"), 'create symlink', __FILE__, __LINE__); - unset($iptables_location); + exec("which ipchains &> /dev/null", $ipchains_location, $ret_val); + if(!is_file("/sbin/ipchains") && !is_link("/sbin/ipchains") && $ret_val == 0) phpcaselog(@symlink(shell_exec("which ipchains"), "/sbin/ipchains"), 'create symlink', __FILE__, __LINE__); + unset($ipchains_location); + exec("which iptables &> /dev/null", $iptables_location, $ret_val); + if(!is_file("/sbin/iptables") && !is_link("/sbin/iptables") && $ret_val == 0) phpcaselog(@symlink(trim(shell_exec("which iptables")), "/sbin/iptables"), 'create symlink', __FILE__, __LINE__); + unset($iptables_location); } public function install_ispconfig() - { + { global $conf; - + $install_dir = $conf['ispconfig_install_dir']; //* Create the ISPConfig installation directory @@ -858,93 +858,93 @@ class installer_dist extends installer_base { $command = "mkdir $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + //* Create a ISPConfig user and group $command = 'groupadd ispconfig'; if(!is_group('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + $command = "useradd -g ispconfig -d $install_dir ispconfig"; if(!is_user('ispconfig')) caselog($command.' &> /dev/null 2> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* copy the ISPConfig interface part $command = "cp -rf ../interface $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* copy the ISPConfig server part $command = "cp -rf ../server $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* Create a symlink, so ISPConfig is accessible via web // Replaced by a separate vhost definition for port 8080 // $command = "ln -s $install_dir/interface/web/ /var/www/ispconfig"; // caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* Create the config file for ISPConfig interface $configfile = 'config.inc.php'; if(is_file($install_dir.'/interface/lib/'.$configfile)){ - copy("$install_dir/interface/lib/$configfile", "$install_dir/interface/lib/$configfile~"); - } + copy("$install_dir/interface/lib/$configfile", "$install_dir/interface/lib/$configfile~"); + } $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/$configfile.master"); $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); - + $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content); $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content); $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content); $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content); - + $content = str_replace('{server_id}', $conf['server_id'], $content); $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content); $content = str_replace('{language}', $conf['language'], $content); $content = str_replace('{timezone}', $conf['timezone'], $content); $content = str_replace('{theme}', $conf['theme'], $content); $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content); - + wf("$install_dir/interface/lib/$configfile", $content); - + //* Create the config file for ISPConfig server $configfile = 'config.inc.php'; if(is_file($install_dir.'/server/lib/'.$configfile)){ - copy("$install_dir/server/lib/$configfile", "$install_dir/interface/lib/$configfile~"); - } + copy("$install_dir/server/lib/$configfile", "$install_dir/interface/lib/$configfile~"); + } $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/$configfile.master"); $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); - + $content = str_replace('{mysql_master_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content); $content = str_replace('{mysql_master_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content); $content = str_replace('{mysql_master_server_database}', $conf['mysql']['master_database'], $content); $content = str_replace('{mysql_master_server_host}', $conf['mysql']['master_host'], $content); - + $content = str_replace('{server_id}', $conf['server_id'], $content); $content = str_replace('{ispconfig_log_priority}', $conf['ispconfig_log_priority'], $content); $content = str_replace('{language}', $conf['language'], $content); $content = str_replace('{timezone}', $conf['timezone'], $content); $content = str_replace('{theme}', $conf['theme'], $content); $content = str_replace('{language_file_import_enabled}', ($conf['language_file_import_enabled'] == true)?'true':'false', $content); - + wf("$install_dir/server/lib/$configfile", $content); - + //* Create the config file for remote-actions (but only, if it does not exist, because // the value is a autoinc-value and so changed by the remoteaction_core_module if (!file_exists($install_dir.'/server/lib/remote_action.inc.php')) { $content = ''; wf($install_dir.'/server/lib/remote_action.inc.php', $content); } - + //* Enable the server modules and plugins. // TODO: Implement a selector which modules and plugins shall be enabled. $dir = $install_dir.'/server/mods-available/'; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { - if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') { - include_once($install_dir.'/server/mods-available/'.$file); - $module_name = substr($file,0,-8); + if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') { + include_once $install_dir.'/server/mods-available/'.$file; + $module_name = substr($file, 0, -8); $tmp = new $module_name; if($tmp->onInstall()) { if(!@is_link($install_dir.'/server/mods-enabled/'.$file)) @symlink($install_dir.'/server/mods-available/'.$file, $install_dir.'/server/mods-enabled/'.$file); @@ -958,16 +958,16 @@ class installer_dist extends installer_base { closedir($dh); } } - + $dir = $install_dir.'/server/plugins-available/'; if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { if($conf['apache']['installed'] == true && $file == 'nginx_plugin.inc.php') continue; if($conf['nginx']['installed'] == true && $file == 'apache2_plugin.inc.php') continue; - if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') { - include_once($install_dir.'/server/plugins-available/'.$file); - $plugin_name = substr($file,0,-8); + if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') { + include_once $install_dir.'/server/plugins-available/'.$file; + $plugin_name = substr($file, 0, -8); $tmp = new $plugin_name; if($tmp->onInstall()) { if(!@is_link($install_dir.'/server/plugins-enabled/'.$file)) @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-enabled/'.$file); @@ -981,7 +981,7 @@ class installer_dist extends installer_base { closedir($dh); } } - + // Update the server config $mail_server_enabled = ($conf['services']['mail'])?1:0; $web_server_enabled = ($conf['services']['web'])?1:0; @@ -990,14 +990,14 @@ class installer_dist extends installer_base { $db_server_enabled = ($conf['services']['db'])?1:0; $vserver_server_enabled = ($conf['services']['vserver'])?1:0; $sql = "UPDATE `server` SET mail_server = '$mail_server_enabled', web_server = '$web_server_enabled', dns_server = '$dns_server_enabled', file_server = '$file_server_enabled', db_server = '$db_server_enabled', vserver_server = '$vserver_server_enabled' WHERE server_id = ".intval($conf['server_id']); - + if($conf['mysql']['master_slave_setup'] == 'y') { $this->dbmaster->query($sql); $this->db->query($sql); } else { $this->db->query($sql); } - + //* Chmod the files $command = "chmod -R 750 $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); @@ -1005,48 +1005,48 @@ class installer_dist extends installer_base { //* chown the files to the ispconfig user and group $command = "chown -R ispconfig:ispconfig $install_dir"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - + //* Make the global language file directory group writable exec("chmod -R 770 $install_dir/interface/lib/lang"); - + //* Make the temp directory for language file exports writable exec("chmod -R 770 $install_dir/interface/web/temp"); - + //* Make all interface language file directories group writable $handle = @opendir($install_dir.'/interface/web'); - while ($file = @readdir ($handle)) { - if ($file != '.' && $file != '..') { - if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) { + while ($file = @readdir($handle)) { + if ($file != '.' && $file != '..') { + if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) { $handle2 = opendir($install_dir.'/interface/web'.'/'.$file.'/lib/lang'); - chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang',0770); - while ($lang_file = @readdir ($handle2)) { + chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang', 0770); + while ($lang_file = @readdir($handle2)) { if ($lang_file != '.' && $lang_file != '..') { - chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file,0770); + chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file, 0770); } } } } } - + //* Make the APS directories group writable exec("chmod -R 770 $install_dir/interface/web/sites/aps_meta_packages"); exec("chmod -R 770 $install_dir/server/aps_packages"); - + //* make sure that the server config file (not the interface one) is only readable by the root user chmod($install_dir.'/server/lib/config.inc.php', 0600); chown($install_dir.'/server/lib/config.inc.php', 'root'); chgrp($install_dir.'/server/lib/config.inc.php', 'root'); - + //* Make sure thet the interface config file is readable by user ispconfig only chmod($install_dir.'/interface/lib/config.inc.php', 0600); chown($install_dir.'/interface/lib/config.inc.php', 'ispconfig'); chgrp($install_dir.'/interface/lib/config.inc.php', 'ispconfig'); - + if(@is_file("$install_dir/server/lib/mysql_clientdb.conf")) { exec("chmod 600 $install_dir/server/lib/mysql_clientdb.conf"); exec("chown root:root $install_dir/server/lib/mysql_clientdb.conf"); } - + // TODO: FIXME: add the www-data user to the ispconfig group. This is just for testing // and must be fixed as this will allow the apache user to read the ispconfig files. // Later this must run as own apache server or via suexec! @@ -1066,31 +1066,31 @@ class installer_dist extends installer_base { caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } } - + //* Make the shell scripts executable $command = "chmod +x $install_dir/server/scripts/*.sh"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); - - + + if($conf['apache']['installed'] == true && $this->install_ispconfig_interface == true){ //* Copy the ISPConfig vhost for the controlpanel // TODO: These are missing! should they be "vhost_dist_*_dir" ? $vhost_conf_dir = $conf['apache']['vhost_conf_dir']; $vhost_conf_enabled_dir = $conf['apache']['vhost_conf_enabled_dir']; - - + + // Dont just copy over the virtualhost template but add some custom settings - + $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig.vhost.master', "tpl/apache_ispconfig.vhost.master"); $content = str_replace('{vhost_port}', $conf['apache']['vhost_port'], $content); - + // comment out the listen directive if port is 80 or 443 if($conf['apache']['vhost_port'] == 80 or $conf['apache']['vhost_port'] == 443) { $content = str_replace('{vhost_port_listen}', '#', $content); } else { $content = str_replace('{vhost_port_listen}', '', $content); } - + if(is_file('/usr/local/ispconfig/interface/ssl/ispserver.crt') && is_file('/usr/local/ispconfig/interface/ssl/ispserver.key')) { $content = str_replace('{ssl_comment}', '', $content); } else { @@ -1101,23 +1101,23 @@ class installer_dist extends installer_base { } else { $content = str_replace('{ssl_bundle_comment}', '#', $content); } - + $content = str_replace('/var/www/', '/srv/www/', $content); - + wf("$vhost_conf_dir/ispconfig.vhost", $content); - + //if(!is_file('/srv/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter')) { - $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig_fcgi_starter.master', 'tpl/apache_ispconfig_fcgi_starter.master'); - $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content); - $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content); - exec('mkdir -p /srv/www/php-fcgi-scripts/ispconfig'); - wf('/srv/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter', $content); - exec('chmod +x /srv/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter'); - exec('ln -s /usr/local/ispconfig/interface/web /srv/www/ispconfig'); - exec('chown -R ispconfig:ispconfig /srv/www/php-fcgi-scripts/ispconfig'); - + $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig_fcgi_starter.master', 'tpl/apache_ispconfig_fcgi_starter.master'); + $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content); + $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content); + exec('mkdir -p /srv/www/php-fcgi-scripts/ispconfig'); + wf('/srv/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter', $content); + exec('chmod +x /srv/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter'); + exec('ln -s /usr/local/ispconfig/interface/web /srv/www/ispconfig'); + exec('chown -R ispconfig:ispconfig /srv/www/php-fcgi-scripts/ispconfig'); + //} - + //copy('tpl/apache_ispconfig.vhost.master', "$vhost_conf_dir/ispconfig.vhost"); //* and create the symlink if($this->is_update == false) { @@ -1125,11 +1125,11 @@ class installer_dist extends installer_base { if(!@is_link("$vhost_conf_enabled_dir/000-ispconfig.vhost")) { exec("ln -s $vhost_conf_dir/ispconfig.vhost $vhost_conf_enabled_dir/000-ispconfig.vhost"); } - + } - + // Fix a setting in vhost master file for suse - replaceLine('/usr/local/ispconfig/server/conf/vhost.conf.master',"suPHP_UserGroup"," suPHP_UserGroup ",0); + replaceLine('/usr/local/ispconfig/server/conf/vhost.conf.master', "suPHP_UserGroup", " suPHP_UserGroup ", 0); } if($conf['nginx']['installed'] == true && $this->install_ispconfig_interface == true){ @@ -1140,7 +1140,7 @@ class installer_dist extends installer_base { // Dont just copy over the virtualhost template but add some custom settings $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/nginx_ispconfig.vhost.master', 'tpl/nginx_ispconfig.vhost.master'); $content = str_replace('{vhost_port}', $conf['nginx']['vhost_port'], $content); - + if(is_file($install_dir.'/interface/ssl/ispserver.crt') && is_file($install_dir.'/interface/ssl/ispserver.key')) { $content = str_replace('{ssl_on}', ' on', $content); $content = str_replace('{ssl_comment}', '', $content); @@ -1150,19 +1150,19 @@ class installer_dist extends installer_base { $content = str_replace('{ssl_comment}', '#', $content); $content = str_replace('{fastcgi_ssl}', 'off', $content); } - + $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']); - if(substr($socket_dir,-1) != '/') $socket_dir .= '/'; + if(substr($socket_dir, -1) != '/') $socket_dir .= '/'; if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir); $fpm_socket = $socket_dir.'ispconfig.sock'; - + //$content = str_replace('{fpm_port}', $conf['nginx']['php_fpm_start_port'], $content); $content = str_replace('{fpm_socket}', $fpm_socket, $content); wf($vhost_conf_dir.'/ispconfig.vhost', $content); - + unset($content); - + // PHP-FPM // Dont just copy over the php-fpm pool template but add some custom settings $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/php_fpm_pool.conf.master', 'tpl/php_fpm_pool.conf.master'); @@ -1178,20 +1178,20 @@ class installer_dist extends installer_base { if($this->is_update == false) { if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost'); if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) { - symlink($vhost_conf_dir.'/ispconfig.vhost',$vhost_conf_enabled_dir.'/000-ispconfig.vhost'); + symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost'); } } - + // create symlinks from /usr/share to phpMyAdmin and SquirrelMail, if they are installed - if(!@file_exists('/usr/share/phpmyadmin') && @is_dir('/srv/www/htdocs/phpMyAdmin')) symlink('/srv/www/htdocs/phpMyAdmin/','/usr/share/phpmyadmin'); - if(!@file_exists('/usr/share/squirrelmail') && @is_dir('/srv/www/htdocs/squirrelmail')) symlink('/srv/www/htdocs/squirrelmail/','/usr/share/squirrelmail'); + if(!@file_exists('/usr/share/phpmyadmin') && @is_dir('/srv/www/htdocs/phpMyAdmin')) symlink('/srv/www/htdocs/phpMyAdmin/', '/usr/share/phpmyadmin'); + if(!@file_exists('/usr/share/squirrelmail') && @is_dir('/srv/www/htdocs/squirrelmail')) symlink('/srv/www/htdocs/squirrelmail/', '/usr/share/squirrelmail'); } - - + + // Make the Clamav log files readable by ISPConfig //exec('chmod +r /var/log/clamav/clamav.log'); //exec('chmod +r /var/log/clamav/freshclam.log'); - + //* Install the update script if(is_file('/usr/local/bin/ispconfig_update_from_svn.sh')) unlink('/usr/local/bin/ispconfig_update_from_svn.sh'); exec('chown root /usr/local/ispconfig/server/scripts/update_from_svn.sh'); @@ -1202,96 +1202,96 @@ class installer_dist extends installer_base { exec('chmod 700 /usr/local/ispconfig/server/scripts/ispconfig_update.sh'); if(!is_link('/usr/local/bin/ispconfig_update_from_svn.sh')) exec('ln -s /usr/local/ispconfig/server/scripts/ispconfig_update.sh /usr/local/bin/ispconfig_update_from_svn.sh'); if(!is_link('/usr/local/bin/ispconfig_update.sh')) exec('ln -s /usr/local/ispconfig/server/scripts/ispconfig_update.sh /usr/local/bin/ispconfig_update.sh'); - + //set the fast cgi starter script to executable //exec('chmod 755 '.$install_dir.'/interface/bin/php-fcgi'); - + //* Make the logs readable for the ispconfig user if(@is_file('/var/log/mail.log')) exec('chmod +r /var/log/mail.log'); if(@is_file('/var/log/mail.warn')) exec('chmod +r /var/log/mail.warn'); if(@is_file('/var/log/mail.err')) exec('chmod +r /var/log/mail.err'); if(@is_file('/var/log/messages')) exec('chmod +r /var/log/messages'); - + //To enable apache to read the directories exec('chmod a+rx /usr/local/ispconfig'); exec('chmod -R 751 /usr/local/ispconfig/interface'); exec('chmod a+rx /usr/local/ispconfig/interface/web'); - + //* Create the ispconfig log directory if(!is_dir($conf['ispconfig_log_dir'])) mkdir($conf['ispconfig_log_dir']); if(!is_file($conf['ispconfig_log_dir'].'/ispconfig.log')) exec('touch '.$conf['ispconfig_log_dir'].'/ispconfig.log'); - + if(is_user('getmail')) { exec('mv /usr/local/ispconfig/server/scripts/run-getmail.sh /usr/local/bin/run-getmail.sh'); exec('chown getmail /usr/local/bin/run-getmail.sh'); exec('chmod 744 /usr/local/bin/run-getmail.sh'); } - + if(is_dir($install_dir.'/interface/invoices')) { exec('chmod -R 770 '.escapeshellarg($install_dir.'/interface/invoices')); exec('chown -R ispconfig:ispconfig '.escapeshellarg($install_dir.'/interface/invoices')); } - + //* Create the ispconfig auth log file and set uid/gid if(!is_file($conf['ispconfig_log_dir'].'/auth.log')) { touch($conf['ispconfig_log_dir'].'/auth.log'); } exec('chown ispconfig:ispconfig '. $conf['ispconfig_log_dir'].'/auth.log'); exec('chmod 660 '. $conf['ispconfig_log_dir'].'/auth.log'); - + //* Remove Domain module as its functions are available in the client module now if(@is_dir('/usr/local/ispconfig/interface/web/domain')) exec('rm -rf /usr/local/ispconfig/interface/web/domain'); - - + + } - + public function configure_dbserver() { global $conf; - + //* If this server shall act as database server for client DB's, we configure this here $install_dir = $conf['ispconfig_install_dir']; - - // Create a file with the database login details which + + // Create a file with the database login details which // are used to create the client databases. - + if(!is_dir("$install_dir/server/lib")) { $command = "mkdir $install_dir/server/lib"; caselog($command.' &> /dev/null', __FILE__, __LINE__, "EXECUTED: $command", "Failed to execute the command $command"); } - + $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/mysql_clientdb.conf.master', "tpl/mysql_clientdb.conf.master"); - $content = str_replace('{hostname}',$conf['mysql']['host'],$content); - $content = str_replace('{username}',$conf['mysql']['admin_user'],$content); - $content = str_replace('{password}',$conf['mysql']['admin_password'], $content); - wf("$install_dir/server/lib/mysql_clientdb.conf",$content); + $content = str_replace('{hostname}', $conf['mysql']['host'], $content); + $content = str_replace('{username}', $conf['mysql']['admin_user'], $content); + $content = str_replace('{password}', $conf['mysql']['admin_password'], $content); + wf("$install_dir/server/lib/mysql_clientdb.conf", $content); exec('chmod 600 '."$install_dir/server/lib/mysql_clientdb.conf"); exec('chown root:root '."$install_dir/server/lib/mysql_clientdb.conf"); - + } - + public function install_crontab() - { + { global $conf; - + //* Root Crontab exec('crontab -u root -l > crontab.txt'); $existing_root_cron_jobs = file('crontab.txt'); - + // remove existing ispconfig cronjobs, in case the syntax has changed foreach($existing_root_cron_jobs as $key => $val) { - if(stristr($val,'/usr/local/ispconfig')) unset($existing_root_cron_jobs[$key]); + if(stristr($val, '/usr/local/ispconfig')) unset($existing_root_cron_jobs[$key]); } - + $root_cron_jobs = array( '* * * * * /usr/local/ispconfig/server/server.sh &> /dev/null', '30 00 * * * /usr/local/ispconfig/server/cron_daily.sh &> /dev/null' ); - + if ($conf['nginx']['installed'] == true) { $root_cron_jobs[] = "0 0 * * * /usr/local/ispconfig/server/scripts/create_daily_nginx_access_logs.sh &> /dev/null"; } - + foreach($root_cron_jobs as $cron_job) { if(!in_array($cron_job."\n", $existing_root_cron_jobs)) { $existing_root_cron_jobs[] = $cron_job."\n"; @@ -1300,22 +1300,22 @@ class installer_dist extends installer_base { file_put_contents('crontab.txt', $existing_root_cron_jobs); exec('crontab -u root crontab.txt &> /dev/null'); unlink('crontab.txt'); - + //* Getmail crontab if(is_user('getmail')) { - $cf = $conf['getmail']; + $cf = $conf['getmail']; exec('crontab -u getmail -l > crontab.txt'); $existing_cron_jobs = file('crontab.txt'); - + $cron_jobs = array( - '*/5 * * * * /usr/local/bin/run-getmail.sh > /dev/null 2>> /dev/null' - ); - + '*/5 * * * * /usr/local/bin/run-getmail.sh > /dev/null 2>> /dev/null' + ); + // remove existing ispconfig cronjobs, in case the syntax has changed foreach($existing_cron_jobs as $key => $val) { - if(stristr($val,'getmail')) unset($existing_cron_jobs[$key]); + if(stristr($val, 'getmail')) unset($existing_cron_jobs[$key]); } - + foreach($cron_jobs as $cron_job) { if(!in_array($cron_job."\n", $existing_cron_jobs)) { $existing_cron_jobs[] = $cron_job."\n"; @@ -1325,7 +1325,7 @@ class installer_dist extends installer_base { exec('crontab -u getmail crontab.txt &> /dev/null'); unlink('crontab.txt'); } - + exec('touch /var/log/ispconfig/cron.log'); exec('chmod 660 /var/log/ispconfig/cron.log'); } diff --git a/install/dist/lib/opensuse110.lib.php b/install/dist/lib/opensuse110.lib.php index da77b423aecf247618a2647aa4b2663d64651ad4..aeda9b9fd1c6b83d7388fc91bde429a6e4dd5b81 100644 --- a/install/dist/lib/opensuse110.lib.php +++ b/install/dist/lib/opensuse110.lib.php @@ -33,4 +33,4 @@ class installer extends installer_dist { } -?> \ No newline at end of file +?> diff --git a/install/dist/lib/opensuse112.lib.php b/install/dist/lib/opensuse112.lib.php index da77b423aecf247618a2647aa4b2663d64651ad4..aeda9b9fd1c6b83d7388fc91bde429a6e4dd5b81 100644 --- a/install/dist/lib/opensuse112.lib.php +++ b/install/dist/lib/opensuse112.lib.php @@ -33,4 +33,4 @@ class installer extends installer_dist { } -?> \ No newline at end of file +?> diff --git a/install/install.php b/install/install.php index be3e37dc3b243cbeca774d05b2bf070e75eada7c..e2d569e72ece0fd7e8f9cc3dd5de73c7a4dc5e07 100644 --- a/install/install.php +++ b/install/install.php @@ -37,7 +37,7 @@ error_reporting(E_ALL|E_STRICT); define('INSTALLER_RUN', true); //** The banner on the command line -echo "\n\n".str_repeat('-',80)."\n"; +echo "\n\n".str_repeat('-', 80)."\n"; echo " _____ ___________ _____ __ _ ____ |_ _/ ___| ___ \ / __ \ / _(_) /__ \ | | \ `--.| |_/ / | / \/ ___ _ __ | |_ _ __ _ _/ / @@ -46,14 +46,14 @@ echo " _____ ___________ _____ __ _ ____ \___/\____/\_| \____/\___/|_| |_|_| |_|\__, | \____/ __/ | |___/ "; -echo "\n".str_repeat('-',80)."\n"; +echo "\n".str_repeat('-', 80)."\n"; echo "\n\n>> Initial configuration \n\n"; //** Include the library with the basic installer functions -require_once('lib/install.lib.php'); +require_once 'lib/install.lib.php'; //** Include the base class of the installer class -require_once('lib/installer_base.lib.php'); +require_once 'lib/installer_base.lib.php'; //** Ensure that current working directory is install directory $cur_dir = getcwd(); @@ -76,12 +76,12 @@ $dist = get_distname(); if($dist['id'] == '') die('Linux distribution or version not recognized.'); //** Include the distribution-specific installer class library and configuration -if(is_file('dist/lib/'.$dist['baseid'].'.lib.php')) include_once('dist/lib/'.$dist['baseid'].'.lib.php'); -include_once('dist/lib/'.$dist['id'].'.lib.php'); -include_once('dist/conf/'.$dist['id'].'.conf.php'); +if(is_file('dist/lib/'.$dist['baseid'].'.lib.php')) include_once 'dist/lib/'.$dist['baseid'].'.lib.php'; +include_once 'dist/lib/'.$dist['id'].'.lib.php'; +include_once 'dist/conf/'.$dist['id'].'.conf.php'; //**************************************************************************************************** -//** Installer Interface +//** Installer Interface //**************************************************************************************************** $inst = new installer(); swriteln($inst->lng(' Following will be a few questions for primary configuration so be careful.')); @@ -90,7 +90,7 @@ swriteln($inst->lng(' Tap in "quit" (without the quotes) to stop the installe //** Check log file is writable (probably not root or sudo) if(!is_writable(dirname(ISPC_LOG_FILE))){ - die("ERROR: Cannot write to the ".dirname(ISPC_LOG_FILE)." directory. Are you root or sudo ?\n\n"); + die("ERROR: Cannot write to the ".dirname(ISPC_LOG_FILE)." directory. Are you root or sudo ?\n\n"); } if(is_dir('/root/ispconfig') || is_dir('/home/admispconfig')) { @@ -105,7 +105,7 @@ if(is_dir('/usr/local/ispconfig')) { $inst->find_installed_apps(); //** Select the language and set default timezone -$conf['language'] = $inst->simple_query('Select language', array('en','de'), 'en'); +$conf['language'] = $inst->simple_query('Select language', array('en', 'de'), 'en'); $conf['timezone'] = get_system_timezone(); //* Set default theme @@ -113,7 +113,7 @@ $conf['theme'] = 'default'; $conf['language_file_import_enabled'] = true; //** Select installation mode -$install_mode = $inst->simple_query('Installation mode', array('standard','expert'), 'standard'); +$install_mode = $inst->simple_query('Installation mode', array('standard', 'expert'), 'standard'); //** Get the hostname @@ -133,13 +133,13 @@ do { $tmp_mysql_server_admin_password = $inst->free_query('MySQL root password', $conf['mysql']['admin_password']); $tmp_mysql_server_database = $inst->free_query('MySQL database to create', $conf['mysql']['database']); $tmp_mysql_server_charset = $inst->free_query('MySQL charset', $conf['mysql']['charset']); - + if($install_mode == 'expert') { swriteln("The next two questions are about the internal ISPConfig database user and password.\nIt is recommended to accept the defaults which are 'ispconfig' as username and a random password.\nIf you use a different password, use only numbers and chars for the password.\n"); $conf['mysql']['ispconfig_user'] = $inst->free_query('ISPConfig mysql database username', $conf['mysql']['ispconfig_user']); $conf['mysql']['ispconfig_password'] = $inst->free_query('ISPConfig mysql database password', $conf['mysql']['ispconfig_password']); } - + //* Initialize the MySQL server connection if(@mysql_connect($tmp_mysql_server_host, $tmp_mysql_server_admin_user, $tmp_mysql_server_admin_password)) { $conf['mysql']['host'] = $tmp_mysql_server_host; @@ -155,44 +155,44 @@ do { unset($finished); // Resolve the IP address of the MySQL hostname. -$tmp = explode(':',$conf['mysql']['host']); +$tmp = explode(':', $conf['mysql']['host']); if(!$conf['mysql']['ip'] = gethostbyname($tmp[0])) die('Unable to resolve hostname'.$tmp[0]); unset($tmp); //** Initializing database connection -include_once('lib/mysql.lib.php'); +include_once 'lib/mysql.lib.php'; $inst->db = new db(); //** Begin with standard or expert installation if($install_mode == 'standard') { - + //* Create the MySQL database $inst->configure_database(); - + //* Configure Webserver - Apache or nginx if($conf['apache']['installed'] == true && $conf['nginx']['installed'] == true) { - $http_server_to_use = $inst->simple_query('Apache and nginx detected. Select server to use for ISPConfig:', array('apache','nginx'), 'apache'); + $http_server_to_use = $inst->simple_query('Apache and nginx detected. Select server to use for ISPConfig:', array('apache', 'nginx'), 'apache'); if($http_server_to_use == 'apache'){ $conf['nginx']['installed'] = false; } else { $conf['apache']['installed'] = false; } } - + //* Insert the Server record into the database $inst->add_database_server_record(); //* Configure Postfix $inst->configure_postfix(); - + //* Configure Mailman $inst->configure_mailman('install'); - + //* Configure jailkit swriteln('Configuring Jailkit'); $inst->configure_jailkit(); - + if($conf['dovecot']['installed'] == true) { //* Configure Dovecot swriteln('Configuring Dovecot'); @@ -205,7 +205,7 @@ if($install_mode == 'standard') { //* Configure PAM swriteln('Configuring PAM'); $inst->configure_pam(); - + //* Configure Courier swriteln('Configuring Courier'); $inst->configure_courier(); @@ -222,7 +222,7 @@ if($install_mode == 'standard') { //* Configure Getmail swriteln('Configuring Getmail'); $inst->configure_getmail(); - + //* Configure Pureftpd swriteln('Configuring Pureftpd'); $inst->configure_pureftpd(); @@ -238,39 +238,39 @@ if($install_mode == 'standard') { swriteln('Configuring MyDNS'); $inst->configure_mydns(); } - + //* Configure Apache if($conf['apache']['installed'] == true){ swriteln('Configuring Apache'); $inst->configure_apache(); } - + //* Configure nginx if($conf['nginx']['installed'] == true){ swriteln('Configuring nginx'); $inst->configure_nginx(); } - - //** Configure Vlogger - swriteln('Configuring Vlogger'); - $inst->configure_vlogger(); - + + //** Configure Vlogger + swriteln('Configuring Vlogger'); + $inst->configure_vlogger(); + //** Configure apps vhost swriteln('Configuring Apps vhost'); $inst->configure_apps_vhost(); - + //* Configure Firewall //* Configure Bastille Firewall $conf['services']['firewall'] = true; swriteln('Configuring Bastille Firewall'); $inst->configure_firewall(); - //* Configure Fail2ban - if($conf['fail2ban']['installed'] == true) { - swriteln('Configuring Fail2ban'); - $inst->configure_fail2ban(); - } - + //* Configure Fail2ban + if($conf['fail2ban']['installed'] == true) { + swriteln('Configuring Fail2ban'); + $inst->configure_fail2ban(); + } + /* if($conf['squid']['installed'] == true) { $conf['services']['proxy'] = true; @@ -282,22 +282,22 @@ if($install_mode == 'standard') { $inst->configure_nginx(); } */ - + //* Configure ISPConfig swriteln('Installing ISPConfig'); - + //** Customize the port ISPConfig runs on $ispconfig_vhost_port = $inst->free_query('ISPConfig Port', '8080'); if($conf['apache']['installed'] == true) $conf['apache']['vhost_port'] = $ispconfig_vhost_port; if($conf['nginx']['installed'] == true) $conf['nginx']['vhost_port'] = $ispconfig_vhost_port; unset($ispconfig_vhost_port); - if(strtolower($inst->simple_query('Do you want a secure (SSL) connection to the ISPConfig web interface',array('y','n'),'y')) == 'y') { - $inst->make_ispconfig_ssl_cert(); + if(strtolower($inst->simple_query('Do you want a secure (SSL) connection to the ISPConfig web interface', array('y', 'n'), 'y')) == 'y') { + $inst->make_ispconfig_ssl_cert(); } $inst->install_ispconfig(); - + //* Configure DBServer swriteln('Configuring DBServer'); $inst->configure_dbserver(); @@ -305,7 +305,7 @@ if($install_mode == 'standard') { //* Configure ISPConfig swriteln('Installing ISPConfig crontab'); $inst->install_crontab(); - + swriteln('Restarting services ...'); if($conf['mysql']['installed'] == true && $conf['mysql']['init_script'] != '') system($inst->getinitcommand($conf['mysql']['init_script'], 'restart')); if($conf['postfix']['installed'] == true && $conf['postfix']['init_script'] != '') system($inst->getinitcommand($conf['postfix']['init_script'], 'restart')); @@ -331,11 +331,11 @@ if($install_mode == 'standard') { if($conf['mydns']['installed'] == true && $conf['mydns']['init_script'] != '') system($inst->getinitcommand($conf['mydns']['init_script'], 'restart').' &> /dev/null'); if($conf['powerdns']['installed'] == true && $conf['powerdns']['init_script'] != '') system($inst->getinitcommand($conf['powerdns']['init_script'], 'restart').' &> /dev/null'); if($conf['bind']['installed'] == true && $conf['bind']['init_script'] != '') system($inst->getinitcommand($conf['bind']['init_script'], 'restart').' &> /dev/null'); - //if($conf['squid']['installed'] == true && $conf['squid']['init_script'] != '' && is_file($conf['init_scripts'].'/'.$conf['squid']['init_script'])) system($conf['init_scripts'].'/'.$conf['squid']['init_script'].' restart &> /dev/null'); + //if($conf['squid']['installed'] == true && $conf['squid']['init_script'] != '' && is_file($conf['init_scripts'].'/'.$conf['squid']['init_script'])) system($conf['init_scripts'].'/'.$conf['squid']['init_script'].' restart &> /dev/null'); if($conf['nginx']['installed'] == true && $conf['nginx']['init_script'] != '') system($inst->getinitcommand($conf['nginx']['init_script'], 'restart').' &> /dev/null'); - //if($conf['ufw']['installed'] == true && $conf['ufw']['init_script'] != '' && is_file($conf['init_scripts'].'/'.$conf['ufw']['init_script'])) system($conf['init_scripts'].'/'.$conf['ufw']['init_script'].' restart &> /dev/null'); + //if($conf['ufw']['installed'] == true && $conf['ufw']['init_script'] != '' && is_file($conf['init_scripts'].'/'.$conf['ufw']['init_script'])) system($conf['init_scripts'].'/'.$conf['ufw']['init_script'].' restart &> /dev/null'); } else { - + //* In expert mode, we select the services in the following steps, only db is always available $conf['services']['mail'] = false; $conf['services']['web'] = false; @@ -343,23 +343,23 @@ if($install_mode == 'standard') { $conf['services']['db'] = true; $conf['services']['firewall'] = false; $conf['services']['proxy'] = false; - - + + //** Get Server ID // $conf['server_id'] = $inst->free_query('Unique Numeric ID of the server','1'); // Server ID is an autoInc value of the mysql database now - - if(strtolower($inst->simple_query('Shall this server join an existing ISPConfig multiserver setup',array('y','n'),'n')) == 'y') { + + if(strtolower($inst->simple_query('Shall this server join an existing ISPConfig multiserver setup', array('y', 'n'), 'n')) == 'y') { $conf['mysql']['master_slave_setup'] = 'y'; - + //** Get MySQL root credentials $finished = false; do { $tmp_mysql_server_host = $inst->free_query('MySQL master server hostname', $conf['mysql']['master_host']); $tmp_mysql_server_admin_user = $inst->free_query('MySQL master server root username', $conf['mysql']['master_admin_user']); $tmp_mysql_server_admin_password = $inst->free_query('MySQL master server root password', $conf['mysql']['master_admin_password']); - $tmp_mysql_server_database = $inst->free_query('MySQL master server database name', $conf['mysql']['master_database']); - + $tmp_mysql_server_database = $inst->free_query('MySQL master server database name', $conf['mysql']['master_database']); + //* Initialize the MySQL server connection if(@mysql_connect($tmp_mysql_server_host, $tmp_mysql_server_admin_user, $tmp_mysql_server_admin_password)) { $conf['mysql']['master_host'] = $tmp_mysql_server_host; @@ -372,7 +372,7 @@ if($install_mode == 'standard') { } } while ($finished == false); unset($finished); - + // initialize the connection to the master database $inst->dbmaster = new db(); if($inst->dbmaster->linkId) $inst->dbmaster->closeConn(); @@ -380,39 +380,39 @@ if($install_mode == 'standard') { $inst->dbmaster->dbName = $conf['mysql']["master_database"]; $inst->dbmaster->dbUser = $conf['mysql']["master_admin_user"]; $inst->dbmaster->dbPass = $conf['mysql']["master_admin_password"]; - + } else { // the master DB is the same then the slave DB $inst->dbmaster = $inst->db; } - + //* Create the mysql database $inst->configure_database(); - + //* Configure Webserver - Apache or nginx if($conf['apache']['installed'] == true && $conf['nginx']['installed'] == true) { - $http_server_to_use = $inst->simple_query('Apache and nginx detected. Select server to use for ISPConfig:', array('apache','nginx'), 'apache'); + $http_server_to_use = $inst->simple_query('Apache and nginx detected. Select server to use for ISPConfig:', array('apache', 'nginx'), 'apache'); if($http_server_to_use == 'apache'){ $conf['nginx']['installed'] = false; } else { $conf['apache']['installed'] = false; } } - + //* Insert the Server record into the database swriteln('Adding ISPConfig server record to database.'); swriteln(''); $inst->add_database_server_record(); - - if(strtolower($inst->simple_query('Configure Mail', array('y','n') ,'y') ) == 'y') { - + + if(strtolower($inst->simple_query('Configure Mail', array('y', 'n') , 'y') ) == 'y') { + $conf['services']['mail'] = true; - + //* Configure Postfix swriteln('Configuring Postfix'); $inst->configure_postfix(); - + //* Configure Mailman swriteln('Configuring Mailman'); $inst->configure_mailman(); @@ -422,15 +422,15 @@ if($install_mode == 'standard') { swriteln('Configuring Dovecot'); $inst->configure_dovecot(); } else { - + //* Configure saslauthd swriteln('Configuring SASL'); $inst->configure_saslauthd(); - + //* Configure PAM swriteln('Configuring PAM'); $inst->configure_pam(); - + //* Configure courier swriteln('Configuring Courier'); $inst->configure_courier(); @@ -447,7 +447,7 @@ if($install_mode == 'standard') { //* Configure Getmail swriteln('Configuring Getmail'); $inst->configure_getmail(); - + if($conf['postfix']['installed'] == true && $conf['postfix']['init_script'] != '') system($inst->getinitcommand($conf['postfix']['init_script'], 'restart')); if($conf['saslauthd']['installed'] == true && $conf['saslauthd']['init_script'] != '') system($inst->getinitcommand($conf['saslauthd']['init_script'], 'restart')); if($conf['amavis']['installed'] == true && $conf['amavis']['init_script'] != '') system($inst->getinitcommand($conf['amavis']['init_script'], 'restart')); @@ -462,22 +462,22 @@ if($install_mode == 'standard') { if($conf['dovecot']['installed'] == true && $conf['dovecot']['init_script'] != '') system($inst->getinitcommand($conf['dovecot']['init_script'], 'restart')); if($conf['mailman']['installed'] == true && $conf['mailman']['init_script'] != '') system('nohup '.$inst->getinitcommand($conf['mailman']['init_script'], 'restart').' >/dev/null 2>&1 &'); } - + //** Configure Jailkit - if(strtolower($inst->simple_query('Configure Jailkit', array('y','n'),'y') ) == 'y') { + if(strtolower($inst->simple_query('Configure Jailkit', array('y', 'n'), 'y') ) == 'y') { swriteln('Configuring Jailkit'); $inst->configure_jailkit(); } - + //** Configure Pureftpd - if(strtolower($inst->simple_query('Configure FTP Server', array('y','n'),'y') ) == 'y') { + if(strtolower($inst->simple_query('Configure FTP Server', array('y', 'n'), 'y') ) == 'y') { swriteln('Configuring Pureftpd'); $inst->configure_pureftpd(); if($conf['pureftpd']['installed'] == true && $conf['pureftpd']['init_script'] != '') system($inst->getinitcommand($conf['pureftpd']['init_script'], 'restart')); } - + //** Configure DNS - if(strtolower($inst->simple_query('Configure DNS Server',array('y','n'),'y')) == 'y') { + if(strtolower($inst->simple_query('Configure DNS Server', array('y', 'n'), 'y')) == 'y') { $conf['services']['dns'] = true; //* Configure DNS if($conf['powerdns']['installed'] == true) { @@ -493,12 +493,12 @@ if($install_mode == 'standard') { $inst->configure_mydns(); if($conf['mydns']['init_script'] != '') system($inst->getinitcommand($conf['mydns']['init_script'], 'restart').' &> /dev/null'); } - + } - + /* //** Configure Squid - if(strtolower($inst->simple_query('Configure Proxy Server', array('y','n'),'y') ) == 'y') { + if(strtolower($inst->simple_query('Configure Proxy Server', array('y','n'),'y') ) == 'y') { if($conf['squid']['installed'] == true) { $conf['services']['proxy'] = true; swriteln('Configuring Squid'); @@ -512,50 +512,50 @@ if($install_mode == 'standard') { } } */ - + //** Configure Apache if($conf['apache']['installed'] == true){ swriteln("\nHint: If this server shall run the ISPConfig interface, select 'y' in the 'Configure Apache Server' option.\n"); - if(strtolower($inst->simple_query('Configure Apache Server',array('y','n'),'y')) == 'y') { + if(strtolower($inst->simple_query('Configure Apache Server', array('y', 'n'), 'y')) == 'y') { $conf['services']['web'] = true; swriteln('Configuring Apache'); $inst->configure_apache(); - + //** Configure Vlogger swriteln('Configuring Vlogger'); $inst->configure_vlogger(); - + //** Configure apps vhost swriteln('Configuring Apps vhost'); $inst->configure_apps_vhost(); } } - + //** Configure nginx if($conf['nginx']['installed'] == true){ swriteln("\nHint: If this server shall run the ISPConfig interface, select 'y' in the 'Configure nginx Server' option.\n"); - if(strtolower($inst->simple_query('Configure nginx Server',array('y','n'),'y')) == 'y') { + if(strtolower($inst->simple_query('Configure nginx Server', array('y', 'n'), 'y')) == 'y') { $conf['services']['web'] = true; swriteln('Configuring nginx'); $inst->configure_nginx(); - + //** Configure Vlogger //swriteln('Configuring Vlogger'); //$inst->configure_vlogger(); - + //** Configure apps vhost swriteln('Configuring Apps vhost'); $inst->configure_apps_vhost(); } } - + //** Configure Firewall - if(strtolower($inst->simple_query('Configure Firewall Server',array('y','n'),'y')) == 'y') { + if(strtolower($inst->simple_query('Configure Firewall Server', array('y', 'n'), 'y')) == 'y') { //if($conf['bastille']['installed'] == true) { - //* Configure Bastille Firewall - $conf['services']['firewall'] = true; - swriteln('Configuring Bastille Firewall'); - $inst->configure_firewall(); + //* Configure Bastille Firewall + $conf['services']['firewall'] = true; + swriteln('Configuring Bastille Firewall'); + $inst->configure_firewall(); /*} elseif($conf['ufw']['installed'] == true) { //* Configure Ubuntu Firewall $conf['services']['firewall'] = true; @@ -564,18 +564,18 @@ if($install_mode == 'standard') { } */ } - + //** Configure Firewall - /*if(strtolower($inst->simple_query('Configure Firewall Server',array('y','n'),'y')) == 'y') { + /*if(strtolower($inst->simple_query('Configure Firewall Server',array('y','n'),'y')) == 'y') { swriteln('Configuring Firewall'); $inst->configure_firewall(); }*/ - + //** Configure ISPConfig :-) $install_ispconfig_interface_default = ($conf['mysql']['master_slave_setup'] == 'y')?'n':'y'; - if(strtolower($inst->simple_query('Install ISPConfig Web Interface',array('y','n'),$install_ispconfig_interface_default)) == 'y') { + if(strtolower($inst->simple_query('Install ISPConfig Web Interface', array('y', 'n'), $install_ispconfig_interface_default)) == 'y') { swriteln('Installing ISPConfig'); - + //** We want to check if the server is a module or cgi based php enabled server //** TODO: Don't always ask for this somehow ? /* @@ -595,23 +595,23 @@ if($install_mode == 'standard') { if($conf['apache']['installed'] == true) $conf['apache']['vhost_port'] = $ispconfig_vhost_port; if($conf['nginx']['installed'] == true) $conf['nginx']['vhost_port'] = $ispconfig_vhost_port; unset($ispconfig_vhost_port); - - if(strtolower($inst->simple_query('Enable SSL for the ISPConfig web interface',array('y','n'),'y')) == 'y') { + + if(strtolower($inst->simple_query('Enable SSL for the ISPConfig web interface', array('y', 'n'), 'y')) == 'y') { $inst->make_ispconfig_ssl_cert(); } - + $inst->install_ispconfig_interface = true; - + } else { $inst->install_ispconfig_interface = false; } - + $inst->install_ispconfig(); - + //* Configure DBServer swriteln('Configuring DBServer'); $inst->configure_dbserver(); - + //* Configure ISPConfig swriteln('Installing ISPConfig crontab'); $inst->install_crontab(); @@ -621,13 +621,13 @@ if($install_mode == 'standard') { if($conf['nginx']['php_fpm_init_script'] != '') system($inst->getinitcommand($conf['nginx']['php_fpm_init_script'], 'reload')); if($conf['nginx']['init_script'] != '') system($inst->getinitcommand($conf['nginx']['init_script'], 'reload')); } - - - + + + } //* << $install_mode / 'Standard' or Genius echo "Installation completed.\n"; -?> \ No newline at end of file +?> diff --git a/install/lib/install.lib.php b/install/lib/install.lib.php index 9c61759c71d2ae6a39c2fb2f698c866f8f70d2bf..30ba04ea1110d938a5a57ab0dd2dad8398a4d726 100644 --- a/install/lib/install.lib.php +++ b/install/lib/install.lib.php @@ -79,66 +79,66 @@ function get_distname() { $distname = 'Ubuntu'; $distid = 'debian40'; $distbaseid = 'debian'; - $ver = explode(' ',$issue); + $ver = explode(' ', $issue); $ver = array_filter($ver); $ver = next($ver); - $mainver = explode('.',$ver); + $mainver = explode('.', $ver); $mainver = array_filter($mainver); $mainver = current($mainver).'.'.next($mainver); switch ($mainver){ - case "12.10": - $relname = "(Quantal Quetzal)"; + case "12.10": + $relname = "(Quantal Quetzal)"; break; - case "12.04": - $relname = "(Precise Pangolin)"; + case "12.04": + $relname = "(Precise Pangolin)"; break; - case "11.10": - $relname = "(Oneiric Ocelot)"; + case "11.10": + $relname = "(Oneiric Ocelot)"; break; - case "11.14": - $relname = "(Natty Narwhal)"; + case "11.14": + $relname = "(Natty Narwhal)"; break; - case "10.10": - $relname = "(Maverick Meerkat)"; + case "10.10": + $relname = "(Maverick Meerkat)"; break; - case "10.04": - $relname = "(Lucid Lynx)"; + case "10.04": + $relname = "(Lucid Lynx)"; break; - case "9.10": - $relname = "(Karmic Koala)"; + case "9.10": + $relname = "(Karmic Koala)"; break; - case "9.04": - $relname = "(Jaunty Jackpole)"; + case "9.04": + $relname = "(Jaunty Jackpole)"; break; - case "8.10": + case "8.10": $relname = "(Intrepid Ibex)"; break; - case "8.04": - $relname = "(Hardy Heron)"; + case "8.04": + $relname = "(Hardy Heron)"; break; - case "7.10": - $relname = "(Gutsy Gibbon)"; + case "7.10": + $relname = "(Gutsy Gibbon)"; break; - case "7.04": - $relname = "(Feisty Fawn)"; + case "7.04": + $relname = "(Feisty Fawn)"; break; - case "6.10": - $relname = "(Edgy Eft)"; + case "6.10": + $relname = "(Edgy Eft)"; break; - case "6.06": - $relname = "(Dapper Drake)"; + case "6.06": + $relname = "(Dapper Drake)"; break; - case "5.10": - $relname = "(Breezy Badger)"; + case "5.10": + $relname = "(Breezy Badger)"; break; - case "5.04": - $relname = "(Hoary Hedgehog)"; + case "5.04": + $relname = "(Hoary Hedgehog)"; break; - case "4.10": - $relname = "(Warty Warthog)"; + case "4.10": + $relname = "(Warty Warthog)"; break; - default: - $relname = "UNKNOWN"; + default: + $relname = "UNKNOWN"; } $distver = $ver.$lts." ".$relname; swriteln("Operating System: ".$distver."\n"); @@ -148,19 +148,19 @@ function get_distname() { $distid = 'debian40'; $distbaseid = 'debian'; swriteln("Operating System: Debian 4.0 or compatible\n"); - } elseif(strstr(trim(file_get_contents('/etc/debian_version')),'5.0')) { + } elseif(strstr(trim(file_get_contents('/etc/debian_version')), '5.0')) { $distname = 'Debian'; $distver = 'Lenny'; $distid = 'debian40'; $distbaseid = 'debian'; swriteln("Operating System: Debian Lenny or compatible\n"); - } elseif(strstr(trim(file_get_contents('/etc/debian_version')),'6.0') || trim(file_get_contents('/etc/debian_version')) == 'squeeze/sid') { + } elseif(strstr(trim(file_get_contents('/etc/debian_version')), '6.0') || trim(file_get_contents('/etc/debian_version')) == 'squeeze/sid') { $distname = 'Debian'; $distver = 'Squeeze/Sid'; $distid = 'debian60'; $distbaseid = 'debian'; swriteln("Operating System: Debian 6.0 (Squeeze/Sid) or compatible\n"); - } elseif(strstr(trim(file_get_contents('/etc/debian_version')),'7.0') || strstr(trim(file_get_contents('/etc/debian_version')),'7.1') || trim(file_get_contents('/etc/debian_version')) == 'wheezy/sid') { + } elseif(strstr(trim(file_get_contents('/etc/debian_version')), '7.0') || strstr(trim(file_get_contents('/etc/debian_version')), '7.1') || trim(file_get_contents('/etc/debian_version')) == 'wheezy/sid') { $distname = 'Debian'; $distver = 'Wheezy/Sid'; $distid = 'debian60'; @@ -177,19 +177,19 @@ function get_distname() { //** OpenSuSE elseif(file_exists('/etc/SuSE-release')) { - if(stristr(file_get_contents('/etc/SuSE-release'),'11.0')) { + if(stristr(file_get_contents('/etc/SuSE-release'), '11.0')) { $distname = 'openSUSE'; $distver = '11.0'; $distid = 'opensuse110'; $distbaseid = 'opensuse'; swriteln("Operating System: openSUSE 11.0 or compatible\n"); - } elseif(stristr(file_get_contents('/etc/SuSE-release'),'11.1')) { + } elseif(stristr(file_get_contents('/etc/SuSE-release'), '11.1')) { $distname = 'openSUSE'; $distver = '11.1'; $distid = 'opensuse110'; $distbaseid = 'opensuse'; swriteln("Operating System: openSUSE 11.1 or compatible\n"); - } elseif(stristr(file_get_contents('/etc/SuSE-release'),'11.2')) { + } elseif(stristr(file_get_contents('/etc/SuSE-release'), '11.2')) { $distname = 'openSUSE'; $distver = '11.2'; $distid = 'opensuse112'; @@ -210,37 +210,37 @@ function get_distname() { $content = file_get_contents('/etc/redhat-release'); - if(stristr($content,'Fedora release 9 (Sulphur)')) { + if(stristr($content, 'Fedora release 9 (Sulphur)')) { $distname = 'Fedora'; $distver = '9'; $distid = 'fedora9'; $distbaseid = 'fedora'; swriteln("Operating System: Fedora 9 or compatible\n"); - } elseif(stristr($content,'Fedora release 10 (Cambridge)')) { + } elseif(stristr($content, 'Fedora release 10 (Cambridge)')) { $distname = 'Fedora'; $distver = '10'; $distid = 'fedora9'; $distbaseid = 'fedora'; swriteln("Operating System: Fedora 10 or compatible\n"); - } elseif(stristr($content,'Fedora release 10')) { + } elseif(stristr($content, 'Fedora release 10')) { $distname = 'Fedora'; $distver = '11'; $distid = 'fedora9'; $distbaseid = 'fedora'; swriteln("Operating System: Fedora 11 or compatible\n"); - } elseif(stristr($content,'CentOS release 5.2 (Final)')) { + } elseif(stristr($content, 'CentOS release 5.2 (Final)')) { $distname = 'CentOS'; $distver = '5.2'; $distid = 'centos52'; $distbaseid = 'fedora'; swriteln("Operating System: CentOS 5.2 or compatible\n"); - } elseif(stristr($content,'CentOS release 5.3 (Final)')) { + } elseif(stristr($content, 'CentOS release 5.3 (Final)')) { $distname = 'CentOS'; $distver = '5.3'; $distid = 'centos53'; $distbaseid = 'fedora'; swriteln("Operating System: CentOS 5.3 or compatible\n"); - } elseif(stristr($content,'CentOS release 5')) { + } elseif(stristr($content, 'CentOS release 5')) { $distname = 'CentOS'; $distver = 'Unknown'; $distid = 'centos53'; @@ -260,7 +260,7 @@ function get_distname() { $content = file_get_contents('/etc/gentoo-release'); - preg_match_all('/([0-9]{1,2})/', $content, $version); + preg_match_all('/([0-9]{1,2})/', $content, $version); $distname = 'Gentoo'; $distver = $version[0][0].$version[0][1]; $distid = 'gentoo'; @@ -275,8 +275,8 @@ function get_distname() { } function sread() { - $input = fgets(STDIN); - return rtrim($input); + $input = fgets(STDIN); + return rtrim($input); } function swrite($text = '') { @@ -288,7 +288,7 @@ function swriteln($text = '') { } function ilog($msg){ - exec("echo `date` \"- [ISPConfig] - \"".$msg.' >> '.ISPC_LOG_FILE); + exec("echo `date` \"- [ISPConfig] - \"".$msg.' >> '.ISPC_LOG_FILE); } function error($msg){ @@ -297,7 +297,7 @@ function error($msg){ } function caselog($command, $file = '', $line = '', $success = '', $failure = ''){ - exec($command,$arr,$ret_val); + exec($command, $arr, $ret_val); $arr = NULL; if(!empty($file) && !empty($line)){ $pre = $file.', Line '.$line.': '; @@ -346,15 +346,15 @@ function mkdirs($strPath, $mode = '0755'){ } function rfsel($file, $file2) { - clearstatcache(); - if(is_file($file)) return rf($file); - else return rf($file2); + clearstatcache(); + if(is_file($file)) return rf($file); + else return rf($file2); } function rf($file){ clearstatcache(); if(is_file($file)) { - if(!$fp = fopen ($file, 'rb')){ + if(!$fp = fopen($file, 'rb')){ ilog('WARNING: could not open file '.$file); } return filesize($file) > 0 ? fread($fp, filesize($file)) : ''; @@ -365,7 +365,7 @@ function rf($file){ function wf($file, $content){ mkdirs(dirname($file)); - if(!$fp = fopen ($file, 'wb')){ + if(!$fp = fopen($file, 'wb')){ ilog('WARNING: could not open file '.$file); } fwrite($fp, $content); @@ -374,18 +374,18 @@ function wf($file, $content){ function af($file, $content){ mkdirs(dirname($file)); - if(!$fp = fopen ($file, 'ab')){ + if(!$fp = fopen($file, 'ab')){ ilog('WARNING: could not open file '.$file); } - fwrite($fp,$content); + fwrite($fp, $content); fclose($fp); } function aftsl($file, $content){ - if(!$fp = fopen ($file, 'ab')){ + if(!$fp = fopen($file, 'ab')){ ilog('WARNING: could not open file '.$file); } - fwrite($fp,$content); + fwrite($fp, $content); fclose($fp); } @@ -428,7 +428,7 @@ function no_comments($file, $comment = '#'){ if(strstr($line, $comment)){ $pos = strpos($line, $comment); if($pos != 0){ - $new_lines[] = substr($line,0,$pos); + $new_lines[] = substr($line, 0, $pos); }else{ $new_lines[] = ''; } @@ -508,7 +508,7 @@ function grep($content, $string, $params = ''){ } if(is_array($find)){ $ret_val = implode("\n", $find); - if(substr($ret_val,-1) != "\n") $ret_val .= "\n"; + if(substr($ret_val, -1) != "\n") $ret_val .= "\n"; $find = NULL; return $ret_val; } else { @@ -555,7 +555,7 @@ function ini_to_array($ini) { $ini = str_replace("\r\n", "\n", $ini); $lines = explode("\n", $ini); foreach($lines as $line) { - $line = trim($line); + $line = trim($line); if($line != '') { if(preg_match("/^\[([\w\d_]+)\]$/", $line, $matches)) { $section = strtolower($matches[1]); @@ -577,8 +577,8 @@ function array_to_ini($config_array = '') { $content .= "[$section]\n"; foreach($data as $item => $value) { if($item != ''){ - $content .= "$item=$value\n"; - } + $content .= "$item=$value\n"; + } } $content .= "\n"; } @@ -617,13 +617,13 @@ function is_group($group){ return false; } -function replaceLine($filename,$search_pattern,$new_line,$strict = 0,$append = 1) { +function replaceLine($filename, $search_pattern, $new_line, $strict = 0, $append = 1) { if($lines = @file($filename)) { $out = ''; $found = 0; foreach($lines as $line) { if($strict == 0) { - if(stristr($line,$search_pattern)) { + if(stristr($line, $search_pattern)) { $out .= $new_line."\n"; $found = 1; } else { @@ -640,20 +640,20 @@ function replaceLine($filename,$search_pattern,$new_line,$strict = 0,$append = 1 } if($found == 0) { //* add \n if the last line does not end with \n or \r - if(substr($out,-1) != "\n" && substr($out,-1) != "\r") $out .= "\n"; + if(substr($out, -1) != "\n" && substr($out, -1) != "\r") $out .= "\n"; //* add the new line at the end of the file if($append == 1) $out .= $new_line."\n"; } - file_put_contents($filename,$out); + file_put_contents($filename, $out); } } -function removeLine($filename,$search_pattern,$strict = 0) { +function removeLine($filename, $search_pattern, $strict = 0) { if($lines = @file($filename)) { $out = ''; foreach($lines as $line) { if($strict == 0) { - if(!stristr($line,$search_pattern)) { + if(!stristr($line, $search_pattern)) { $out .= $line; } } else { @@ -662,13 +662,13 @@ function removeLine($filename,$search_pattern,$strict = 0) { } } } - file_put_contents($filename,$out); + file_put_contents($filename, $out); } } function is_installed($appname) { - exec('which '.escapeshellcmd($appname).' 2> /dev/null',$out,$returncode); - if(isset($out[0]) && stristr($out[0],$appname) && $returncode == 0) { + exec('which '.escapeshellcmd($appname).' 2> /dev/null', $out, $returncode); + if(isset($out[0]) && stristr($out[0], $appname) && $returncode == 0) { return true; } else { return false; @@ -683,12 +683,12 @@ function is_installed($appname) { * 1 $current version is older then new version (update) */ -function compare_ispconfig_version($current,$new) { +function compare_ispconfig_version($current, $new) { if( $current == $new) { return 0; } - $p = explode('.',$current); + $p = explode('.', $current); $tmp = ''; $tmp .= str_pad(intval($p[0]), 3, '0', STR_PAD_LEFT); $tmp .= (isset($p[1]))?str_pad(intval($p[1]), 3, '0', STR_PAD_LEFT):'000'; @@ -696,7 +696,7 @@ function compare_ispconfig_version($current,$new) { $tmp .= (isset($p[3]))?str_pad(intval($p[3]), 3, '0', STR_PAD_LEFT):'000'; $current = $tmp; - $p = explode('.',$new); + $p = explode('.', $new); $tmp = ''; $tmp .= str_pad(intval($p[0]), 3, '0', STR_PAD_LEFT); $tmp .= (isset($p[1]))?str_pad(intval($p[1]), 3, '0', STR_PAD_LEFT):'000'; @@ -728,7 +728,7 @@ function get_ispconfig_port_number() { if(is_file($ispconfig_vhost_file)) { $tmp = file_get_contents($ispconfig_vhost_file); - preg_match($regex,$tmp,$matches); + preg_match($regex, $tmp, $matches); $port_number = @intval($matches[1]); if($port_number > 0) { return $port_number; @@ -748,7 +748,7 @@ function is_ispconfig_ssl_enabled() { if(is_file($ispconfig_vhost_file)) { $tmp = file_get_contents($ispconfig_vhost_file); - if(stristr($tmp,'SSLCertificateFile')) { + if(stristr($tmp, 'SSLCertificateFile')) { return true; } else { return false; @@ -756,60 +756,63 @@ function is_ispconfig_ssl_enabled() { } } -/** - Function to find the hash file for timezone detection - (c) 2012 Marius Cramer, pixcept KG, m.cramer@pixcept.de -*/ +/** + Function to find the hash file for timezone detection + (c) 2012 Marius Cramer, pixcept KG, m.cramer@pixcept.de + */ + + function find_hash_file($hash, $dir, $basedir = '') { - $res = opendir($dir); - if(!$res) return false; - - if(substr($basedir, -1) === '/') $basedir = substr($basedir, 0, strlen($basedir) - 1); - if(substr($dir, -1) === '/') $dir = substr($dir, 0, strlen($dir) - 1); - if($basedir === '') $basedir = $dir; - - while($cur = readdir($res)) { - if($cur == '.' || $cur == '..') continue; - $entry = $dir.'/'.$cur; - if(is_dir($entry)) { - $result = find_hash_file($hash, $entry, $basedir); - if($result !== false) return $result; - } elseif(md5_file($entry) === $hash) { - $entry = substr($entry, strlen($basedir) + 1); - if(substr($entry, 0, 7) === '/posix/') $entry = substr($entry, 7); - return $entry; - } - } - closedir($res); - return false; -} - -/** - Function to get the timezone of the Linux system - (c) 2012 Marius Cramer, pixcept KG, m.cramer@pixcept.de -*/ + $res = opendir($dir); + if(!$res) return false; + + if(substr($basedir, -1) === '/') $basedir = substr($basedir, 0, strlen($basedir) - 1); + if(substr($dir, -1) === '/') $dir = substr($dir, 0, strlen($dir) - 1); + if($basedir === '') $basedir = $dir; + + while($cur = readdir($res)) { + if($cur == '.' || $cur == '..') continue; + $entry = $dir.'/'.$cur; + if(is_dir($entry)) { + $result = find_hash_file($hash, $entry, $basedir); + if($result !== false) return $result; + } elseif(md5_file($entry) === $hash) { + $entry = substr($entry, strlen($basedir) + 1); + if(substr($entry, 0, 7) === '/posix/') $entry = substr($entry, 7); + return $entry; + } + } + closedir($res); + return false; +} + + +/** + Function to get the timezone of the Linux system + (c) 2012 Marius Cramer, pixcept KG, m.cramer@pixcept.de + */ function get_system_timezone() { - $timezone = false; - if(file_exists('/etc/timezone') && is_readable('/etc/timezone')) { - $timezone = trim(file_get_contents('/etc/timezone')); - if(file_exists('/usr/share/zoneinfo/' . $timezone) == false) $timezone = false; - } - - if(!$timezone && is_link('/etc/localtime')) { - $timezone = readlink('/etc/localtime'); - $timezone = str_replace('/usr/share/zoneinfo/', '', $timezone); - if(substr($timezone, 0, 6) === 'posix/') $timezone = substr($timezone, 6); - } elseif(!$timezone) { - $hash = md5_file('/etc/localtime'); - $timezone = find_hash_file($hash, '/usr/share/zoneinfo'); - } - - if(!$timezone) { - exec('date +%Z', $tzinfo); - $timezone = $tzinfo[0]; - } - - return $timezone; + $timezone = false; + if(file_exists('/etc/timezone') && is_readable('/etc/timezone')) { + $timezone = trim(file_get_contents('/etc/timezone')); + if(file_exists('/usr/share/zoneinfo/' . $timezone) == false) $timezone = false; + } + + if(!$timezone && is_link('/etc/localtime')) { + $timezone = readlink('/etc/localtime'); + $timezone = str_replace('/usr/share/zoneinfo/', '', $timezone); + if(substr($timezone, 0, 6) === 'posix/') $timezone = substr($timezone, 6); + } elseif(!$timezone) { + $hash = md5_file('/etc/localtime'); + $timezone = find_hash_file($hash, '/usr/share/zoneinfo'); + } + + if(!$timezone) { + exec('date +%Z', $tzinfo); + $timezone = $tzinfo[0]; + } + + return $timezone; } diff --git a/install/lib/installer_base.lib.php b/install/lib/installer_base.lib.php index ba2e17929d32b962d7b1274d99f9e1de55832be0..14d054ac429e1e8d61b43d70e146e30320f421a9 100644 --- a/install/lib/installer_base.lib.php +++ b/install/lib/installer_base.lib.php @@ -53,7 +53,7 @@ class installer_base { } public function warning($msg) { - echo('WARNING: '.$msg."\n"); + echo 'WARNING: '.$msg."\n"; } public function simple_query($query, $answers, $default) { @@ -86,7 +86,7 @@ class installer_base { return $answer; } - public function free_query($query,$default) { + public function free_query($query, $default) { swrite($this->lng($query).' ['.$default.']: '); $input = sread(); @@ -141,6 +141,8 @@ class installer_base { } /** Create the database for ISPConfig */ + + public function configure_database() { global $conf; @@ -159,10 +161,10 @@ class installer_base { } else { if($conf['mysql']['admin_password'] == '') { caselog("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." ".escapeshellarg($conf['mysql']['database'])." < '".ISPC_INSTALL_ROOT."/install/sql/ispconfig3.sql' &> /dev/null", - __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in ispconfig3.sql'); + __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in ispconfig3.sql'); } else { caselog("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." -p".escapeshellarg($conf['mysql']['admin_password'])." ".escapeshellarg($conf['mysql']['database'])." < '".ISPC_INSTALL_ROOT."/install/sql/ispconfig3.sql' &> /dev/null", - __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in ispconfig3.sql'); + __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in ispconfig3.sql'); } $db_tables = $this->db->getTables(); if(count($db_tables) == 0) { @@ -194,8 +196,8 @@ class installer_base { //* Create the ISPConfig database user in the local database $query = 'GRANT SELECT, INSERT, UPDATE, DELETE ON '.$conf['mysql']['database'].".* " - ."TO '".$conf['mysql']['ispconfig_user']."'@'".$from_host."' " - ."IDENTIFIED BY '".$conf['mysql']['ispconfig_password']."';"; + ."TO '".$conf['mysql']['ispconfig_user']."'@'".$from_host."' " + ."IDENTIFIED BY '".$conf['mysql']['ispconfig_password']."';"; if(!$this->db->query($query)) { $this->error('Unable to create database user: '.$conf['mysql']['ispconfig_user'].' Error: '.$this->db->errorMessage); } @@ -360,140 +362,140 @@ class installer_base { } if(count($hosts) > 0) { - foreach($hosts as $host => $value) { - /* + foreach($hosts as $host => $value) { + /* * If a pwd exists, this means, we have to add the new user (and his pwd). * if not, the user already exists and we do not need the pwd */ - if ($value['pwd'] != ''){ - $query = "CREATE USER '".$value['user']."'@'".$host."' IDENTIFIED BY '" . $value['pwd'] . "'"; - if ($verbose){ - echo "\n\n" . $query ."\n"; + if ($value['pwd'] != ''){ + $query = "CREATE USER '".$value['user']."'@'".$host."' IDENTIFIED BY '" . $value['pwd'] . "'"; + if ($verbose){ + echo "\n\n" . $query ."\n"; + } + $this->dbmaster->query($query); // ignore the error } - $this->dbmaster->query($query); // ignore the error - } - /* + /* * Try to delete all rights of the user in case that it exists. * In Case that it will not exist, do nothing (ignore the error!) */ - $query = "REVOKE ALL PRIVILEGES, GRANT OPTION FROM '".$value['user']."'@'".$host."' "; - if ($verbose){ + $query = "REVOKE ALL PRIVILEGES, GRANT OPTION FROM '".$value['user']."'@'".$host."' "; + if ($verbose){ echo "\n\n" . $query ."\n"; - } - $this->dbmaster->query($query); // ignore the error + } + $this->dbmaster->query($query); // ignore the error - //* Create the ISPConfig database user in the remote database - $query = "GRANT SELECT ON ".$value['db'].".`server` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } + //* Create the ISPConfig database user in the remote database + $query = "GRANT SELECT ON ".$value['db'].".`server` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - $query = "GRANT SELECT, INSERT ON ".$value['db'].".`sys_log` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } + $query = "GRANT SELECT, INSERT ON ".$value['db'].".`sys_log` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - $query = "GRANT SELECT, UPDATE(`status`, `error`) ON ".$value['db'].".`sys_datalog` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } + $query = "GRANT SELECT, UPDATE(`status`, `error`) ON ".$value['db'].".`sys_datalog` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - $query = "GRANT SELECT, UPDATE(`status`) ON ".$value['db'].".`software_update_inst` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } + $query = "GRANT SELECT, UPDATE(`status`) ON ".$value['db'].".`software_update_inst` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - $query = "GRANT SELECT, UPDATE(`updated`) ON ".$value['db'].".`server` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } + $query = "GRANT SELECT, UPDATE(`updated`) ON ".$value['db'].".`server` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - $query = "GRANT SELECT, UPDATE (`ssl_request`, `ssl_cert`, `ssl_action`, `ssl_key`) ON ".$value['db'].".`web_domain` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } + $query = "GRANT SELECT, UPDATE (`ssl_request`, `ssl_cert`, `ssl_action`, `ssl_key`) ON ".$value['db'].".`web_domain` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - $query = "GRANT SELECT ON ".$value['db'].".`sys_group` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } + $query = "GRANT SELECT ON ".$value['db'].".`sys_group` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - $query = "GRANT SELECT, UPDATE (`action_state`, `response`) ON ".$value['db'].".`sys_remoteaction` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } + $query = "GRANT SELECT, UPDATE (`action_state`, `response`) ON ".$value['db'].".`sys_remoteaction` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - $query = "GRANT SELECT, INSERT , DELETE ON ".$value['db'].".`monitor_data` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } + $query = "GRANT SELECT, INSERT , DELETE ON ".$value['db'].".`monitor_data` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - $query = "GRANT SELECT, INSERT, UPDATE ON ".$value['db'].".`mail_traffic` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } + $query = "GRANT SELECT, INSERT, UPDATE ON ".$value['db'].".`mail_traffic` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - $query = "GRANT SELECT, INSERT, UPDATE ON ".$value['db'].".`web_traffic` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } + $query = "GRANT SELECT, INSERT, UPDATE ON ".$value['db'].".`web_traffic` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - $query = "GRANT SELECT, UPDATE ON ".$value['db'].".`aps_instances` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } - - $query = "GRANT SELECT, INSERT, DELETE ON ".$value['db'].".`web_backup` TO '".$value['user']."'@'".$host."' "; - if ($verbose){ - echo $query ."\n"; - } - if(!$this->dbmaster->query($query)) { - $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); - } + $query = "GRANT SELECT, UPDATE ON ".$value['db'].".`aps_instances` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - } + $query = "GRANT SELECT, INSERT, DELETE ON ".$value['db'].".`web_backup` TO '".$value['user']."'@'".$host."' "; + if ($verbose){ + echo $query ."\n"; + } + if(!$this->dbmaster->query($query)) { + $this->warning('Unable to set rights of user in master database: '.$value['db']."\n Query: ".$query."\n Error: ".$this->dbmaster->errorMessage); + } - /* + } + + /* * It is all done. Relod the rights... */ - $this->dbmaster->query('FLUSH PRIVILEGES;'); + $this->dbmaster->query('FLUSH PRIVILEGES;'); } } @@ -528,17 +530,17 @@ class installer_base { if (is_dir($config_dir)) { if(is_file($config_dir.'/'.$jk_init)) copy($config_dir.'/'.$jk_init, $config_dir.'/'.$jk_init.'~'); if(is_file($config_dir.'/'.$jk_chrootsh.'.master')) copy($config_dir.'/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh.'~'); - - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_init.'.master')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_init.'.master', $config_dir.'/'.$jk_init); - } else { - copy('tpl/'.$jk_init.'.master', $config_dir.'/'.$jk_init); - } - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_chrootsh.'.master')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh); - } else { - copy('tpl/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh); - } + + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_init.'.master')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_init.'.master', $config_dir.'/'.$jk_init); + } else { + copy('tpl/'.$jk_init.'.master', $config_dir.'/'.$jk_init); + } + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_chrootsh.'.master')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh); + } else { + copy('tpl/'.$jk_chrootsh.'.master', $config_dir.'/'.$jk_chrootsh); + } } //* help jailkit fo find its ini files @@ -583,13 +585,13 @@ class installer_base { $domainAll = $this->db->queryAllRecords("SELECT domain FROM mail_mailinglist GROUP BY domain"); if(is_array($domainAll)) { - foreach($domainAll as $domain) - { - if ($domainAll[0]['domain'] == $domain['domain']) - $virtual_domains .= "'".$domain['domain']."'"; - else - $virtual_domains .= ", '".$domain['domain']."'"; - } + foreach($domainAll as $domain) + { + if ($domainAll[0]['domain'] == $domain['domain']) + $virtual_domains .= "'".$domain['domain']."'"; + else + $virtual_domains .= ", '".$domain['domain']."'"; + } } } else @@ -599,31 +601,31 @@ class installer_base { if(!isset($old_options['DEFAULT_SERVER_LANGUAGE'])) $old_options['DEFAULT_SERVER_LANGUAGE'] = ''; $content = str_replace('{default_language}', $old_options['DEFAULT_SERVER_LANGUAGE'], $content); $content = str_replace('{virtual_domains}', $virtual_domains, $content); - + wf($full_file_name, $content); - + //* Write virtual_to_transport.sh script $config_dir = $conf['mailman']['config_dir'].'/'; $full_file_name = $config_dir.'virtual_to_transport.sh'; - + //* Backup exiting virtual_to_transport.sh script if(is_file($full_file_name)) { copy($full_file_name, $config_dir.'virtual_to_transport.sh~'); } - + if(is_dir('/etc/mailman')) { if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name); - } else { - copy('tpl/mailman-virtual_to_transport.sh',$full_file_name); - } - chgrp($full_file_name,'list'); - chmod($full_file_name,0750); - } - + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/mailman-virtual_to_transport.sh', $full_file_name); + } else { + copy('tpl/mailman-virtual_to_transport.sh', $full_file_name); + } + chgrp($full_file_name, 'list'); + chmod($full_file_name, 0750); + } + //* Create aliasaes exec('/usr/lib/mailman/bin/genaliases 2>/dev/null'); - + } public function configure_postfix($options = '') { @@ -667,9 +669,9 @@ class installer_base { //* Changing mode and group of the new created config files. caselog('chmod o= '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null', - __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed'); + __FILE__, __LINE__, 'chmod on mysql-virtual_*.cf*', 'chmod on mysql-virtual_*.cf* failed'); caselog('chgrp '.$cf['group'].' '.$config_dir.'/mysql-virtual_*.cf* &> /dev/null', - __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed'); + __FILE__, __LINE__, 'chgrp on mysql-virtual_*.cf*', 'chgrp on mysql-virtual_*.cf* failed'); //* Creating virtual mail user and group $command = 'groupadd -g '.$cf['vmail_groupid'].' '.$cf['vmail_groupname']; @@ -686,31 +688,31 @@ class installer_base { //* If there are RBL's defined, format the list and add them to smtp_recipient_restrictions to prevent removeal after an update $rbl_list = ''; if (@isset($server_ini_array['mail']['realtime_blackhole_list']) && $server_ini_array['mail']['realtime_blackhole_list'] != '') { - $rbl_hosts = explode(",",str_replace(" ", "", $server_ini_array['mail']['realtime_blackhole_list'])); + $rbl_hosts = explode(",", str_replace(" ", "", $server_ini_array['mail']['realtime_blackhole_list'])); foreach ($rbl_hosts as $key => $value) { $rbl_list .= ", reject_rbl_client ". $value; } } unset($rbl_hosts); unset($server_ini_array); - - $postconf_placeholders = array('{config_dir}' => $config_dir, - '{vmail_mailbox_base}' => $cf['vmail_mailbox_base'], - '{vmail_userid}' => $cf['vmail_userid'], - '{vmail_groupid}' => $cf['vmail_groupid'], - '{rbl_list}' => $rbl_list); - - $postconf_tpl = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_postfix.conf.master', 'tpl/debian_postfix.conf.master'); - $postconf_tpl = strtr($postconf_tpl, $postconf_placeholders); - $postconf_commands = array_filter(explode("\n", $postconf_tpl)); // read and remove empty lines + + $postconf_placeholders = array('{config_dir}' => $config_dir, + '{vmail_mailbox_base}' => $cf['vmail_mailbox_base'], + '{vmail_userid}' => $cf['vmail_userid'], + '{vmail_groupid}' => $cf['vmail_groupid'], + '{rbl_list}' => $rbl_list); + + $postconf_tpl = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_postfix.conf.master', 'tpl/debian_postfix.conf.master'); + $postconf_tpl = strtr($postconf_tpl, $postconf_placeholders); + $postconf_commands = array_filter(explode("\n", $postconf_tpl)); // read and remove empty lines //* These postconf commands will be executed on installation only if($this->is_update == false) { - $postconf_commands = array_merge($postconf_commands,array( - 'myhostname = '.$conf['hostname'], - 'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain', - 'mynetworks = 127.0.0.0/8 [::1]/128' - )); + $postconf_commands = array_merge($postconf_commands, array( + 'myhostname = '.$conf['hostname'], + 'mydestination = '.$conf['hostname'].', localhost, localhost.localdomain', + 'mynetworks = 127.0.0.0/8 [::1]/128' + )); } //* Create the header and body check files @@ -737,10 +739,10 @@ class installer_base { caselog($command." &> /dev/null", __FILE__, __LINE__, 'EXECUTED: '.$command, 'Failed to execute the command '.$command); } - if(!stristr($options,'dont-create-certs')) { + if(!stristr($options, 'dont-create-certs')) { //* Create the SSL certificate $command = 'cd '.$config_dir.'; ' - .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:4096 -nodes -keyout smtpd.key -keyform PEM -days 3650 -x509'; + .'openssl req -new -outform PEM -out smtpd.cert -newkey rsa:4096 -nodes -keyout smtpd.key -keyform PEM -days 3650 -x509'; exec($command); $command = 'chmod o= '.$config_dir.'/smtpd.key'; @@ -761,8 +763,8 @@ class installer_base { $configfile = $config_dir.'/master.cf'; $content = rf($configfile); $content = str_replace('flags=DRhu user=vmail argv=/usr/bin/maildrop -d ${recipient}', - 'flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d '.$cf['vmail_username'].' ${extension} ${recipient} ${user} ${nexthop} ${sender}', - $content); + 'flags=DRhu user='.$cf['vmail_username'].' argv=/usr/bin/maildrop -d '.$cf['vmail_username'].' ${extension} ${recipient} ${user} ${nexthop} ${sender}', + $content); wf($configfile, $content); //* Writing the Maildrop mailfilter file @@ -793,8 +795,8 @@ class installer_base { global $conf; //* Get saslsauthd version - exec('saslauthd -v 2>&1',$out); - $parts = explode(' ',$out[0]); + exec('saslauthd -v 2>&1', $out); + $parts = explode(' ', $out[0]); $saslversion = $parts[1]; unset($parts); unset($out); @@ -807,14 +809,14 @@ class installer_base { $configfile = 'sasl_smtpd.conf'; } - if(is_file($conf['postfix']['config_dir'].'/sasl/smtpd.conf')) copy($conf['postfix']['config_dir'].'/sasl/smtpd.conf',$conf['postfix']['config_dir'].'/sasl/smtpd.conf~'); + if(is_file($conf['postfix']['config_dir'].'/sasl/smtpd.conf')) copy($conf['postfix']['config_dir'].'/sasl/smtpd.conf', $conf['postfix']['config_dir'].'/sasl/smtpd.conf~'); if(is_file($conf['postfix']['config_dir'].'/sasl/smtpd.conf~')) chmod($conf['postfix']['config_dir'].'/sasl/smtpd.conf~', 0400); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master'); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_ip}',$conf['mysql']['ip'],$content); - wf($conf['postfix']['config_dir'].'/sasl/smtpd.conf',$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content); + wf($conf['postfix']['config_dir'].'/sasl/smtpd.conf', $content); // TODO: Chmod and chown on the config file @@ -824,21 +826,21 @@ class installer_base { // Edit the file /etc/default/saslauthd $configfile = $conf['saslauthd']['config']; - if(is_file($configfile)) copy($configfile,$configfile.'~'); + if(is_file($configfile)) copy($configfile, $configfile.'~'); if(is_file($configfile.'~')) chmod($configfile.'~', 0400); $content = rf($configfile); - $content = str_replace('START=no','START=yes',$content); + $content = str_replace('START=no', 'START=yes', $content); // Debian - $content = str_replace('OPTIONS="-c"','OPTIONS="-m /var/spool/postfix/var/run/saslauthd -r"',$content); + $content = str_replace('OPTIONS="-c"', 'OPTIONS="-m /var/spool/postfix/var/run/saslauthd -r"', $content); // Ubuntu - $content = str_replace('OPTIONS="-c -m /var/run/saslauthd"','OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r"',$content); - wf($configfile,$content); + $content = str_replace('OPTIONS="-c -m /var/run/saslauthd"', 'OPTIONS="-c -m /var/spool/postfix/var/run/saslauthd -r"', $content); + wf($configfile, $content); // Edit the file /etc/init.d/saslauthd $configfile = $conf['init_scripts'].'/'.$conf['saslauthd']['init_script']; $content = rf($configfile); - $content = str_replace('PIDFILE=$RUN_DIR/saslauthd.pid','PIDFILE="/var/spool/postfix/var/run/${NAME}/saslauthd.pid"',$content); - wf($configfile,$content); + $content = str_replace('PIDFILE=$RUN_DIR/saslauthd.pid', 'PIDFILE="/var/spool/postfix/var/run/${NAME}/saslauthd.pid"', $content); + wf($configfile, $content); // add the postfix user to the sasl group (at least necessary for Ubuntu 8.04 and most likely Debian Lenny as well. exec('adduser postfix sasl'); @@ -878,10 +880,10 @@ class installer_base { } chmod($config_dir.'/'.$configfile.'~', 0400); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master'); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); wf($config_dir.'/'.$configfile, $content); chmod($config_dir.'/'.$configfile, 0660); @@ -915,9 +917,9 @@ class installer_base { } $content = rf($conf['postfix']['config_dir'].'/master.cf'); // Only add the content if we had not addded it before - if(!stristr($content,'dovecot/deliver')) { + if(!stristr($content, 'dovecot/deliver')) { $deliver_content = 'dovecot unix - n n - - pipe'."\n".' flags=DROhu user=vmail:vmail argv=/usr/lib/dovecot/deliver -f ${sender} -d ${user}@${nexthop}'; - af($conf['postfix']['config_dir'].'/master.cf',$deliver_content); + af($conf['postfix']['config_dir'].'/master.cf', $deliver_content); } unset($content); unset($deliver_content); @@ -926,14 +928,14 @@ class installer_base { //* Reconfigure postfix to use dovecot authentication // Adding the amavisd commands to the postfix configuration $postconf_commands = array ( - 'dovecot_destination_recipient_limit = 1', - 'virtual_transport = dovecot', - 'smtpd_sasl_type = dovecot', - 'smtpd_sasl_path = private/auth' + 'dovecot_destination_recipient_limit = 1', + 'virtual_transport = dovecot', + 'smtpd_sasl_type = dovecot', + 'smtpd_sasl_path = private/auth' ); // Make a backup copy of the main.cf file - copy($conf['postfix']['config_dir'].'/main.cf',$conf['postfix']['config_dir'].'/main.cf~3'); + copy($conf['postfix']['config_dir'].'/main.cf', $conf['postfix']['config_dir'].'/main.cf~3'); // Executing the postconf commands foreach($postconf_commands as $cmd) { @@ -948,25 +950,25 @@ class installer_base { } //* Get the dovecot version - exec('dovecot --version',$tmp); - $parts = explode('.',trim($tmp[0])); + exec('dovecot --version', $tmp); + $parts = explode('.', trim($tmp[0])); $dovecot_version = $parts[0]; unset($tmp); unset($parts); //* Copy dovecot configuration file if($dovecot_version == 2) { - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot2.conf.master')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot2.conf.master', $config_dir.'/'.$configfile); - } else { - copy('tpl/debian_dovecot2.conf.master',$config_dir.'/'.$configfile); - } + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot2.conf.master')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot2.conf.master', $config_dir.'/'.$configfile); + } else { + copy('tpl/debian_dovecot2.conf.master', $config_dir.'/'.$configfile); + } } else { - if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot.conf.master')) { - copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot.conf.master', $config_dir.'/'.$configfile); - } else { - copy('tpl/debian_dovecot.conf.master',$config_dir.'/'.$configfile); - } + if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot.conf.master')) { + copy($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot.conf.master', $config_dir.'/'.$configfile); + } else { + copy('tpl/debian_dovecot.conf.master', $config_dir.'/'.$configfile); + } } //* dovecot-sql.conf @@ -976,10 +978,10 @@ class installer_base { } if(is_file($config_dir.'/'.$configfile.'~')) chmod($config_dir.'/'.$configfile.'~', 0400); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/debian_dovecot-sql.conf.master', 'tpl/debian_dovecot-sql.conf.master'); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); wf($config_dir.'/'.$configfile, $content); chmod($config_dir.'/'.$configfile, 0600); @@ -993,15 +995,15 @@ class installer_base { // amavisd user config file $configfile = 'amavisd_user_config'; - if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user')) copy($conf['amavis']['config_dir'].'/conf.d/50-user',$conf['amavis']['config_dir'].'/50-user~'); + if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user')) copy($conf['amavis']['config_dir'].'/conf.d/50-user', $conf['amavis']['config_dir'].'/50-user~'); if(is_file($conf['amavis']['config_dir'].'/conf.d/50-user~')) chmod($conf['amavis']['config_dir'].'/conf.d/50-user~', 0400); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master'); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_port}',$conf['mysql']['port'],$content); - $content = str_replace('{mysql_server_ip}',$conf['mysql']['ip'],$content); - wf($conf['amavis']['config_dir'].'/conf.d/50-user',$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_port}', $conf['mysql']['port'], $content); + $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content); + wf($conf['amavis']['config_dir'].'/conf.d/50-user', $content); // TODO: chmod and chown on the config file @@ -1017,7 +1019,7 @@ class installer_base { } // Make a backup copy of the main.cf file - copy($conf['postfix']['config_dir'].'/main.cf',$conf['postfix']['config_dir'].'/main.cf~2'); + copy($conf['postfix']['config_dir'].'/main.cf', $conf['postfix']['config_dir'].'/main.cf~2'); // Executing the postconf commands foreach($postconf_commands as $cmd) { @@ -1026,13 +1028,13 @@ class installer_base { } // Append the configuration for amavisd to the master.cf file - if(is_file($conf['postfix']['config_dir'].'/master.cf')) copy($conf['postfix']['config_dir'].'/master.cf',$conf['postfix']['config_dir'].'/master.cf~'); + if(is_file($conf['postfix']['config_dir'].'/master.cf')) copy($conf['postfix']['config_dir'].'/master.cf', $conf['postfix']['config_dir'].'/master.cf~'); $content = rf($conf['postfix']['config_dir'].'/master.cf'); // Only add the content if we had not addded it before - if(!stristr($content,'127.0.0.1:10025')) { + if(!stristr($content, '127.0.0.1:10025')) { unset($content); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/master_cf_amavis.master', 'tpl/master_cf_amavis.master'); - af($conf['postfix']['config_dir'].'/master.cf',$content); + af($conf['postfix']['config_dir'].'/master.cf', $content); } unset($content); @@ -1103,12 +1105,12 @@ class installer_base { exec('echo "yes" > '.$config_dir.'/conf/DisplayDotFiles'); if(is_file('/etc/default/pure-ftpd-common')) { - replaceLine('/etc/default/pure-ftpd-common','STANDALONE_OR_INETD=inetd','STANDALONE_OR_INETD=standalone',1,0); - replaceLine('/etc/default/pure-ftpd-common','VIRTUALCHROOT=false','VIRTUALCHROOT=true',1,0); + replaceLine('/etc/default/pure-ftpd-common', 'STANDALONE_OR_INETD=inetd', 'STANDALONE_OR_INETD=standalone', 1, 0); + replaceLine('/etc/default/pure-ftpd-common', 'VIRTUALCHROOT=false', 'VIRTUALCHROOT=true', 1, 0); } if(is_file('/etc/inetd.conf')) { - replaceLine('/etc/inetd.conf','/usr/sbin/pure-ftpd-wrapper','#ftp stream tcp nowait root /usr/sbin/tcpd /usr/sbin/pure-ftpd-wrapper',0,0); + replaceLine('/etc/inetd.conf', '/usr/sbin/pure-ftpd-wrapper', '#ftp stream tcp nowait root /usr/sbin/tcpd /usr/sbin/pure-ftpd-wrapper', 0, 0); exec($this->getinitcommand('openbsd-inetd', 'restart')); //if(is_file($conf['init_scripts'].'/'.'openbsd-inetd')) exec($conf['init_scripts'].'/'.'openbsd-inetd restart'); } @@ -1121,15 +1123,15 @@ class installer_base { // configure pam for SMTP authentication agains the ispconfig database $configfile = 'mydns.conf'; - if(is_file($conf['mydns']['config_dir'].'/'.$configfile)) copy($conf['mydns']['config_dir'].'/'.$configfile,$conf['mydns']['config_dir'].'/'.$configfile.'~'); + if(is_file($conf['mydns']['config_dir'].'/'.$configfile)) copy($conf['mydns']['config_dir'].'/'.$configfile, $conf['mydns']['config_dir'].'/'.$configfile.'~'); if(is_file($conf['mydns']['config_dir'].'/'.$configfile.'~')) chmod($conf['mydns']['config_dir'].'/'.$configfile.'~', 0400); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master'); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content); - $content = str_replace('{server_id}',$conf['server_id'],$content); - wf($conf['mydns']['config_dir'].'/'.$configfile,$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); + $content = str_replace('{server_id}', $conf['server_id'], $content); + wf($conf['mydns']['config_dir'].'/'.$configfile, $content); chmod($conf['mydns']['config_dir'].'/'.$configfile, 0600); chown($conf['mydns']['config_dir'].'/'.$configfile, 'root'); chgrp($conf['mydns']['config_dir'].'/'.$configfile, 'root'); @@ -1156,22 +1158,22 @@ class installer_base { //* load the powerdns databse dump if($conf['mysql']['admin_password'] == '') { caselog("mysql --default-character-set=".$conf['mysql']['charset']." -h '".$conf['mysql']['host']."' -u '".$conf['mysql']['admin_user']."' '".$conf['powerdns']['database']."' < '".ISPC_INSTALL_ROOT."/install/sql/powerdns.sql' &> /dev/null", - __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql'); + __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql'); } else { caselog("mysql --default-character-set=".$conf['mysql']['charset']." -h '".$conf['mysql']['host']."' -u '".$conf['mysql']['admin_user']."' -p'".$conf['mysql']['admin_password']."' '".$conf['powerdns']['database']."' < '".ISPC_INSTALL_ROOT."/install/sql/powerdns.sql' &> /dev/null", - __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql'); + __FILE__, __LINE__, 'read in ispconfig3.sql', 'could not read in powerdns.sql'); } //* Create the powerdns config file $configfile = 'pdns.local'; - if(is_file($conf['powerdns']['config_dir'].'/'.$configfile)) copy($conf['powerdns']['config_dir'].'/'.$configfile,$conf['powerdns']['config_dir'].'/'.$configfile.'~'); + if(is_file($conf['powerdns']['config_dir'].'/'.$configfile)) copy($conf['powerdns']['config_dir'].'/'.$configfile, $conf['powerdns']['config_dir'].'/'.$configfile.'~'); if(is_file($conf['powerdns']['config_dir'].'/'.$configfile.'~')) chmod($conf['powerdns']['config_dir'].'/'.$configfile.'~', 0400); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master'); - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{powerdns_database}',$conf['powerdns']['database'],$content); - $content = str_replace('{mysql_server_host}',$conf['mysql']['host'],$content); - wf($conf['powerdns']['config_dir'].'/'.$configfile,$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{powerdns_database}', $conf['powerdns']['database'], $content); + $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); + wf($conf['powerdns']['config_dir'].'/'.$configfile, $content); chmod($conf['powerdns']['config_dir'].'/'.$configfile, 0600); chown($conf['powerdns']['config_dir'].'/'.$configfile, 'root'); chgrp($conf['powerdns']['config_dir'].'/'.$configfile, 'root'); @@ -1182,19 +1184,19 @@ class installer_base { public function configure_bind() { global $conf; - //* Check if the zonefile directory has a slash at the end - $content=$conf['bind']['bind_zonefiles_dir']; - if(substr($content,-1,1) != '/') { - $content .= '/'; + //* Check if the zonefile directory has a slash at the end + $content=$conf['bind']['bind_zonefiles_dir']; + if(substr($content, -1, 1) != '/') { + $content .= '/'; } //* Create the slave subdirectory - $content .= 'slave'; - if(!@is_dir($content)) mkdir($content, 0770, true); + $content .= 'slave'; + if(!@is_dir($content)) mkdir($content, 0770, true); - //* Chown the slave subdirectory to $conf['bind']['bind_user'] - chown($content, $conf['bind']['bind_user']); - chgrp($content, $conf['bind']['bind_group']); + //* Chown the slave subdirectory to $conf['bind']['bind_user'] + chown($content, $conf['bind']['bind_user']); + chgrp($content, $conf['bind']['bind_group']); } @@ -1208,19 +1210,19 @@ class installer_base { if(!@is_dir($conf['ispconfig_log_dir'].'/httpd')) mkdir($conf['ispconfig_log_dir'].'/httpd', 0755, true); if(is_file('/etc/suphp/suphp.conf')) { - replaceLine('/etc/suphp/suphp.conf','php=php:/usr/bin','x-httpd-suphp="php:/usr/bin/php-cgi"',0); + replaceLine('/etc/suphp/suphp.conf', 'php=php:/usr/bin', 'x-httpd-suphp="php:/usr/bin/php-cgi"', 0); //replaceLine('/etc/suphp/suphp.conf','docroot=','docroot=/var/clients',0); - replaceLine('/etc/suphp/suphp.conf','umask=0077','umask=0022',0); + replaceLine('/etc/suphp/suphp.conf', 'umask=0077', 'umask=0022', 0); } if(is_file('/etc/apache2/sites-enabled/000-default')) { - replaceLine('/etc/apache2/sites-available/000-default','NameVirtualHost *','NameVirtualHost *:80',1,0); - replaceLine('/etc/apache2/sites-available/000-default','','',1,0); + replaceLine('/etc/apache2/sites-available/000-default', 'NameVirtualHost *', 'NameVirtualHost *:80', 1, 0); + replaceLine('/etc/apache2/sites-available/000-default', '', '', 1, 0); } if(is_file('/etc/apache2/ports.conf')) { // add a line "Listen 443" to ports conf if line does not exist - replaceLine('/etc/apache2/ports.conf','Listen 443','Listen 443',1); + replaceLine('/etc/apache2/ports.conf', 'Listen 443', 'Listen 443', 1); } @@ -1240,7 +1242,7 @@ class installer_base { } else { $ip_address = $rec['ip_address']; } - $ports = explode(',',$rec['virtualhost_port']); + $ports = explode(',', $rec['virtualhost_port']); if(is_array($ports)) { foreach($ports as $port) { $port = intval($port); @@ -1253,29 +1255,29 @@ class installer_base { } $content .= "\n"; - wf($vhost_conf_dir.'/ispconfig.conf',$content); + wf($vhost_conf_dir.'/ispconfig.conf', $content); if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.conf')) { - symlink($vhost_conf_dir.'/ispconfig.conf',$vhost_conf_enabled_dir.'/000-ispconfig.conf'); + symlink($vhost_conf_dir.'/ispconfig.conf', $vhost_conf_enabled_dir.'/000-ispconfig.conf'); } //* make sure that webalizer finds its config file when it is directly in /etc if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) { mkdir('/etc/webalizer'); - symlink('/etc/webalizer.conf','/etc/webalizer/webalizer.conf'); + symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf'); } if(is_file('/etc/webalizer/webalizer.conf')) { // Change webalizer mode to incremental - replaceLine('/etc/webalizer/webalizer.conf','#IncrementalName','IncrementalName webalizer.current',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#Incremental','Incremental yes',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#HistoryName','HistoryName webalizer.hist',0,0); + replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental yes', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName webalizer.hist', 0, 0); } // Check the awsatst script if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools'); - if(!file_exists('/usr/share/awstats/tools/awstats_buildstaticpages.pl') && file_exists('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl')) symlink('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl','/usr/share/awstats/tools/awstats_buildstaticpages.pl'); - if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local','LogFormat=4','LogFormat=1',0,1); + if(!file_exists('/usr/share/awstats/tools/awstats_buildstaticpages.pl') && file_exists('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl')) symlink('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl', '/usr/share/awstats/tools/awstats_buildstaticpages.pl'); + if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local', 'LogFormat=4', 'LogFormat=1', 0, 1); //* add a sshusers group $command = 'groupadd sshusers'; @@ -1293,20 +1295,20 @@ class installer_base { //* make sure that webalizer finds its config file when it is directly in /etc if(@is_file('/etc/webalizer.conf') && !@is_dir('/etc/webalizer')) { mkdir('/etc/webalizer'); - symlink('/etc/webalizer.conf','/etc/webalizer/webalizer.conf'); + symlink('/etc/webalizer.conf', '/etc/webalizer/webalizer.conf'); } if(is_file('/etc/webalizer/webalizer.conf')) { // Change webalizer mode to incremental - replaceLine('/etc/webalizer/webalizer.conf','#IncrementalName','IncrementalName webalizer.current',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#Incremental','Incremental yes',0,0); - replaceLine('/etc/webalizer/webalizer.conf','#HistoryName','HistoryName webalizer.hist',0,0); + replaceLine('/etc/webalizer/webalizer.conf', '#IncrementalName', 'IncrementalName webalizer.current', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#Incremental', 'Incremental yes', 0, 0); + replaceLine('/etc/webalizer/webalizer.conf', '#HistoryName', 'HistoryName webalizer.hist', 0, 0); } // Check the awsatst script if(!is_dir('/usr/share/awstats/tools')) exec('mkdir -p /usr/share/awstats/tools'); - if(!file_exists('/usr/share/awstats/tools/awstats_buildstaticpages.pl') && file_exists('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl')) symlink('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl','/usr/share/awstats/tools/awstats_buildstaticpages.pl'); - if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local','LogFormat=4','LogFormat=1',0,1); + if(!file_exists('/usr/share/awstats/tools/awstats_buildstaticpages.pl') && file_exists('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl')) symlink('/usr/share/doc/awstats/examples/awstats_buildstaticpages.pl', '/usr/share/awstats/tools/awstats_buildstaticpages.pl'); + if(file_exists('/etc/awstats/awstats.conf.local')) replaceLine('/etc/awstats/awstats.conf.local', 'LogFormat=4', 'LogFormat=1', 0, 1); //* add a sshusers group $command = 'groupadd sshusers'; @@ -1344,8 +1346,8 @@ class installer_base { } public function configure_fail2ban() { - // To Do - } + // To Do + } public function configure_squid() { @@ -1355,13 +1357,13 @@ class installer_base { $server_name = $row["server_name"]; $configfile = 'squid.conf'; - if(is_file($conf["squid"]["config_dir"].'/'.$configfile)) copy($conf["squid"]["config_dir"].'/'.$configfile,$conf["squid"]["config_dir"].'/'.$configfile.'~'); + if(is_file($conf["squid"]["config_dir"].'/'.$configfile)) copy($conf["squid"]["config_dir"].'/'.$configfile, $conf["squid"]["config_dir"].'/'.$configfile.'~'); if(is_file($conf["squid"]["config_dir"].'/'.$configfile.'~')) exec('chmod 400 '.$conf["squid"]["config_dir"].'/'.$configfile.'~'); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', "tpl/".$configfile.".master"); - $content = str_replace('{server_name}',$server_name,$content); - $content = str_replace('{ip_address}',$ip_address, $content); - $content = str_replace('{config_dir}',$conf['squid']['config_dir'], $content); - wf($conf["squid"]["config_dir"].'/'.$configfile,$content); + $content = str_replace('{server_name}', $server_name, $content); + $content = str_replace('{ip_address}', $ip_address, $content); + $content = str_replace('{config_dir}', $conf['squid']['config_dir'], $content); + wf($conf["squid"]["config_dir"].'/'.$configfile, $content); exec('chmod 600 '.$conf["squid"]["config_dir"].'/'.$configfile); exec('chown root:root '.$conf["squid"]["config_dir"].'/'.$configfile); } @@ -1388,10 +1390,10 @@ class installer_base { @mkdir('/etc/Bastille', 0700); if(is_dir('/etc/Bastille.backup/firewall.d')) caselog('cp -pfr /etc/Bastille.backup/firewall.d /etc/Bastille/', __FILE__, __LINE__); if(is_file($conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master')) { - caselog('cp -f ' . $conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__); - } else { - caselog('cp -f tpl/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__); - } + caselog('cp -f ' . $conf['ispconfig_install_dir'].'/server/conf-custom/install/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__); + } else { + caselog('cp -f tpl/bastille-firewall.cfg.master /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__); + } caselog('chmod 644 /etc/Bastille/bastille-firewall.cfg', __FILE__, __LINE__); $content = rf('/etc/Bastille/bastille-firewall.cfg'); $content = str_replace('{DNS_SERVERS}', '', $content); @@ -1402,8 +1404,8 @@ class installer_base { $row = $this->db->queryOneRecord('SELECT * FROM '.$conf["mysql"]["database"].'.firewall WHERE server_id = '.intval($conf['server_id'])); if(trim($row['tcp_port']) != '' || trim($row['udp_port']) != '') { - $tcp_public_services = trim(str_replace(',',' ',$row['tcp_port'])); - $udp_public_services = trim(str_replace(',',' ',$row['udp_port'])); + $tcp_public_services = trim(str_replace(',', ' ', $row['tcp_port'])); + $udp_public_services = trim(str_replace(',', ' ', $row['udp_port'])); } else { $tcp_public_services = '21 22 25 53 80 110 143 443 3306 8080 10000'; $udp_public_services = '53'; @@ -1447,21 +1449,21 @@ class installer_base { //** Configure vlogger to use traffic logging to mysql (master) db $configfile = 'vlogger-dbi.conf'; - if(is_file($conf['vlogger']['config_dir'].'/'.$configfile)) copy($conf['vlogger']['config_dir'].'/'.$configfile,$conf['vlogger']['config_dir'].'/'.$configfile.'~'); + if(is_file($conf['vlogger']['config_dir'].'/'.$configfile)) copy($conf['vlogger']['config_dir'].'/'.$configfile, $conf['vlogger']['config_dir'].'/'.$configfile.'~'); if(is_file($conf['vlogger']['config_dir'].'/'.$configfile.'~')) chmod($conf['vlogger']['config_dir'].'/'.$configfile.'~', 0400); $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master'); if($conf['mysql']['master_slave_setup'] == 'y') { - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['master_ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['master_ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['master_database'],$content); - $content = str_replace('{mysql_server_ip}',$conf['mysql']['master_host'],$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['master_ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['master_ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['master_database'], $content); + $content = str_replace('{mysql_server_ip}', $conf['mysql']['master_host'], $content); } else { - $content = str_replace('{mysql_server_ispconfig_user}',$conf['mysql']['ispconfig_user'],$content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); - $content = str_replace('{mysql_server_database}',$conf['mysql']['database'],$content); - $content = str_replace('{mysql_server_ip}',$conf['mysql']['ip'],$content); + $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); + $content = str_replace('{mysql_server_ip}', $conf['mysql']['ip'], $content); } - wf($conf['vlogger']['config_dir'].'/'.$configfile,$content); + wf($conf['vlogger']['config_dir'].'/'.$configfile, $content); chmod($conf['vlogger']['config_dir'].'/'.$configfile, 0600); chown($conf['vlogger']['config_dir'].'/'.$configfile, 'root'); chgrp($conf['vlogger']['config_dir'].'/'.$configfile, 'root'); @@ -1523,7 +1525,7 @@ class installer_base { //* and create the symlink if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost'); if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) { - symlink($vhost_conf_dir.'/apps.vhost',$vhost_conf_enabled_dir.'/000-apps.vhost'); + symlink($vhost_conf_dir.'/apps.vhost', $vhost_conf_enabled_dir.'/000-apps.vhost'); } if(!is_file($conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter')) { @@ -1536,7 +1538,7 @@ class installer_base { exec('chmod +x '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps/.php-fcgi-starter'); exec('chown -R ispapps:ispapps '.$conf['web']['website_basedir'].'/php-fcgi-scripts/apps'); - } + } } if($conf['nginx']['installed'] == true){ $apps_vhost_user = escapeshellcmd($conf['web']['apps_vhost_user']); @@ -1576,7 +1578,7 @@ class installer_base { } $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']); - if(substr($socket_dir,-1) != '/') $socket_dir .= '/'; + if(substr($socket_dir, -1) != '/') $socket_dir .= '/'; if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir); $fpm_socket = $socket_dir.'apps.sock'; $cgi_socket = escapeshellcmd($conf['nginx']['cgi_socket']); @@ -1588,7 +1590,7 @@ class installer_base { //$content = str_replace('{fpm_port}', ($conf['nginx']['php_fpm_start_port']+1), $content); $content = str_replace('{fpm_socket}', $fpm_socket, $content); $content = str_replace('{cgi_socket}', $cgi_socket, $content); - + if(file_exists('/var/run/php5-fpm.sock')){ $use_tcp = '#'; $use_socket = ''; @@ -1615,7 +1617,7 @@ class installer_base { //* and create the symlink if(@is_link($vhost_conf_enabled_dir.'/apps.vhost')) unlink($vhost_conf_enabled_dir.'/apps.vhost'); if(!@is_link($vhost_conf_enabled_dir.'/000-apps.vhost')) { - symlink($vhost_conf_dir.'/apps.vhost',$vhost_conf_enabled_dir.'/000-apps.vhost'); + symlink($vhost_conf_dir.'/apps.vhost', $vhost_conf_enabled_dir.'/000-apps.vhost'); } } @@ -1632,13 +1634,13 @@ class installer_base { if(!@is_dir($install_dir.'/interface/ssl')) mkdir($install_dir.'/interface/ssl', 0755, true); - $ssl_pw = substr(md5(mt_rand()),0,6); + $ssl_pw = substr(md5(mt_rand()), 0, 6); exec("openssl genrsa -des3 -passout pass:$ssl_pw -out $ssl_key_file 4096"); exec("openssl req -new -passin pass:$ssl_pw -passout pass:$ssl_pw -key $ssl_key_file -out $ssl_csr_file"); exec("openssl req -x509 -passin pass:$ssl_pw -passout pass:$ssl_pw -key $ssl_key_file -in $ssl_csr_file -out $ssl_crt_file -days 3650"); exec("openssl rsa -passin pass:$ssl_pw -in $ssl_key_file -out $ssl_key_file.insecure"); - rename($ssl_key_file,$ssl_key_file.'.secure'); - rename($ssl_key_file.'.insecure',$ssl_key_file); + rename($ssl_key_file, $ssl_key_file.'.secure'); + rename($ssl_key_file.'.insecure', $ssl_key_file); } @@ -1680,7 +1682,7 @@ class installer_base { } $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/'.$configfile.'.master', 'tpl/'.$configfile.'.master'); $content = str_replace('{mysql_server_ispconfig_user}', $conf['mysql']['ispconfig_user'], $content); - $content = str_replace('{mysql_server_ispconfig_password}',$conf['mysql']['ispconfig_password'], $content); + $content = str_replace('{mysql_server_ispconfig_password}', $conf['mysql']['ispconfig_password'], $content); $content = str_replace('{mysql_server_database}', $conf['mysql']['database'], $content); $content = str_replace('{mysql_server_host}', $conf['mysql']['host'], $content); @@ -1736,9 +1738,9 @@ class installer_base { if (is_dir($dir)) { if ($dh = opendir($dir)) { while (($file = readdir($dh)) !== false) { - if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') { - include_once($install_dir.'/server/mods-available/'.$file); - $module_name = substr($file,0,-8); + if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') { + include_once $install_dir.'/server/mods-available/'.$file; + $module_name = substr($file, 0, -8); $tmp = new $module_name; if($tmp->onInstall()) { if(!@is_link($install_dir.'/server/mods-enabled/'.$file)) { @@ -1765,11 +1767,11 @@ class installer_base { while (($file = readdir($dh)) !== false) { if($conf['apache']['installed'] == true && $file == 'nginx_plugin.inc.php') continue; if($conf['nginx']['installed'] == true && $file == 'apache2_plugin.inc.php') continue; - if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') { - include_once($install_dir.'/server/plugins-available/'.$file); - $plugin_name = substr($file,0,-8); + if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') { + include_once $install_dir.'/server/plugins-available/'.$file; + $plugin_name = substr($file, 0, -8); $tmp = new $plugin_name; - if(method_exists($tmp,'onInstall') && $tmp->onInstall()) { + if(method_exists($tmp, 'onInstall') && $tmp->onInstall()) { if(!@is_link($install_dir.'/server/plugins-enabled/'.$file)) { @symlink($install_dir.'/server/plugins-available/'.$file, $install_dir.'/server/plugins-enabled/'.$file); //@symlink($install_dir.'/server/plugins-available/'.$file, '../plugins-enabled/'.$file); @@ -1824,14 +1826,14 @@ class installer_base { //* Make all interface language file directories group writable $handle = @opendir($install_dir.'/interface/web'); - while ($file = @readdir ($handle)) { + while ($file = @readdir($handle)) { if ($file != '.' && $file != '..') { if(@is_dir($install_dir.'/interface/web'.'/'.$file.'/lib/lang')) { $handle2 = opendir($install_dir.'/interface/web'.'/'.$file.'/lib/lang'); - chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang',0770); - while ($lang_file = @readdir ($handle2)) { + chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang', 0770); + while ($lang_file = @readdir($handle2)) { if ($lang_file != '.' && $lang_file != '..') { - chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file,0770); + chmod($install_dir.'/interface/web'.'/'.$file.'/lib/lang/'.$lang_file, 0770); } } } @@ -1846,7 +1848,7 @@ class installer_base { chmod($install_dir.'/server/lib/config.inc.php', 0600); chown($install_dir.'/server/lib/config.inc.php', 'root'); chgrp($install_dir.'/server/lib/config.inc.php', 'root'); - + //* Make sure thet the interface config file is readable by user ispconfig only chmod($install_dir.'/interface/lib/config.inc.php', 0600); chown($install_dir.'/interface/lib/config.inc.php', 'ispconfig'); @@ -1925,18 +1927,18 @@ class installer_base { if($this->is_update == false) { if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost'); if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) { - symlink($vhost_conf_dir.'/ispconfig.vhost',$vhost_conf_enabled_dir.'/000-ispconfig.vhost'); + symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost'); } } //if(!is_file('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter')) { - $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig_fcgi_starter.master', 'tpl/apache_ispconfig_fcgi_starter.master'); - $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content); - $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content); - @mkdir('/var/www/php-fcgi-scripts/ispconfig', 0755, true); - wf('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter', $content); - exec('chmod +x /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter'); - @symlink($install_dir.'/interface/web','/var/www/ispconfig'); - exec('chown -R ispconfig:ispconfig /var/www/php-fcgi-scripts/ispconfig'); + $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/apache_ispconfig_fcgi_starter.master', 'tpl/apache_ispconfig_fcgi_starter.master'); + $content = str_replace('{fastcgi_bin}', $conf['fastcgi']['fastcgi_bin'], $content); + $content = str_replace('{fastcgi_phpini_path}', $conf['fastcgi']['fastcgi_phpini_path'], $content); + @mkdir('/var/www/php-fcgi-scripts/ispconfig', 0755, true); + wf('/var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter', $content); + exec('chmod +x /var/www/php-fcgi-scripts/ispconfig/.php-fcgi-starter'); + @symlink($install_dir.'/interface/web', '/var/www/ispconfig'); + exec('chown -R ispconfig:ispconfig /var/www/php-fcgi-scripts/ispconfig'); //} } @@ -1960,7 +1962,7 @@ class installer_base { } $socket_dir = escapeshellcmd($conf['nginx']['php_fpm_socket_dir']); - if(substr($socket_dir,-1) != '/') $socket_dir .= '/'; + if(substr($socket_dir, -1) != '/') $socket_dir .= '/'; if(!is_dir($socket_dir)) exec('mkdir -p '.$socket_dir); $fpm_socket = $socket_dir.'ispconfig.sock'; @@ -1986,7 +1988,7 @@ class installer_base { if($this->is_update == false) { if(@is_link($vhost_conf_enabled_dir.'/ispconfig.vhost')) unlink($vhost_conf_enabled_dir.'/ispconfig.vhost'); if(!@is_link($vhost_conf_enabled_dir.'/000-ispconfig.vhost')) { - symlink($vhost_conf_dir.'/ispconfig.vhost',$vhost_conf_enabled_dir.'/000-ispconfig.vhost'); + symlink($vhost_conf_dir.'/ispconfig.vhost', $vhost_conf_enabled_dir.'/000-ispconfig.vhost'); } } } @@ -1999,8 +2001,8 @@ class installer_base { chmod($install_dir.'/server/scripts/update_from_tgz.sh', 0700); chown($install_dir.'/server/scripts/ispconfig_update.sh', 'root'); chmod($install_dir.'/server/scripts/ispconfig_update.sh', 0700); - if(!is_link('/usr/local/bin/ispconfig_update_from_svn.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh','/usr/local/bin/ispconfig_update_from_svn.sh'); - if(!is_link('/usr/local/bin/ispconfig_update.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh','/usr/local/bin/ispconfig_update.sh'); + if(!is_link('/usr/local/bin/ispconfig_update_from_svn.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh', '/usr/local/bin/ispconfig_update_from_svn.sh'); + if(!is_link('/usr/local/bin/ispconfig_update.sh')) symlink($install_dir.'/server/scripts/ispconfig_update.sh', '/usr/local/bin/ispconfig_update.sh'); //* Make the logs readable for the ispconfig user if(@is_file('/var/log/mail.log')) exec('chmod +r /var/log/mail.log'); @@ -2024,7 +2026,7 @@ class installer_base { exec('chmod 660 '. $conf['ispconfig_log_dir'].'/auth.log'); if(is_user('getmail')) { - rename($install_dir.'/server/scripts/run-getmail.sh','/usr/local/bin/run-getmail.sh'); + rename($install_dir.'/server/scripts/run-getmail.sh', '/usr/local/bin/run-getmail.sh'); if(is_user('getmail')) chown('/usr/local/bin/run-getmail.sh', 'getmail'); chmod('/usr/local/bin/run-getmail.sh', 0744); } @@ -2052,11 +2054,11 @@ class installer_base { fclose($fh); */ } - + //* Remove Domain module as its functions are available in the client module now if(@is_dir('/usr/local/ispconfig/interface/web/domain')) exec('rm -rf /usr/local/ispconfig/interface/web/domain'); - - + + } public function configure_dbserver() { @@ -2074,10 +2076,10 @@ class installer_base { } $content = rfsel($conf['ispconfig_install_dir'].'/server/conf-custom/install/mysql_clientdb.conf.master', 'tpl/mysql_clientdb.conf.master'); - $content = str_replace('{hostname}',$conf['mysql']['host'],$content); - $content = str_replace('{username}',$conf['mysql']['admin_user'],$content); - $content = str_replace('{password}',$conf['mysql']['admin_password'], $content); - wf($install_dir.'/server/lib/mysql_clientdb.conf',$content); + $content = str_replace('{hostname}', $conf['mysql']['host'], $content); + $content = str_replace('{username}', $conf['mysql']['admin_user'], $content); + $content = str_replace('{password}', $conf['mysql']['admin_password'], $content); + wf($install_dir.'/server/lib/mysql_clientdb.conf', $content); chmod($install_dir.'/server/lib/mysql_clientdb.conf', 0600); chown($install_dir.'/server/lib/mysql_clientdb.conf', 'root'); chgrp($install_dir.'/server/lib/mysql_clientdb.conf', 'root'); @@ -2095,12 +2097,12 @@ class installer_base { // remove existing ispconfig cronjobs, in case the syntax has changed foreach($existing_root_cron_jobs as $key => $val) { - if(stristr($val,$install_dir)) unset($existing_root_cron_jobs[$key]); + if(stristr($val, $install_dir)) unset($existing_root_cron_jobs[$key]); } $root_cron_jobs = array( - "* * * * * ".$install_dir."/server/server.sh 2>&1 > /dev/null | while read line; do echo `/bin/date` \"\$line\" >> ".$conf['ispconfig_log_dir']."/cron.log; done", - "30 00 * * * ".$install_dir."/server/cron_daily.sh 2>&1 > /dev/null | while read line; do echo `/bin/date` \"\$line\" >> ".$conf['ispconfig_log_dir']."/cron.log; done" + "* * * * * ".$install_dir."/server/server.sh 2>&1 > /dev/null | while read line; do echo `/bin/date` \"\$line\" >> ".$conf['ispconfig_log_dir']."/cron.log; done", + "30 00 * * * ".$install_dir."/server/cron_daily.sh 2>&1 > /dev/null | while read line; do echo `/bin/date` \"\$line\" >> ".$conf['ispconfig_log_dir']."/cron.log; done" ); if ($conf['nginx']['installed'] == true) { @@ -2123,12 +2125,12 @@ class installer_base { $existing_cron_jobs = file('crontab.txt'); $cron_jobs = array( - '*/5 * * * * /usr/local/bin/run-getmail.sh > /dev/null 2>> /dev/null' + '*/5 * * * * /usr/local/bin/run-getmail.sh > /dev/null 2>> /dev/null' ); // remove existing ispconfig cronjobs, in case the syntax has changed foreach($existing_cron_jobs as $key => $val) { - if(stristr($val,'getmail')) unset($existing_cron_jobs[$key]); + if(stristr($val, 'getmail')) unset($existing_cron_jobs[$key]); } foreach($cron_jobs as $cron_job) { @@ -2145,7 +2147,7 @@ class installer_base { chmod($conf['ispconfig_log_dir'].'/cron.log', 0660); } - + public function getinitcommand($servicename, $action, $init_script_directory = ''){ global $conf; // systemd @@ -2182,17 +2184,17 @@ class installer_base { global $conf, $dist; $final_path = ''; - $dist_template = $conf['ispconfig_install_dir'] . '/server/conf-custom/install/' . $tLocal . '.master'; - if (file_exists($dist_template)) { + $dist_template = $conf['ispconfig_install_dir'] . '/server/conf-custom/install/' . $tLocal . '.master'; + if (file_exists($dist_template)) { $final_path = $dist_template; } else { - $dist_template = 'dist/tpl/'.strtolower($dist['name'])."/$tLocal.master"; - if (file_exists($dist_template)) { - $final_path = $dist_template; - } else { - $final_path = "tpl/$tLocal.master"; - } - } + $dist_template = 'dist/tpl/'.strtolower($dist['name'])."/$tLocal.master"; + if (file_exists($dist_template)) { + $final_path = $dist_template; + } else { + $final_path = "tpl/$tLocal.master"; + } + } if (!$tRf) { return $final_path; @@ -2230,21 +2232,21 @@ class installer_base { wf($tConf, $tContents); // write file if (func_num_args() >= 4) // override rights and/or ownership - { + { $args = func_get_args(); $output = array_slice($args, 2); switch (sizeof($output)) { - case 3: - $umask = array_shift($output); - if (is_numeric($umask) && preg_match('/^0?[0-7]{3}$/', $umask)) { - $access = $umask; - } - case 2: - if (is_user($output[0]) && is_group($output[1])) { - list($user,$group) = $output; - } - break; + case 3: + $umask = array_shift($output); + if (is_numeric($umask) && preg_match('/^0?[0-7]{3}$/', $umask)) { + $access = $umask; + } + case 2: + if (is_user($output[0]) && is_group($output[1])) { + list($user, $group) = $output; + } + break; } } @@ -2273,11 +2275,12 @@ class installer_base { $tContents = str_replace('{mysql_server_ispconfig_password}', $conf["mysql"]["ispconfig_password"], $tContents); $tContents = str_replace('{mysql_server_database}', $conf["mysql"]["database"], $tContents); $tContents = str_replace('{mysql_server_ip}', $conf["mysql"]["ip"], $tContents); - $tContents = str_replace('{mysql_server_host}',$conf['mysql']['host'], $tContents); - $tContents = str_replace('{mysql_server_port}',$conf["mysql"]["port"], $tContents); + $tContents = str_replace('{mysql_server_host}', $conf['mysql']['host'], $tContents); + $tContents = str_replace('{mysql_server_port}', $conf["mysql"]["port"], $tContents); return $tContents; } + } ?> diff --git a/install/lib/mysql.lib.php b/install/lib/mysql.lib.php index b7f1ae8726373e0913d66b71f2b5c91505d0765f..c5c2a83a68681ac18a7c3036307c6f0b4423fa49 100644 --- a/install/lib/mysql.lib.php +++ b/install/lib/mysql.lib.php @@ -30,25 +30,25 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class db { - var $dbHost = ""; // hostname of the MySQL server - var $dbName = ""; // logical database name on that server - var $dbUser = ""; // database authorized user - var $dbPass = ""; // user's password + var $dbHost = ""; // hostname of the MySQL server + var $dbName = ""; // logical database name on that server + var $dbUser = ""; // database authorized user + var $dbPass = ""; // user's password var $dbCharset = ""; // what charset comes and goes to mysql: utf8 / latin1 - var $linkId = false; // last result of mysql_connect() - var $queryId = 0; // last result of mysql_query() - var $record = array(); // last record fetched - var $autoCommit = 1; // Autocommit Transactions - var $currentRow; // current row number - var $errorNumber = 0; // last error number - var $errorMessage = ""; // last error message + var $linkId = false; // last result of mysql_connect() + var $queryId = 0; // last result of mysql_query() + var $record = array(); // last record fetched + var $autoCommit = 1; // Autocommit Transactions + var $currentRow; // current row number + var $errorNumber = 0; // last error number + var $errorMessage = ""; // last error message var $errorLocation = ""; // last error location var $show_error_messages = false; // constructor function db() { - + global $conf; $this->dbHost = $conf["mysql"]["host"]; //$this->dbName = $conf["mysql"]["database"]; @@ -66,7 +66,7 @@ class db $this->errorLocation = $location; if($this->errorNumber && $this->show_error_messages) { - echo('
'.$this->errorLocation.'
'.$this->errorMessage); + echo '
'.$this->errorLocation.'
'.$this->errorMessage; flush(); } } @@ -138,7 +138,7 @@ class db // returns the next record in an array function nextRecord() { - $this->record = mysqli_fetch_assoc($this->queryId); + $this->record = mysqli_fetch_assoc($this->queryId); $this->updateError('DB::nextRecord()
mysqli_fetch_array'); if(!$this->record || !is_array($this->record)) { @@ -153,37 +153,37 @@ class db { return mysqli_num_rows($this->queryId); } - + function affectedRows() { return mysqli_affected_rows($this->linkId); } - + // returns mySQL insert id function insertID() { return mysqli_insert_id($this->linkId); } - - // Check der variablen + + // Check der variablen // deprecated, now use quote - function check($formfield) - { - return $this->quote($formfield); - } - + function check($formfield) + { + return $this->quote($formfield); + } + // Check der variablen - function quote($formfield) - { - return mysqli_real_escape_string($this->linkId, $formfield); - } - + function quote($formfield) + { + return mysqli_real_escape_string($this->linkId, $formfield); + } + // Check der variablen - function unquote($formfield) - { - return stripslashes($formfield); - } - + function unquote($formfield) + { + return stripslashes($formfield); + } + function toLower($record) { if(is_array($record)) { foreach($record as $key => $val) { @@ -191,64 +191,64 @@ class db $out[$key] = $val; } } - return $out; + return $out; } - - - function insert($tablename,$form,$debug = 0) - { - if(is_array($form)){ - foreach($form as $key => $value) - { - $sql_key .= "$key, "; - $sql_value .= "'".$this->check($value)."', "; - } - $sql_key = substr($sql_key,0,strlen($sql_key) - 2); - $sql_value = substr($sql_value,0,strlen($sql_value) - 2); - - $sql = "INSERT INTO $tablename (" . $sql_key . ") VALUES (" . $sql_value .")"; - - if($debug == 1) echo "SQL-Statement: ".$sql."

"; - $this->query($sql); - if($debug == 1) echo "mySQL Error Message: ".$this->errorMessage; - } - } - - function update($tablename,$form,$bedingung,$debug = 0) - { - - if(is_array($form)){ - foreach($form as $key => $value) - { - $insql .= "$key = '".$this->check($value)."', "; - } - $insql = substr($insql,0,strlen($insql) - 2); - $sql = "UPDATE $tablename SET " . $insql . " WHERE $bedingung"; - if($debug == 1) echo "SQL-Statement: ".$sql."

"; - $this->query($sql); - if($debug == 1) echo "mySQL Error Message: ".$this->errorMessage; - } - } - - function closeConn() { - - } - - function freeResult() { - - - } - - function delete() { - - } - - function Transaction($action) { - //action = begin, commit oder rollback - - } - - /* + + + function insert($tablename, $form, $debug = 0) + { + if(is_array($form)){ + foreach($form as $key => $value) + { + $sql_key .= "$key, "; + $sql_value .= "'".$this->check($value)."', "; + } + $sql_key = substr($sql_key, 0, strlen($sql_key) - 2); + $sql_value = substr($sql_value, 0, strlen($sql_value) - 2); + + $sql = "INSERT INTO $tablename (" . $sql_key . ") VALUES (" . $sql_value .")"; + + if($debug == 1) echo "SQL-Statement: ".$sql."

"; + $this->query($sql); + if($debug == 1) echo "mySQL Error Message: ".$this->errorMessage; + } + } + + function update($tablename, $form, $bedingung, $debug = 0) + { + + if(is_array($form)){ + foreach($form as $key => $value) + { + $insql .= "$key = '".$this->check($value)."', "; + } + $insql = substr($insql, 0, strlen($insql) - 2); + $sql = "UPDATE $tablename SET " . $insql . " WHERE $bedingung"; + if($debug == 1) echo "SQL-Statement: ".$sql."

"; + $this->query($sql); + if($debug == 1) echo "mySQL Error Message: ".$this->errorMessage; + } + } + + function closeConn() { + + } + + function freeResult() { + + + } + + function delete() { + + } + + function Transaction($action) { + //action = begin, commit oder rollback + + } + + /* $columns = array(action => add | alter | drop name => Spaltenname name_new => neuer Spaltenname, nur bei 'alter' belegt @@ -258,49 +258,49 @@ class db notNull => true | false autoInc => true | false option => unique | primary | index) - - + + */ - - function createTable($table_name,$columns) { - $index = ""; - $sql = "CREATE TABLE $table_name ("; - foreach($columns as $col){ - $sql .= $col["name"]." ".$this->mapType($col["type"],$col["typeValue"])." "; - - if($col["defaultValue"] != "") { - if($col["defaultValue"] == "NULL" or $col["defaultValue"] == "NOT NULL") { - $sql .= "DEFAULT ".$col["defaultValue"]." "; - } else { - $sql .= "DEFAULT '".$col["defaultValue"]."' "; + + function createTable($table_name, $columns) { + $index = ""; + $sql = "CREATE TABLE $table_name ("; + foreach($columns as $col){ + $sql .= $col["name"]." ".$this->mapType($col["type"], $col["typeValue"])." "; + + if($col["defaultValue"] != "") { + if($col["defaultValue"] == "NULL" or $col["defaultValue"] == "NOT NULL") { + $sql .= "DEFAULT ".$col["defaultValue"]." "; + } else { + $sql .= "DEFAULT '".$col["defaultValue"]."' "; + } + + } elseif($col["defaultValue"] != false) { + $sql .= "DEFAULT '' "; } - - } elseif($col["defaultValue"] != false) { - $sql .= "DEFAULT '' "; - } - if($col["defaultValue"] != "NULL" && $col["defaultValue"] != "NOT NULL") { - if($col["notNull"] == true) { - $sql .= "NOT NULL "; - } else { - $sql .= "NULL "; - } + if($col["defaultValue"] != "NULL" && $col["defaultValue"] != "NOT NULL") { + if($col["notNull"] == true) { + $sql .= "NOT NULL "; + } else { + $sql .= "NULL "; + } + } + if($col["autoInc"] == true) $sql .= "auto_increment "; + $sql.= ","; + // key Definitionen + if($col["option"] == "primary") $index .= "PRIMARY KEY (".$col["name"]."),"; + if($col["option"] == "index") $index .= "INDEX (".$col["name"]."),"; + if($col["option"] == "unique") $index .= "UNIQUE (".$col["name"]."),"; } - if($col["autoInc"] == true) $sql .= "auto_increment "; - $sql.= ","; - // key Definitionen - if($col["option"] == "primary") $index .= "PRIMARY KEY (".$col["name"]."),"; - if($col["option"] == "index") $index .= "INDEX (".$col["name"]."),"; - if($col["option"] == "unique") $index .= "UNIQUE (".$col["name"]."),"; - } - $sql .= $index; - $sql = substr($sql,0,-1); - $sql .= ")"; - - $this->query($sql); - return true; - } - - /* + $sql .= $index; + $sql = substr($sql, 0, -1); + $sql .= ")"; + + $this->query($sql); + return true; + } + + /* $columns = array(action => add | alter | drop name => Spaltenname name_new => neuer Spaltenname, nur bei 'alter' belegt @@ -310,56 +310,56 @@ class db notNull => true | false autoInc => true | false option => unique | primary | index) - - + + */ - function alterTable($table_name,$columns) { - $index = ""; - $sql = "ALTER TABLE $table_name "; - foreach($columns as $col){ - if($col["action"] == 'add') { - $sql .= "ADD ".$col["name"]." ".$this->mapType($col["type"],$col["typeValue"])." "; - } elseif ($col["action"] == 'alter') { - $sql .= "CHANGE ".$col["name"]." ".$col["name_new"]." ".$this->mapType($col["type"],$col["typeValue"])." "; - } elseif ($col["action"] == 'drop') { - $sql .= "DROP ".$col["name"]." "; - } - if($col["action"] != 'drop') { - if($col["defaultValue"] != "") $sql .= "DEFAULT '".$col["defaultValue"]."' "; - if($col["notNull"] == true) { - $sql .= "NOT NULL "; - } else { - $sql .= "NULL "; - } - if($col["autoInc"] == true) $sql .= "auto_increment "; - $sql.= ","; - // key Definitionen - if($col["option"] == "primary") $index .= "PRIMARY KEY (".$col["name"]."),"; - if($col["option"] == "index") $index .= "INDEX (".$col["name"]."),"; - if($col["option"] == "unique") $index .= "UNIQUE (".$col["name"]."),"; - } - } - $sql .= $index; - $sql = substr($sql,0,-1); - - //die($sql); - $this->query($sql); - return true; - } - - function dropTable($table_name) { - $this->check($table_name); - $sql = "DROP TABLE '". $table_name."'"; - return $this->query($sql); - } - - // gibt Array mit Tabellennamen zur�ck - function getTables($database_name = '') { - + function alterTable($table_name, $columns) { + $index = ""; + $sql = "ALTER TABLE $table_name "; + foreach($columns as $col){ + if($col["action"] == 'add') { + $sql .= "ADD ".$col["name"]." ".$this->mapType($col["type"], $col["typeValue"])." "; + } elseif ($col["action"] == 'alter') { + $sql .= "CHANGE ".$col["name"]." ".$col["name_new"]." ".$this->mapType($col["type"], $col["typeValue"])." "; + } elseif ($col["action"] == 'drop') { + $sql .= "DROP ".$col["name"]." "; + } + if($col["action"] != 'drop') { + if($col["defaultValue"] != "") $sql .= "DEFAULT '".$col["defaultValue"]."' "; + if($col["notNull"] == true) { + $sql .= "NOT NULL "; + } else { + $sql .= "NULL "; + } + if($col["autoInc"] == true) $sql .= "auto_increment "; + $sql.= ","; + // key Definitionen + if($col["option"] == "primary") $index .= "PRIMARY KEY (".$col["name"]."),"; + if($col["option"] == "index") $index .= "INDEX (".$col["name"]."),"; + if($col["option"] == "unique") $index .= "UNIQUE (".$col["name"]."),"; + } + } + $sql .= $index; + $sql = substr($sql, 0, -1); + + //die($sql); + $this->query($sql); + return true; + } + + function dropTable($table_name) { + $this->check($table_name); + $sql = "DROP TABLE '". $table_name."'"; + return $this->query($sql); + } + + // gibt Array mit Tabellennamen zur�ck + function getTables($database_name = '') { + if($database_name == ''){ - $database_name = $this->dbName; - } - + $database_name = $this->dbName; + } + $tables = $this->queryAllRecords("SHOW TABLES FROM `$database_name`"); $tb_names = array(); if(is_array($tables) && !empty($tables)){ @@ -367,7 +367,7 @@ class db $tb_names[$i] = $tables[$i]['Tables_in_'.$database_name]; } } - + /* $result = mysqli_query("SHOW TABLES FROM `$database_name`"); $tb_names = array(); @@ -375,11 +375,11 @@ class db $tb_names[$i] = mysql_tablename($result, $i); } */ - return $tb_names; - } - - // gibt Feldinformationen zur Tabelle zur�ck - /* + return $tb_names; + } + + // gibt Feldinformationen zur Tabelle zur�ck + /* $columns = array(action => add | alter | drop name => Spaltenname name_new => neuer Spaltenname, nur bei 'alter' belegt @@ -389,101 +389,101 @@ class db notNull => true | false autoInc => true | false option => unique | primary | index) - - + + */ - - function tableInfo($table_name) { - - global $go_api,$go_info; - // Tabellenfelder einlesen - - if($rows = $go_api->db->queryAllRecords("SHOW FIELDS FROM ".$table_name)){ - foreach($rows as $row) { - $name = $row[0]; - $default = $row[4]; - $key = $row[3]; - $extra = $row[5]; - $isnull = $row[2]; - $type = $row[1]; - - - $column = array(); - - $column["name"] = $name; - //$column["type"] = $type; - $column["defaultValue"] = $default; - if(stristr($key,"PRI")) $column["option"] = "primary"; - if(stristr($isnull,"YES")) { - $column["notNull"] = false; - } else { - $column["notNull"] = true; - } - if($extra == 'auto_increment') $column["autoInc"] = true; - - - // Type in Metatype umsetzen - - if(stristr($type,"int(")) $metaType = 'int32'; - if(stristr($type,"bigint")) $metaType = 'int64'; - if(stristr($type,"char")) { - $metaType = 'char'; - $tmp_typeValue = explode('(',$type); - $column["typeValue"] = substr($tmp_typeValue[1],0,-1); - } - if(stristr($type,"varchar")) { - $metaType = 'varchar'; - $tmp_typeValue = explode('(',$type); - $column["typeValue"] = substr($tmp_typeValue[1],0,-1); - } - if(stristr($type,"text")) $metaType = 'text'; - if(stristr($type,"double")) $metaType = 'double'; - if(stristr($type,"blob")) $metaType = 'blob'; - - - $column["type"] = $metaType; - - $columns[] = $column; - } - return $columns; - } else { - return false; - } - - } - - function mapType($metaType,$typeValue) { - global $go_api; - $metaType = strtolower($metaType); - switch ($metaType) { - case 'int16': - return 'smallint'; - break; - case 'int32': - return 'int'; - break; - case 'int64': - return 'bigint'; - break; - case 'double': - return 'double'; - break; - case 'char': - return 'char'; - break; - case 'varchar': - if($typeValue < 1) die("Datenbank Fehler: F�r diesen Datentyp ist eine L�ngenangabe notwendig."); - return 'varchar('.$typeValue.')'; - break; - case 'text': - return 'text'; - break; - case 'blob': - return 'blob'; - break; - } - } - + + function tableInfo($table_name) { + + global $go_api, $go_info; + // Tabellenfelder einlesen + + if($rows = $go_api->db->queryAllRecords("SHOW FIELDS FROM ".$table_name)){ + foreach($rows as $row) { + $name = $row[0]; + $default = $row[4]; + $key = $row[3]; + $extra = $row[5]; + $isnull = $row[2]; + $type = $row[1]; + + + $column = array(); + + $column["name"] = $name; + //$column["type"] = $type; + $column["defaultValue"] = $default; + if(stristr($key, "PRI")) $column["option"] = "primary"; + if(stristr($isnull, "YES")) { + $column["notNull"] = false; + } else { + $column["notNull"] = true; + } + if($extra == 'auto_increment') $column["autoInc"] = true; + + + // Type in Metatype umsetzen + + if(stristr($type, "int(")) $metaType = 'int32'; + if(stristr($type, "bigint")) $metaType = 'int64'; + if(stristr($type, "char")) { + $metaType = 'char'; + $tmp_typeValue = explode('(', $type); + $column["typeValue"] = substr($tmp_typeValue[1], 0, -1); + } + if(stristr($type, "varchar")) { + $metaType = 'varchar'; + $tmp_typeValue = explode('(', $type); + $column["typeValue"] = substr($tmp_typeValue[1], 0, -1); + } + if(stristr($type, "text")) $metaType = 'text'; + if(stristr($type, "double")) $metaType = 'double'; + if(stristr($type, "blob")) $metaType = 'blob'; + + + $column["type"] = $metaType; + + $columns[] = $column; + } + return $columns; + } else { + return false; + } + + } + + function mapType($metaType, $typeValue) { + global $go_api; + $metaType = strtolower($metaType); + switch ($metaType) { + case 'int16': + return 'smallint'; + break; + case 'int32': + return 'int'; + break; + case 'int64': + return 'bigint'; + break; + case 'double': + return 'double'; + break; + case 'char': + return 'char'; + break; + case 'varchar': + if($typeValue < 1) die("Datenbank Fehler: F�r diesen Datentyp ist eine L�ngenangabe notwendig."); + return 'varchar('.$typeValue.')'; + break; + case 'text': + return 'text'; + break; + case 'blob': + return 'blob'; + break; + } + } + } ?> diff --git a/install/lib/update.lib.php b/install/lib/update.lib.php index b4e73abb1d0694dbec42a6c1fca688836beeb5cc..bc0453f7f63df24fbe45fef5e219131f297c45ef 100644 --- a/install/lib/update.lib.php +++ b/install/lib/update.lib.php @@ -29,10 +29,12 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //* Installer patch stub class class installer_patch_update { - protected function onBeforeSQL() { - } - protected function onAfterSQL() { - } + protected function onBeforeSQL() { + } + + protected function onAfterSQL() { + } + } //* DB dump function @@ -70,25 +72,25 @@ function prepareDBDump() { } else { $backup_db_name = '/root/ispconfig_db_backup_'.@date('Y-m-d_H-i').'.sql'; } - copy('existing_db.sql',$backup_db_name); + copy('existing_db.sql', $backup_db_name); chmod($backup_db_name, 0700); chown($backup_db_name, 'root'); chgrp($backup_db_name, 'root'); if ($conf['powerdns']['installed']) { //** export the current PowerDNS database data - if( !empty($conf["mysql"]["admin_password"]) ) { - system("mysqldump -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." -p".escapeshellarg($conf['mysql']['admin_password'])." -c -t --add-drop-table --create-options --quick --result-file=existing_powerdns_db.sql ".$conf['powerdns']['database']); - } else { - system("mysqldump -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." -c -t --add-drop-table --create-options --quick --result-file=existing_powerdns_db.sql ".$conf['powerdns']['database']); - } + if( !empty($conf["mysql"]["admin_password"]) ) { + system("mysqldump -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." -p".escapeshellarg($conf['mysql']['admin_password'])." -c -t --add-drop-table --create-options --quick --result-file=existing_powerdns_db.sql ".$conf['powerdns']['database']); + } else { + system("mysqldump -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." -c -t --add-drop-table --create-options --quick --result-file=existing_powerdns_db.sql ".$conf['powerdns']['database']); + } // create a backup copy of the PowerDNS database in the root folder $backup_db_name = '/root/ispconfig_powerdns_db_backup_'.@date('Y-m-d_h-i').'.sql'; - copy('existing_powerdns_db.sql',$backup_db_name); + copy('existing_powerdns_db.sql', $backup_db_name); chmod($backup_db_name, 0700); - chown($backup_db_name, 'root'); - chgrp($backup_db_name, 'root'); + chown($backup_db_name, 'root'); + chgrp($backup_db_name, 'root'); } } @@ -115,7 +117,7 @@ function checkDbHealth() { sread(); } else - echo "OK\n"; + echo "OK\n"; } function updateDbAndIni() { @@ -136,9 +138,9 @@ function updateDbAndIni() { $conf['services']['vserver'] = ($tmp['vserver_server'] == 1)?true:false; $conf['services']['proxy'] = (isset($tmp['proxy_server']) && $tmp['proxy_server'] == 1)?true:false; $conf['services']['firewall'] = (isset($tmp['firewall_server']) && $tmp['firewall_server'] == 1)?true:false; - + $conf['postfix']['vmail_mailbox_base'] = $ini_array['mail']['homedir_path']; - + if(isset($ini_array['web']['server_type']) && $ini_array['web']['server_type'] != ''){ $conf['webserver']['server_type'] = $ini_array['web']['server_type']; if($conf['webserver']['server_type'] == 'nginx'){ @@ -150,38 +152,38 @@ function updateDbAndIni() { $conf['webserver']['server_type'] = 'apache'; $conf['nginx']['installed'] = false; } - + //* Do incremental DB updates only on installed ISPConfig versions > 3.0.3 - if(compare_ispconfig_version('3.0.3',ISPC_APP_VERSION) >= 0) { - + if(compare_ispconfig_version('3.0.3', ISPC_APP_VERSION) >= 0) { + swriteln($inst->lng('Starting incremental database update.')); - - //* get the version of the db schema from the server table + + //* get the version of the db schema from the server table $found = true; while($found == true) { $next_db_version = intval($current_db_version + 1); $sql_patch_filename = realpath(dirname(__FILE__).'/../').'/sql/incremental/upd_'.str_pad($next_db_version, 4, '0', STR_PAD_LEFT).'.sql'; $php_patch_filename = realpath(dirname(__FILE__).'/../').'/patches/upd_'.str_pad($next_db_version, 4, '0', STR_PAD_LEFT).'.php'; - + if(is_file($sql_patch_filename)) { - + //* Load php patch file and instantiate object if(is_file($php_patch_filename)) { $php_patch_class_name = 'upd_'.str_pad($next_db_version, 4, '0', STR_PAD_LEFT); - include_once($php_patch_filename); + include_once $php_patch_filename; if(class_exists($php_patch_class_name)) { $php_patch = new $php_patch_class_name; } else { swriteln($inst->lng('WARNING: PHP patch file').': '.$php_patch_filename.' '.$inst->lng('contains errors.')); } } - + //* Exec onBeforeSQL function if(isset($php_patch) && is_object($php_patch)) { $php_patch->onBeforeSQL(); swriteln($inst->lng('Executing PHP patch file').': '.$php_patch_filename); } - + //* Load patch file into database if( !empty($conf["mysql"]["admin_password"]) ) { system("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." --force -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." -p".escapeshellarg($conf['mysql']['admin_password'])." ".escapeshellarg($conf['mysql']['database'])." < ".$sql_patch_filename); @@ -189,32 +191,32 @@ function updateDbAndIni() { system("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." --force -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." ".escapeshellarg($conf['mysql']['database'])." < ".$sql_patch_filename); } swriteln($inst->lng('Loading SQL patch file').': '.$sql_patch_filename); - + //* Exec onAfterSQL function if(isset($php_patch) && is_object($php_patch)) { $php_patch->onAfterSQL(); } - + $current_db_version = $next_db_version; if(isset($php_patch)) unset($php_patch); } else { $found = false; } } - + //* update the database version in server table $inst->db->query("UPDATE ".$conf["mysql"]["database"].".server SET dbversion = '".$current_db_version."' WHERE server_id = ".$conf['server_id']); if($inst->db->dbHost != $inst->dbmaster->dbHost) $inst->dbmaster->query("UPDATE ".$conf["mysql"]["master_database"].".server SET dbversion = '".$current_db_version."' WHERE server_id = ".$conf['server_id']); - - - //* If ISPConfig Version < 3.0.3, we will do a full db update + + + //* If ISPConfig Version < 3.0.3, we will do a full db update } else { - + swriteln($inst->lng('Starting full database update.')); - + //** Delete the old database if( !$inst->db->query('DROP DATABASE IF EXISTS '.$conf['mysql']['database']) ) { - $inst->error('Unable to drop MySQL database: '.$conf['mysql']['database'].'.'); + $inst->error('Unable to drop MySQL database: '.$conf['mysql']['database'].'.'); } //** Create the mysql database @@ -233,7 +235,7 @@ function updateDbAndIni() { } else { system("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." --force -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." ".escapeshellarg($conf['mysql']['database'])." < existing_db.sql"); } - + //** Get the database version number based on the patchfile $found = true; while($found == true) { @@ -245,29 +247,29 @@ function updateDbAndIni() { $found = false; } } - + //* update the database version in server table $inst->db->query("UPDATE ".$conf["mysql"]["database"].".server SET dbversion = '".$current_db_version."' WHERE server_id = ".$conf['server_id']); if($inst->db->dbHost != $inst->dbmaster->dbHost) $inst->dbmaster->query("UPDATE ".$conf["mysql"]["master_database"].".server SET dbversion = '".$current_db_version."' WHERE server_id = ".$conf['server_id']); if ($conf['powerdns']['installed']) { - + swriteln($inst->lng('Starting full PowerDNS database update.')); - //** Delete the old PowerDNS database - if( !$inst->db->query('DROP DATABASE IF EXISTS '.$conf['powerdns']['database']) ) { + //** Delete the old PowerDNS database + if( !$inst->db->query('DROP DATABASE IF EXISTS '.$conf['powerdns']['database']) ) { $inst->error('Unable to drop MySQL database: '.$conf['powerdns']['database'].'.'); - } + } - //** Create the mysql database - $inst->configure_powerdns(); + //** Create the mysql database + $inst->configure_powerdns(); - //** load old data back into the PowerDNS database - if( !empty($conf["mysql"]["admin_password"]) ) { - system("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." --force -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." -p".escapeshellarg($conf['mysql']['admin_password'])." ".escapeshellarg($conf['powerdns']['database'])." < existing_powerdns_db.sql"); - } else { - system("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." --force -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." ".escapeshellarg($conf['powerdns']['database'])." < existing_powerdns_db.sql"); - } + //** load old data back into the PowerDNS database + if( !empty($conf["mysql"]["admin_password"]) ) { + system("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." --force -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." -p".escapeshellarg($conf['mysql']['admin_password'])." ".escapeshellarg($conf['powerdns']['database'])." < existing_powerdns_db.sql"); + } else { + system("mysql --default-character-set=".escapeshellarg($conf['mysql']['charset'])." --force -h ".escapeshellarg($conf['mysql']['host'])." -u ".escapeshellarg($conf['mysql']['admin_user'])." ".escapeshellarg($conf['powerdns']['database'])." < existing_powerdns_db.sql"); + } } } @@ -277,7 +279,7 @@ function updateDbAndIni() { $old_ini_array = ini_to_array(stripslashes($tmp_server_rec['config'])); unset($tmp_server_rec); $tpl_ini_array = ini_to_array(rf('tpl/server.ini.master')); - + //* Update further distribution specific parameters for server config here //* HINT: Every line added here has to be added in installer_base.lib.php too!! $tpl_ini_array['jailkit']['jailkit_chroot_app_programs'] = $conf['jailkit']['jailkit_chroot_app_programs']; @@ -302,7 +304,7 @@ function updateDbAndIni() { $tpl_ini_array['dns']['bind_zonefiles_dir'] = $conf['bind']['bind_zonefiles_dir']; $tpl_ini_array['dns']['named_conf_path'] = $conf['bind']['named_conf_path']; $tpl_ini_array['dns']['named_conf_local_path'] = $conf['bind']['named_conf_local_path']; - + $tpl_ini_array['web']['nginx_vhost_conf_dir'] = $conf['nginx']['vhost_conf_dir']; $tpl_ini_array['web']['nginx_vhost_conf_enabled_dir'] = $conf['nginx']['vhost_conf_enabled_dir']; $tpl_ini_array['web']['nginx_user'] = $conf['nginx']['user']; @@ -313,7 +315,7 @@ function updateDbAndIni() { $tpl_ini_array['web']['php_fpm_pool_dir'] = $conf['nginx']['php_fpm_pool_dir']; $tpl_ini_array['web']['php_fpm_start_port'] = $conf['nginx']['php_fpm_start_port']; $tpl_ini_array['web']['php_fpm_socket_dir'] = $conf['nginx']['php_fpm_socket_dir']; - + if ($conf['nginx']['installed'] == true) { $tpl_ini_array['web']['server_type'] = 'nginx'; $tpl_ini_array['global']['webserver'] = 'nginx'; @@ -331,7 +333,7 @@ function updateDbAndIni() { $new_ini = array_to_ini($tpl_ini_array); $sql = "UPDATE ".$conf["mysql"]["database"].".server SET config = '".mysql_real_escape_string($new_ini)."' WHERE server_id = ".$conf['server_id']; $inst->db->query($sql); - + if($inst->db->dbHost != $inst->dbmaster->dbHost) { $sql = "UPDATE ".$conf["mysql"]["master_database"].".server SET config = '".mysql_real_escape_string($new_ini)."' WHERE server_id = ".$conf['server_id']; $inst->dbmaster->query($sql); diff --git a/install/patches/upd_0001.php b/install/patches/upd_0001.php index 93d6967b9d2f5d77b69e57466548daf9560df71c..596bef596406fff80925416d18e80426c8ce267e 100644 --- a/install/patches/upd_0001.php +++ b/install/patches/upd_0001.php @@ -1,6 +1,6 @@ diff --git a/install/setrights.php b/install/setrights.php index 1124136baaee5ec95f7981bd050bd318094bfba8..275401a91f247201f764fc92c50167f7aef5e033 100644 --- a/install/setrights.php +++ b/install/setrights.php @@ -34,7 +34,7 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. error_reporting(E_ALL|E_STRICT); //** The banner on the command line -echo "\n\n".str_repeat('-',80)."\n"; +echo "\n\n".str_repeat('-', 80)."\n"; echo " _____ ___________ _____ __ _ ____ |_ _/ ___| ___ \ / __ \ / _(_) /__ \ | | \ `--.| |_/ / | / \/ ___ _ __ | |_ _ __ _ _/ / @@ -43,17 +43,17 @@ echo " _____ ___________ _____ __ _ ____ \___/\____/\_| \____/\___/|_| |_|_| |_|\__, | \____/ __/ | |___/ "; - echo "\n".str_repeat('-',80)."\n"; - echo "\n\n>>This script tries to repair the client rights \n\n"; +echo "\n".str_repeat('-', 80)."\n"; +echo "\n\n>>This script tries to repair the client rights \n\n"; //** Include the library with the basic installer functions -require_once('lib/install.lib.php'); +require_once 'lib/install.lib.php'; //** Include the library with the basic updater functions -require_once('lib/update.lib.php'); +require_once 'lib/update.lib.php'; //** Include the base class of the installer class -require_once('lib/installer_base.lib.php'); +require_once 'lib/installer_base.lib.php'; //** Ensure that current working directory is install directory $cur_dir = getcwd(); @@ -62,16 +62,16 @@ if(realpath(dirname(__FILE__)) != $cur_dir) die("Please run installation/update //** Get distribution identifier $dist = get_distname(); -include_once("/usr/local/ispconfig/server/lib/config.inc.php"); +include_once "/usr/local/ispconfig/server/lib/config.inc.php"; $conf_old = $conf; unset($conf); if($dist['id'] == '') die('Linux distribution or version not recognized.'); //** Include the distribution-specific installer class library and configuration -if(is_file('dist/lib/'.$dist['baseid'].'.lib.php')) include_once('dist/lib/'.$dist['baseid'].'.lib.php'); -include_once('dist/lib/'.$dist['id'].'.lib.php'); -include_once('dist/conf/'.$dist['id'].'.conf.php'); +if(is_file('dist/lib/'.$dist['baseid'].'.lib.php')) include_once 'dist/lib/'.$dist['baseid'].'.lib.php'; +include_once 'dist/lib/'.$dist['id'].'.lib.php'; +include_once 'dist/conf/'.$dist['id'].'.conf.php'; //** Get hostname exec('hostname -f', $tmp_out); @@ -87,15 +87,15 @@ if($conf["mysql"]["master_host"] != '' && $conf["mysql"]["host"] != $conf["mysql /* * Try to read the DB-admin settings */ -$clientdb_host = ''; -$clientdb_user = ''; -$clientdb_password = ''; -include_once("/usr/local/ispconfig/server/lib/mysql_clientdb.conf"); +$clientdb_host = ''; +$clientdb_user = ''; +$clientdb_password = ''; +include_once "/usr/local/ispconfig/server/lib/mysql_clientdb.conf"; $conf["mysql"]["admin_user"] = $clientdb_user; $conf["mysql"]["admin_password"] = $clientdb_password; -$clientdb_host = ''; -$clientdb_user = ''; -$clientdb_password = ''; +$clientdb_host = ''; +$clientdb_user = ''; +$clientdb_password = ''; //** There is a error if user for mysql admin_password if empty if( empty($conf["mysql"]["admin_password"]) ) { @@ -105,7 +105,7 @@ if( empty($conf["mysql"]["admin_password"]) ) { $inst = new installer(); //** Initialize the MySQL server connection -include_once('lib/mysql.lib.php'); +include_once 'lib/mysql.lib.php'; //* initialize the database $inst->db = new db(); diff --git a/install/uninstall-fedora.php b/install/uninstall-fedora.php index 4da434787a285c1ef092b69f8063785dee89b389..66eb3003f60b35250c10e31d9b71c971467811a4 100644 --- a/install/uninstall-fedora.php +++ b/install/uninstall-fedora.php @@ -35,7 +35,7 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. error_reporting(E_ALL|E_STRICT); //** The banner on the command line -echo "\n\n".str_repeat('-',80)."\n"; +echo "\n\n".str_repeat('-', 80)."\n"; echo " _____ ___________ _____ __ _ ____ |_ _/ ___| ___ \ / __ \ / _(_) /__ \ | | \ `--.| |_/ / | / \/ ___ _ __ | |_ _ __ _ _/ / @@ -44,11 +44,11 @@ echo " _____ ___________ _____ __ _ ____ \___/\____/\_| \____/\___/|_| |_|_| |_|\__, | \____/ __/ | |___/ "; -echo "\n".str_repeat('-',80)."\n"; +echo "\n".str_repeat('-', 80)."\n"; echo "\n\n>> Uninstall \n\n"; -require("/usr/local/ispconfig/server/lib/config.inc.php"); -require("/usr/local/ispconfig/server/lib/app.inc.php"); +require "/usr/local/ispconfig/server/lib/config.inc.php"; +require "/usr/local/ispconfig/server/lib/app.inc.php"; // Delete the ISPConfig database // $app->db->query("DROP DATABASE '".$conf["db_database"]."'"); diff --git a/install/uninstall.php b/install/uninstall.php index 415ecf4f0fb1399c17b6be8200763dbe064f96e1..96d98c7cad6b3e922f1ca66d916c587a66d5e3db 100644 --- a/install/uninstall.php +++ b/install/uninstall.php @@ -35,7 +35,7 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. error_reporting(E_ALL|E_STRICT); //** The banner on the command line -echo "\n\n".str_repeat('-',80)."\n"; +echo "\n\n".str_repeat('-', 80)."\n"; echo " _____ ___________ _____ __ _ ____ |_ _/ ___| ___ \ / __ \ / _(_) /__ \ | | \ `--.| |_/ / | / \/ ___ _ __ | |_ _ __ _ _/ / @@ -44,11 +44,11 @@ echo " _____ ___________ _____ __ _ ____ \___/\____/\_| \____/\___/|_| |_|_| |_|\__, | \____/ __/ | |___/ "; -echo "\n".str_repeat('-',80)."\n"; +echo "\n".str_repeat('-', 80)."\n"; echo "\n\n>> Uninstall \n\n"; -require("/usr/local/ispconfig/server/lib/config.inc.php"); -require("/usr/local/ispconfig/server/lib/app.inc.php"); +require "/usr/local/ispconfig/server/lib/config.inc.php"; +require "/usr/local/ispconfig/server/lib/app.inc.php"; // Delete the ISPConfig database // $app->db->query("DROP DATABASE '".$conf["db_database"]."'"); diff --git a/install/update.php b/install/update.php index e5bcfb6720b02b2609985857089782391d17dc95..5cc2f42818bd268a09f19248a64f6091a5318486 100644 --- a/install/update.php +++ b/install/update.php @@ -37,7 +37,7 @@ error_reporting(E_ALL|E_STRICT); define('INSTALLER_RUN', true); //** The banner on the command line -echo "\n\n".str_repeat('-',80)."\n"; +echo "\n\n".str_repeat('-', 80)."\n"; echo " _____ ___________ _____ __ _ ____ |_ _/ ___| ___ \ / __ \ / _(_) /__ \ | | \ `--.| |_/ / | / \/ ___ _ __ | |_ _ __ _ _/ / @@ -46,17 +46,17 @@ echo " _____ ___________ _____ __ _ ____ \___/\____/\_| \____/\___/|_| |_|_| |_|\__, | \____/ __/ | |___/ "; -echo "\n".str_repeat('-',80)."\n"; +echo "\n".str_repeat('-', 80)."\n"; echo "\n\n>> Update \n\n"; //** Include the library with the basic installer functions -require_once('lib/install.lib.php'); +require_once 'lib/install.lib.php'; //** Include the library with the basic updater functions -require_once('lib/update.lib.php'); +require_once 'lib/update.lib.php'; //** Include the base class of the installer class -require_once('lib/installer_base.lib.php'); +require_once 'lib/installer_base.lib.php'; //** Ensure that current working directory is install directory $cur_dir = getcwd(); @@ -74,16 +74,16 @@ if(is_dir('/root/ispconfig') || is_dir('/home/admispconfig')) { //** Get distribution identifier $dist = get_distname(); -include_once("/usr/local/ispconfig/server/lib/config.inc.php"); +include_once "/usr/local/ispconfig/server/lib/config.inc.php"; $conf_old = $conf; unset($conf); if($dist['id'] == '') die('Linux distribution or version not recognized.'); //** Include the distribution-specific installer class library and configuration -if(is_file('dist/lib/'.$dist['baseid'].'.lib.php')) include_once('dist/lib/'.$dist['baseid'].'.lib.php'); -include_once('dist/lib/'.$dist['id'].'.lib.php'); -include_once('dist/conf/'.$dist['id'].'.conf.php'); +if(is_file('dist/lib/'.$dist['baseid'].'.lib.php')) include_once 'dist/lib/'.$dist['baseid'].'.lib.php'; +include_once 'dist/lib/'.$dist['id'].'.lib.php'; +include_once 'dist/conf/'.$dist['id'].'.conf.php'; //** Get hostname exec('hostname -f', $tmp_out); @@ -128,52 +128,52 @@ $inst->find_installed_apps(); echo "This application will update ISPConfig 3 on your server.\n\n"; //* Make a backup before we start the update -$do_backup = $inst->simple_query('Shall the script create a ISPConfig backup in /var/backup/ now?', array('yes','no'),'yes'); +$do_backup = $inst->simple_query('Shall the script create a ISPConfig backup in /var/backup/ now?', array('yes', 'no'), 'yes'); if($do_backup == 'yes') { - + //* Create the backup directory $backup_path = '/var/backup/ispconfig_'.@date('Y-m-d_H-i'); $conf['backup_path'] = $backup_path; exec("mkdir -p $backup_path"); exec("chown root:root $backup_path"); exec("chmod 700 $backup_path"); - + //* Do the backup swriteln('Creating backup of "/usr/local/ispconfig" directory...'); - exec("tar pcfz $backup_path/ispconfig_software.tar.gz /usr/local/ispconfig 2> /dev/null",$out,$returnvar); + exec("tar pcfz $backup_path/ispconfig_software.tar.gz /usr/local/ispconfig 2> /dev/null", $out, $returnvar); if($returnvar != 0) die("Backup failed. We stop here...\n"); - + swriteln('Creating backup of "/etc" directory...'); - exec("tar pcfz $backup_path/etc.tar.gz /etc 2> /dev/null",$out,$returnvar); + exec("tar pcfz $backup_path/etc.tar.gz /etc 2> /dev/null", $out, $returnvar); if($returnvar != 0) die("Backup failed. We stop here...\n"); - + exec("chown root:root $backup_path/*.tar.gz"); exec("chmod 700 $backup_path/*.tar.gz"); } //** Initialize the MySQL server connection -include_once('lib/mysql.lib.php'); +include_once 'lib/mysql.lib.php'; //** Database update is a bit brute force and should be rebuild later ;) /* * Try to read the DB-admin settings */ -$clientdb_host = ''; -$clientdb_user = ''; -$clientdb_password = ''; -include_once("/usr/local/ispconfig/server/lib/mysql_clientdb.conf"); +$clientdb_host = ''; +$clientdb_user = ''; +$clientdb_password = ''; +include_once "/usr/local/ispconfig/server/lib/mysql_clientdb.conf"; $conf["mysql"]["admin_user"] = $clientdb_user; $conf["mysql"]["admin_password"] = $clientdb_password; -$clientdb_host = ''; -$clientdb_user = ''; -$clientdb_password = ''; +$clientdb_host = ''; +$clientdb_user = ''; +$clientdb_password = ''; //** Test mysql root connection $finished = false; do { - if(@mysql_connect($conf["mysql"]["host"],$conf["mysql"]["admin_user"],$conf["mysql"]["admin_password"])) { + if(@mysql_connect($conf["mysql"]["host"], $conf["mysql"]["admin_user"], $conf["mysql"]["admin_password"])) { $finished = true; } else { swriteln($inst->lng('Unable to connect to mysql server').' '.mysql_error()); @@ -183,7 +183,7 @@ do { unset($finished); /* - * Prepare the dump of the database + * Prepare the dump of the database */ prepareDBDump(); @@ -192,34 +192,34 @@ $inst->db = new db(); //* initialize the master DB, if we have a multiserver setup if($conf['mysql']['master_slave_setup'] == 'y') { - //** Get MySQL root credentials - $finished = false; - do { - $tmp_mysql_server_host = $inst->free_query('MySQL master server hostname', $conf['mysql']['master_host']); - $tmp_mysql_server_admin_user = $inst->free_query('MySQL master server root username', $conf['mysql']['master_admin_user']); - $tmp_mysql_server_admin_password = $inst->free_query('MySQL master server root password', $conf['mysql']['master_admin_password']); - $tmp_mysql_server_database = $inst->free_query('MySQL master server database name', $conf['mysql']['master_database']); - - //* Initialize the MySQL server connection - if(@mysql_connect($tmp_mysql_server_host, $tmp_mysql_server_admin_user, $tmp_mysql_server_admin_password)) { - $conf['mysql']['master_host'] = $tmp_mysql_server_host; - $conf['mysql']['master_admin_user'] = $tmp_mysql_server_admin_user; - $conf['mysql']['master_admin_password'] = $tmp_mysql_server_admin_password; - $conf['mysql']['master_database'] = $tmp_mysql_server_database; - $finished = true; - } else { - swriteln($inst->lng('Unable to connect to mysql server').' '.mysql_error()); - } - } while ($finished == false); - unset($finished); - - // initialize the connection to the master database - $inst->dbmaster = new db(); - if($inst->dbmaster->linkId) $inst->dbmaster->closeConn(); - $inst->dbmaster->dbHost = $conf['mysql']["master_host"]; - $inst->dbmaster->dbName = $conf['mysql']["master_database"]; - $inst->dbmaster->dbUser = $conf['mysql']["master_admin_user"]; - $inst->dbmaster->dbPass = $conf['mysql']["master_admin_password"]; + //** Get MySQL root credentials + $finished = false; + do { + $tmp_mysql_server_host = $inst->free_query('MySQL master server hostname', $conf['mysql']['master_host']); + $tmp_mysql_server_admin_user = $inst->free_query('MySQL master server root username', $conf['mysql']['master_admin_user']); + $tmp_mysql_server_admin_password = $inst->free_query('MySQL master server root password', $conf['mysql']['master_admin_password']); + $tmp_mysql_server_database = $inst->free_query('MySQL master server database name', $conf['mysql']['master_database']); + + //* Initialize the MySQL server connection + if(@mysql_connect($tmp_mysql_server_host, $tmp_mysql_server_admin_user, $tmp_mysql_server_admin_password)) { + $conf['mysql']['master_host'] = $tmp_mysql_server_host; + $conf['mysql']['master_admin_user'] = $tmp_mysql_server_admin_user; + $conf['mysql']['master_admin_password'] = $tmp_mysql_server_admin_password; + $conf['mysql']['master_database'] = $tmp_mysql_server_database; + $finished = true; + } else { + swriteln($inst->lng('Unable to connect to mysql server').' '.mysql_error()); + } + } while ($finished == false); + unset($finished); + + // initialize the connection to the master database + $inst->dbmaster = new db(); + if($inst->dbmaster->linkId) $inst->dbmaster->closeConn(); + $inst->dbmaster->dbHost = $conf['mysql']["master_host"]; + $inst->dbmaster->dbName = $conf['mysql']["master_database"]; + $inst->dbmaster->dbUser = $conf['mysql']["master_admin_user"]; + $inst->dbmaster->dbPass = $conf['mysql']["master_admin_password"]; } else { $inst->dbmaster = $inst->db; } @@ -240,28 +240,28 @@ updateDbAndIni(); * If this is done at server side, all clients are updated. */ //if($conf_old['dbmaster_user'] != '' or $conf_old['dbmaster_host'] != '') { - //** Update master database rights - $reconfigure_master_database_rights_answer = $inst->simple_query('Reconfigure Permissions in master database?', array('yes','no'),'no'); +//** Update master database rights +$reconfigure_master_database_rights_answer = $inst->simple_query('Reconfigure Permissions in master database?', array('yes', 'no'), 'no'); - if($reconfigure_master_database_rights_answer == 'yes') { - $inst->grant_master_database_rights(); - } +if($reconfigure_master_database_rights_answer == 'yes') { + $inst->grant_master_database_rights(); +} //} //** Shall the services be reconfigured during update -$reconfigure_services_answer = $inst->simple_query('Reconfigure Services?', array('yes','no'),'yes'); +$reconfigure_services_answer = $inst->simple_query('Reconfigure Services?', array('yes', 'no'), 'yes'); if($reconfigure_services_answer == 'yes') { - + if($conf['services']['mail']) { //** Configure postfix swriteln('Configuring Postfix'); $inst->configure_postfix('dont-create-certs'); - + //** Configure mailman swriteln('Configuring Mailman'); $inst->configure_mailman('update'); - + //* Configure Jailkit swriteln('Configuring Jailkit'); $inst->configure_jailkit(); @@ -274,11 +274,11 @@ if($reconfigure_services_answer == 'yes') { //** Configure saslauthd swriteln('Configuring SASL'); $inst->configure_saslauthd(); - + //** Configure PAM swriteln('Configuring PAM'); $inst->configure_pam(); - + //* Configure courier swriteln('Configuring Courier'); $inst->configure_courier(); @@ -296,13 +296,13 @@ if($reconfigure_services_answer == 'yes') { swriteln('Configuring Getmail'); $inst->configure_getmail(); } - + if($conf['services']['web'] && $conf['pureftpd']['installed'] == true) { //** Configure Pureftpd swriteln('Configuring Pureftpd'); $inst->configure_pureftpd(); } - + if($conf['services']['dns']) { //* Configure DNS if($conf['powerdns']['installed'] == true) { @@ -316,13 +316,13 @@ if($reconfigure_services_answer == 'yes') { $inst->configure_mydns(); } } - + if($conf['services']['web']) { if($conf['webserver']['server_type'] == 'apache'){ //** Configure Apache swriteln('Configuring Apache'); $inst->configure_apache(); - + //** Configure vlogger swriteln('Configuring vlogger'); $inst->configure_vlogger(); @@ -331,7 +331,7 @@ if($reconfigure_services_answer == 'yes') { swriteln('Configuring nginx'); $inst->configure_nginx(); } - + //** Configure apps vhost swriteln('Configuring Apps vhost'); $inst->configure_apps_vhost(); @@ -342,7 +342,7 @@ if($reconfigure_services_answer == 'yes') { swriteln('Configuring Database'); $inst->configure_dbserver(); - + if($conf['services']['firewall']) { if($conf['bastille']['installed'] == true) { //* Configure Bastille Firewall @@ -350,7 +350,7 @@ if($reconfigure_services_answer == 'yes') { $inst->configure_firewall(); } } - + /* if($conf['squid']['installed'] == true) { swriteln('Configuring Squid'); @@ -379,10 +379,10 @@ if ($conf['services']['web'] && $inst->install_ispconfig_interface) { } else { $conf['apache']['vhost_port'] = $inst->free_query('ISPConfig Port', $ispconfig_port_number); } - - + + // $ispconfig_ssl_default = (is_ispconfig_ssl_enabled() == true)?'y':'n'; - if(strtolower($inst->simple_query('Create new ISPConfig SSL certificate',array('yes','no'),'no')) == 'yes') { + if(strtolower($inst->simple_query('Create new ISPConfig SSL certificate', array('yes', 'no'), 'no')) == 'yes') { $inst->make_ispconfig_ssl_cert(); } } @@ -390,7 +390,7 @@ if ($conf['services']['web'] && $inst->install_ispconfig_interface) { $inst->install_ispconfig(); //** Configure Crontab -$update_crontab_answer = $inst->simple_query('Reconfigure Crontab?', array('yes','no'),'yes'); +$update_crontab_answer = $inst->simple_query('Reconfigure Crontab?', array('yes', 'no'), 'yes'); if($update_crontab_answer == 'yes') { swriteln('Updating Crontab'); $inst->install_crontab(); @@ -429,14 +429,14 @@ if($reconfigure_services_answer == 'yes') { if($conf['powerdns']['installed'] == true && $conf['powerdns']['init_script'] != '') system($inst->getinitcommand($conf['powerdns']['init_script'], 'restart').' &> /dev/null'); if($conf['bind']['installed'] == true && $conf['bind']['init_script'] != '') system($inst->getinitcommand($conf['bind']['init_script'], 'restart').' &> /dev/null'); } - + if($conf['services']['proxy']) { - // if($conf['squid']['installed'] == true && $conf['squid']['init_script'] != '' && is_executable($conf['init_scripts'].'/'.$conf['squid']['init_script'])) system($conf['init_scripts'].'/'.$conf['squid']['init_script'].' restart &> /dev/null'); + // if($conf['squid']['installed'] == true && $conf['squid']['init_script'] != '' && is_executable($conf['init_scripts'].'/'.$conf['squid']['init_script'])) system($conf['init_scripts'].'/'.$conf['squid']['init_script'].' restart &> /dev/null'); if($conf['nginx']['installed'] == true && $conf['nginx']['init_script'] != '') system($inst->getinitcommand($conf['nginx']['init_script'], 'restart').' &> /dev/null'); } - + if($conf['services']['firewall']) { - //if($conf['ufw']['installed'] == true && $conf['ufw']['init_script'] != '' && is_executable($conf['init_scripts'].'/'.$conf['ufw']['init_script'])) system($conf['init_scripts'].'/'.$conf['ufw']['init_script'].' restart &> /dev/null'); + //if($conf['ufw']['installed'] == true && $conf['ufw']['init_script'] != '' && is_executable($conf['init_scripts'].'/'.$conf['ufw']['init_script'])) system($conf['init_scripts'].'/'.$conf['ufw']['init_script'].' restart &> /dev/null'); } } diff --git a/interface/lib/app.inc.php b/interface/lib/app.inc.php index e0b237b3b635b29d4f3d4c8a4bb5701216c86081..e1929d3aa71aea4d415bf6615b5c3a8d679dfbbd 100755 --- a/interface/lib/app.inc.php +++ b/interface/lib/app.inc.php @@ -64,15 +64,15 @@ class app { //* Start the session if($this->_conf['start_session'] == true) { - + $this->uses('session'); - session_set_save_handler( array($this->session, 'open'), - array($this->session, 'close'), - array($this->session, 'read'), - array($this->session, 'write'), - array($this->session, 'destroy'), - array($this->session, 'gc')); - + session_set_save_handler( array($this->session, 'open'), + array($this->session, 'close'), + array($this->session, 'read'), + array($this->session, 'write'), + array($this->session, 'destroy'), + array($this->session, 'gc')); + session_start(); //* Initialize session variables @@ -81,10 +81,10 @@ class app { if(empty($_SESSION['s']['language'])) $_SESSION['s']['language'] = $conf['language']; } - $this->uses('functions'); // we need this before all others! + $this->uses('functions'); // we need this before all others! $this->uses('auth,plugin'); } - + public function __destruct() { session_write_close(); } @@ -96,7 +96,7 @@ class app { $classname = trim($classname); //* Class is not loaded so load it if(!array_key_exists($classname, $this->_loaded_classes)) { - include_once(ISPC_CLASS_PATH."/$classname.inc.php"); + include_once ISPC_CLASS_PATH."/$classname.inc.php"; $this->$classname = new $classname(); $this->_loaded_classes[$classname] = true; } @@ -109,12 +109,14 @@ class app { if(is_array($fl)) { foreach($fl as $file) { $file = trim($file); - include_once(ISPC_CLASS_PATH."/$file.inc.php"); + include_once ISPC_CLASS_PATH."/$file.inc.php"; } } } /** Priority values are: 0 = DEBUG, 1 = WARNING, 2 = ERROR */ + + public function log($msg, $priority = 0) { global $conf; if($priority >= $this->_conf['log_priority']) { @@ -196,12 +198,12 @@ class app { //** Helper function to load the language files. public function load_language_file($filename) { $filename = ISPC_ROOT_PATH.'/'.$filename; - if(substr($filename,-4) != '.lng') $this->error('Language file has wrong extension.'); + if(substr($filename, -4) != '.lng') $this->error('Language file has wrong extension.'); if(file_exists($filename)) { - @include($filename); + @include $filename; if(is_array($wb)) { if(is_array($this->_wb)) { - $this->_wb = array_merge($this->_wb,$wb); + $this->_wb = array_merge($this->_wb, $wb); } else { $this->_wb = $wb; } @@ -213,12 +215,12 @@ class app { $this->tpl->setVar('app_title', $this->_conf['app_title']); if(isset($_SESSION['s']['user'])) { $this->tpl->setVar('app_version', $this->_conf['app_version']); - // get pending datalog changes - $datalog = $this->db->datalogStatus(); - $this->tpl->setVar('datalog_changes_txt', $this->lng('datalog_changes_txt')); - $this->tpl->setVar('datalog_changes_end_txt', $this->lng('datalog_changes_end_txt')); - $this->tpl->setVar('datalog_changes_count', $datalog['count']); - $this->tpl->setLoop('datalog_changes', $datalog['entries']); + // get pending datalog changes + $datalog = $this->db->datalogStatus(); + $this->tpl->setVar('datalog_changes_txt', $this->lng('datalog_changes_txt')); + $this->tpl->setVar('datalog_changes_end_txt', $this->lng('datalog_changes_end_txt')); + $this->tpl->setVar('datalog_changes_count', $datalog['count']); + $this->tpl->setLoop('datalog_changes', $datalog['entries']); } else { $this->tpl->setVar('app_version', ''); } @@ -253,13 +255,13 @@ class app { $this->tpl->setVar('cpuser', $_SESSION['s']['user']['username']); $this->tpl->setVar('logout_txt', $this->lng('logout_txt')); /* Show search field only for normal users, not mail users */ - if(stristr($_SESSION['s']['user']['username'],'@')){ + if(stristr($_SESSION['s']['user']['username'], '@')){ $this->tpl->setVar('usertype', 'mailuser'); } else { $this->tpl->setVar('usertype', 'normaluser'); } } - + /* Global Search */ $this->tpl->setVar('globalsearch_resultslimit_of_txt', $this->lng('globalsearch_resultslimit_of_txt')); $this->tpl->setVar('globalsearch_resultslimit_results_txt', $this->lng('globalsearch_resultslimit_results_txt')); diff --git a/interface/lib/classes/aps_base.inc.php b/interface/lib/classes/aps_base.inc.php index 4c1512ba2a018e45f9aee6ef758be1c65e767b70..c4aaf52fd8074046b3ba24929b4e02f71e48bf83 100644 --- a/interface/lib/classes/aps_base.inc.php +++ b/interface/lib/classes/aps_base.inc.php @@ -43,61 +43,69 @@ define('PACKAGE_ERROR_NOMETA', 4); class ApsBase { - protected $log_prefix = ''; - protected $fetch_url = ''; - protected $aps_version = ''; - protected $packages_dir = ''; - protected $temp_pkg_dir = ''; - protected $interface_pkg_dir = ''; - protected $interface_mode = false; // server mode by default - - /** - * Constructor - * - * @param $app the application instance (db handle + log method) - * @param $interface_mode act in interface (true) or server mode (false) - * @param $log_prefix a prefix to set before all log entries - */ - public function __construct($app, $log_prefix = 'APS: ', $interface_mode = false) - { - $this->log_prefix = $log_prefix; - $this->interface_mode = $interface_mode; - $this->fetch_url = 'apscatalog.com'; - $this->aps_version = '1'; - $this->packages_dir = ISPC_ROOT_PATH.'/aps_packages'; - $this->interface_pkg_dir = ISPC_ROOT_PATH.'/web/sites/aps_meta_packages'; - } - - /** - * Converts a given value to it's native representation in 1024 units - * - * @param $value the size to convert - * @return integer and string - */ - public function convertSize($value) - { - $unit = array('Bytes', 'KB', 'MB', 'GB', 'TB'); - return @round($value/pow(1024, ($i = floor(log($value, 1024)))), 2).' '.$unit[$i]; - } - - /** - * Determine a specific xpath from a given SimpleXMLElement handle. If the - * element is found, it's string representation is returned. If not, - * the return value will stay empty - * - * @param $xml_handle the SimpleXMLElement handle - * @param $query the XPath query - * @param $array define whether to return an array or a string - * @return $ret the return string - */ - protected function getXPathValue($xml_handle, $query, $array = false) - { - $ret = ''; - - $xp_result = @($xml_handle->xpath($query)) ? $xml_handle->xpath($query) : false; - if($xp_result !== false) $ret = (($array === false) ? (string)$xp_result[0] : $xp_result); - - return $ret; - } + protected $log_prefix = ''; + protected $fetch_url = ''; + protected $aps_version = ''; + protected $packages_dir = ''; + protected $temp_pkg_dir = ''; + protected $interface_pkg_dir = ''; + protected $interface_mode = false; // server mode by default + + /** + * Constructor + * + * @param $app the application instance (db handle + log method) + * @param $interface_mode act in interface (true) or server mode (false) + * @param $log_prefix a prefix to set before all log entries + */ + + + public function __construct($app, $log_prefix = 'APS: ', $interface_mode = false) + { + $this->log_prefix = $log_prefix; + $this->interface_mode = $interface_mode; + $this->fetch_url = 'apscatalog.com'; + $this->aps_version = '1'; + $this->packages_dir = ISPC_ROOT_PATH.'/aps_packages'; + $this->interface_pkg_dir = ISPC_ROOT_PATH.'/web/sites/aps_meta_packages'; + } + + + + /** + * Converts a given value to it's native representation in 1024 units + * + * @param $value the size to convert + * @return integer and string + */ + public function convertSize($value) + { + $unit = array('Bytes', 'KB', 'MB', 'GB', 'TB'); + return @round($value/pow(1024, ($i = floor(log($value, 1024)))), 2).' '.$unit[$i]; + } + + + + /** + * Determine a specific xpath from a given SimpleXMLElement handle. If the + * element is found, it's string representation is returned. If not, + * the return value will stay empty + * + * @param $xml_handle the SimpleXMLElement handle + * @param $query the XPath query + * @param $array define whether to return an array or a string + * @return $ret the return string + */ + protected function getXPathValue($xml_handle, $query, $array = false) + { + $ret = ''; + + $xp_result = @($xml_handle->xpath($query)) ? $xml_handle->xpath($query) : false; + if($xp_result !== false) $ret = (($array === false) ? (string)$xp_result[0] : $xp_result); + + return $ret; + } + } -?> \ No newline at end of file + +?> diff --git a/interface/lib/classes/aps_crawler.inc.php b/interface/lib/classes/aps_crawler.inc.php index 2c6906efda50d4716a66c664dc3ab04ef78cc4d4..8260f340973be59fa6b68fc9e24b9aff601593f8 100644 --- a/interface/lib/classes/aps_crawler.inc.php +++ b/interface/lib/classes/aps_crawler.inc.php @@ -27,264 +27,277 @@ OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -require_once('aps_base.inc.php'); +require_once 'aps_base.inc.php'; @set_time_limit(0); @ignore_user_abort(1); class ApsCrawler extends ApsBase { - - //public $app_download_url_list = array(); - - /** - * Constructor - * - * @param $app the application instance (db handle + log method) - * @param $interface_mode act in interface (true) or server mode (false) - */ - public function __construct($app, $interface_mode = false) - { - parent::__construct($app, 'APS crawler: ', $interface_mode); - } - - /** - * Before the cron is executed, make sure all necessary options are set - * and all functions (i.e. cURL) are available - */ - private function checkRequirements() - { - global $app; - - try - { - // Check if allow_url_fopen is enabled - if(!@ini_get('allow_url_fopen')) throw new Exception('allow_url_fopen is not enabled'); - // Check if the cURL module is available - if(!function_exists('curl_version')) throw new Exception('cURL is not available'); - - // Check if used folders are writable - if($this->interface_mode) - { - if(!is_writable($this->interface_pkg_dir)) - throw new Exception('the folder '.basename($this->interface_pkg_dir).' is not writable'); - } - else - { - if(!is_writable($this->packages_dir)) - throw new Exception('the folder '.basename($this->packages_dir).' is not writable'); - } - - return true; - } - catch(Exception $e) - { - $app->log($this->log_prefix.'Aborting execution because '.$e->getMessage(), LOGLEVEL_ERROR); - return false; - } - } - - /** - * Remove a directory recursively - * In case of error be silent - * - * @param $dir the directory to remove - */ - private function removeDirectory($dir) - { - if(is_dir($dir)) - { - $files = scandir($dir); - foreach($files as $file) - { - if($file != '.' && $file != '..') - if(filetype($dir.'/'.$file) == 'dir') $this->removeDirectory($dir.'/'.$file); - else @unlink($dir.'/'.$file); - } - reset($files); - @rmdir($dir); - } - } - - - /** - * Fetch HTML data from one or more given URLs - * If a string is given, a string is returned, if an array of URLs should - * be fetched, the responses of the parallel queries are returned as array - * - * @param $input the string or array to fetch - * @return $ret a query response string or array - */ - private function fetchPage($input) - { - $ret = array(); - $url = array(); - $conn = array(); - - // Make sure we are working with an array, further on - if(!is_array($input)) $url[] = $input; - else $url = $input; - - // Build the single cURL handles and add them to a multi handle - $mh = curl_multi_init(); - for($i = 0; $i < count($url); $i++) - { - $conn[$i] = curl_init('http://'.$this->fetch_url.$url[$i]); - curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, true); - curl_multi_add_handle($mh, $conn[$i]); - } - - $active = 0; - do curl_multi_exec($mh, $active); - while($active > 0); - - // Get the response(s) - for($i = 0; $i < count($url); $i++) - { - $ret[$i] = curl_multi_getcontent($conn[$i]); - curl_multi_remove_handle($mh, $conn[$i]); - curl_close($conn[$i]); - } - curl_multi_close($mh); - - if(count($url) == 1) $ret = $ret[0]; - - return $ret; - } - - /** - * Fetch binary data from a given array - * The data is retrieved in binary mode and - * then directly written to an output file - * - * @param $input a specially structed array - * @see $this->startUpdate() - */ - private function fetchFiles($input) - { - $fh = array(); - $url = array(); - $conn = array(); - - // Build the single cURL handles and add them to a multi handle - $mh = curl_multi_init(); - - // Process each app - for($i = 0; $i < count($input); $i++) - { - $conn[$i] = curl_init($input[$i]['url']); - $fh[$i] = fopen($input[$i]['localtarget'], 'wb'); - - curl_setopt($conn[$i], CURLOPT_BINARYTRANSFER, true); - curl_setopt($conn[$i], CURLOPT_FILE, $fh[$i]); - curl_setopt($conn[$i], CURLOPT_TIMEOUT, 0); - curl_setopt($conn[$i], CURLOPT_FAILONERROR, 1); - curl_setopt($conn[$i], CURLOPT_FOLLOWLOCATION, 1); - - curl_multi_add_handle($mh, $conn[$i]); - } - - $active = 0; - do curl_multi_exec($mh, $active); - while($active > 0); - - // Close the handles - for($i = 0; $i < count($input); $i++) - { - fclose($fh[$i]); - curl_multi_remove_handle($mh, $conn[$i]); - curl_close($conn[$i]); - } - curl_multi_close($mh); - } - - /** - * A method to build query URLs out of a list of vendors - * - */ - private function formatVendorCallback($array_item) - { - $array_item = str_replace(' ', '%20', $array_item); - $array_item = str_replace('http://', '', $array_item); - $array_item = '/'.$this->aps_version.'.atom?vendor='.$array_item.'&pageSize=100'; - return($array_item); - } - - /** - * The main method which performs the actual crawling - */ - public function startCrawler() - { - global $app; - - try - { - // Make sure the requirements are given so that this script can execute - $req_ret = $this->checkRequirements(); - if(!$req_ret) return false; - - // Execute the open task and first fetch all vendors (APS catalog API 1.1, p. 12) - $app->log($this->log_prefix.'Fetching data from '.$this->fetch_url); - - $vendor_page = $this->fetchPage('/all-app/'); //$vendor_page = $this->fetchPage('/'.$this->aps_version.'/'); - preg_match_all("/\ /1.atom?vendor=typo3.org&pageSize=100 - //array_walk($vendors, array($this, 'formatVendorCallback')); + + //public $app_download_url_list = array(); + + /** + * Constructor + * + * @param $app the application instance (db handle + log method) + * @param $interface_mode act in interface (true) or server mode (false) + */ + + + public function __construct($app, $interface_mode = false) + { + parent::__construct($app, 'APS crawler: ', $interface_mode); + } + + + + /** + * Before the cron is executed, make sure all necessary options are set + * and all functions (i.e. cURL) are available + */ + private function checkRequirements() + { + global $app; + + try + { + // Check if allow_url_fopen is enabled + if(!@ini_get('allow_url_fopen')) throw new Exception('allow_url_fopen is not enabled'); + // Check if the cURL module is available + if(!function_exists('curl_version')) throw new Exception('cURL is not available'); + + // Check if used folders are writable + if($this->interface_mode) + { + if(!is_writable($this->interface_pkg_dir)) + throw new Exception('the folder '.basename($this->interface_pkg_dir).' is not writable'); + } + else + { + if(!is_writable($this->packages_dir)) + throw new Exception('the folder '.basename($this->packages_dir).' is not writable'); + } + + return true; + } + + catch(Exception $e) + { + $app->log($this->log_prefix.'Aborting execution because '.$e->getMessage(), LOGLEVEL_ERROR); + return false; + } + } + + + + /** + * Remove a directory recursively + * In case of error be silent + * + * @param $dir the directory to remove + */ + private function removeDirectory($dir) + { + if(is_dir($dir)) + { + $files = scandir($dir); + foreach($files as $file) + { + if($file != '.' && $file != '..') + if(filetype($dir.'/'.$file) == 'dir') $this->removeDirectory($dir.'/'.$file); + else @unlink($dir.'/'.$file); + } + reset($files); + @rmdir($dir); + } + } + + + /** + * Fetch HTML data from one or more given URLs + * If a string is given, a string is returned, if an array of URLs should + * be fetched, the responses of the parallel queries are returned as array + * + * @param $input the string or array to fetch + * @return $ret a query response string or array + */ + private function fetchPage($input) + { + $ret = array(); + $url = array(); + $conn = array(); + + // Make sure we are working with an array, further on + if(!is_array($input)) $url[] = $input; + else $url = $input; + + // Build the single cURL handles and add them to a multi handle + $mh = curl_multi_init(); + for($i = 0; $i < count($url); $i++) + { + $conn[$i] = curl_init('http://'.$this->fetch_url.$url[$i]); + curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, true); + curl_multi_add_handle($mh, $conn[$i]); + } + + $active = 0; + do curl_multi_exec($mh, $active); + while($active > 0); + + // Get the response(s) + for($i = 0; $i < count($url); $i++) + { + $ret[$i] = curl_multi_getcontent($conn[$i]); + curl_multi_remove_handle($mh, $conn[$i]); + curl_close($conn[$i]); + } + curl_multi_close($mh); + + if(count($url) == 1) $ret = $ret[0]; + + return $ret; + } + + + + /** + * Fetch binary data from a given array + * The data is retrieved in binary mode and + * then directly written to an output file + * + * @param $input a specially structed array + * @see $this->startUpdate() + */ + private function fetchFiles($input) + { + $fh = array(); + $url = array(); + $conn = array(); + + // Build the single cURL handles and add them to a multi handle + $mh = curl_multi_init(); + + // Process each app + for($i = 0; $i < count($input); $i++) + { + $conn[$i] = curl_init($input[$i]['url']); + $fh[$i] = fopen($input[$i]['localtarget'], 'wb'); + + curl_setopt($conn[$i], CURLOPT_BINARYTRANSFER, true); + curl_setopt($conn[$i], CURLOPT_FILE, $fh[$i]); + curl_setopt($conn[$i], CURLOPT_TIMEOUT, 0); + curl_setopt($conn[$i], CURLOPT_FAILONERROR, 1); + curl_setopt($conn[$i], CURLOPT_FOLLOWLOCATION, 1); + + curl_multi_add_handle($mh, $conn[$i]); + } + + $active = 0; + do curl_multi_exec($mh, $active); + while($active > 0); + + // Close the handles + for($i = 0; $i < count($input); $i++) + { + fclose($fh[$i]); + curl_multi_remove_handle($mh, $conn[$i]); + curl_close($conn[$i]); + } + curl_multi_close($mh); + } + + + + /** + * A method to build query URLs out of a list of vendors + * + */ + private function formatVendorCallback($array_item) + { + $array_item = str_replace(' ', '%20', $array_item); + $array_item = str_replace('http://', '', $array_item); + $array_item = '/'.$this->aps_version.'.atom?vendor='.$array_item.'&pageSize=100'; + return $array_item; + } + + + + /** + * The main method which performs the actual crawling + */ + public function startCrawler() + { + global $app; + + try + { + // Make sure the requirements are given so that this script can execute + $req_ret = $this->checkRequirements(); + if(!$req_ret) return false; + + // Execute the open task and first fetch all vendors (APS catalog API 1.1, p. 12) + $app->log($this->log_prefix.'Fetching data from '.$this->fetch_url); + + $vendor_page = $this->fetchPage('/all-app/'); //$vendor_page = $this->fetchPage('/'.$this->aps_version.'/'); + preg_match_all("/\ /1.atom?vendor=typo3.org&pageSize=100 + //array_walk($vendors, array($this, 'formatVendorCallback')); if(is_array($vendors)) { foreach($vendors as $key => $array_item) { $vendors[$key] = $this->formatVendorCallback($array_item); } } - - // Process all vendors in chunks of 50 entries - $vendor_chunks = array_chunk($vendors, 50); - //var_dump($vendor_chunks); - - // Get all known apps from the database and the highest known version - // Note: A dirty hack is used for numerical sorting of the VARCHAR field Version: +0 -> cast - // A longer but typesafe way would be: ORDER BY CAST(REPLACE(Version, '.', '') AS UNSIGNED) DESC - $existing_apps = $app->db->queryAllRecords("SELECT * FROM ( - SELECT name AS Name, CONCAT(version, '-', CAST(`release` AS CHAR)) AS CurrentVersion + + // Process all vendors in chunks of 50 entries + $vendor_chunks = array_chunk($vendors, 50); + //var_dump($vendor_chunks); + + // Get all known apps from the database and the highest known version + // Note: A dirty hack is used for numerical sorting of the VARCHAR field Version: +0 -> cast + // A longer but typesafe way would be: ORDER BY CAST(REPLACE(Version, '.', '') AS UNSIGNED) DESC + $existing_apps = $app->db->queryAllRecords("SELECT * FROM ( + SELECT name AS Name, CONCAT(version, '-', CAST(`release` AS CHAR)) AS CurrentVersion FROM aps_packages ORDER BY REPLACE(version, '.', '')+0 DESC, `release` DESC ) as Versions GROUP BY name"); - //var_dump($existing_apps); - - // Used for statistics later - $apps_in_repo = 0; - $apps_updated = 0; - $apps_downloaded = 0; - - $apps_to_dl = array(); - - for($i = 0; $i < count($vendor_chunks); $i++) - { - // Fetch all apps for the current chunk of vendors - $apps = $this->fetchPage($vendor_chunks[$i]); - - for($j = 0; $j < count($apps); $j++) - { - // Before parsing, make sure it's worth the work by checking if at least one app exists - $apps_count = substr_count($apps[$j], '0'); - if($apps_count == 0) // obviously this vendor provides one or more apps - { - // Rename namespaces and register them - $xml = str_replace("xmlns=", "ns=", $apps[$j]); - $sxe = new SimpleXMLElement($xml); - $namespaces = $sxe->getDocNamespaces(true); - foreach($namespaces as $ns => $url) $sxe->registerXPathNamespace($ns, $url); - - // Fetching values of interest - $app_name = parent::getXPathValue($sxe, 'entry[position()=1]/a:name'); - $app_version = parent::getXPathValue($sxe, 'entry[position()=1]/a:version'); - $app_release = parent::getXPathValue($sxe, 'entry[position()=1]/a:release'); - - // Find out a (possibly) existing package version - $ex_ver = ''; + //var_dump($existing_apps); + + // Used for statistics later + $apps_in_repo = 0; + $apps_updated = 0; + $apps_downloaded = 0; + + $apps_to_dl = array(); + + for($i = 0; $i < count($vendor_chunks); $i++) + { + // Fetch all apps for the current chunk of vendors + $apps = $this->fetchPage($vendor_chunks[$i]); + + for($j = 0; $j < count($apps); $j++) + { + // Before parsing, make sure it's worth the work by checking if at least one app exists + $apps_count = substr_count($apps[$j], '0'); + if($apps_count == 0) // obviously this vendor provides one or more apps + { + // Rename namespaces and register them + $xml = str_replace("xmlns=", "ns=", $apps[$j]); + $sxe = new SimpleXMLElement($xml); + $namespaces = $sxe->getDocNamespaces(true); + foreach($namespaces as $ns => $url) $sxe->registerXPathNamespace($ns, $url); + + // Fetching values of interest + $app_name = parent::getXPathValue($sxe, 'entry[position()=1]/a:name'); + $app_version = parent::getXPathValue($sxe, 'entry[position()=1]/a:version'); + $app_release = parent::getXPathValue($sxe, 'entry[position()=1]/a:release'); + + // Find out a (possibly) existing package version + $ex_ver = ''; /* - array_walk($existing_apps, + array_walk($existing_apps, create_function('$v, $k, $ex_ver', 'if($v["Name"] == "'.$app_name.'") $ex_ver = $v["CurrentVersion"];'), &$ex_ver); */ if(is_array($existing_apps)) { @@ -292,286 +305,292 @@ class ApsCrawler extends ApsBase if($v["Name"] == $app_name) $ex_ver = $v["CurrentVersion"]; } } - - $new_ver = $app_version.'-'.$app_release; - $local_intf_folder = $this->interface_pkg_dir.'/'.$app_name.'-'.$new_ver.'.app.zip/'; - - // Proceed if a newer or at least equal version has been found with server mode or - // interface mode is activated and there are no valid APP-META.xml and PKG_URL existing yet - if((!$this->interface_mode && version_compare($new_ver, $ex_ver) >= 0) || ($this->interface_mode && (!file_exists($local_intf_folder.'APP-META.xml') || filesize($local_intf_folder.'APP-META.xml') == 0 || !file_exists($local_intf_folder.'PKG_URL') || filesize($local_intf_folder.'PKG_URL') == 0))){ - // Check if we already have an old version of this app - if(!empty($ex_ver) && version_compare($new_ver, $ex_ver) == 1) $apps_updated++; - - $app_dl = parent::getXPathValue($sxe, "entry[position()=1]/link[@a:type='aps']/@href"); - $app_filesize = parent::getXPathValue($sxe, "entry[position()=1]/link[@a:type='aps']/@length"); - $app_metafile = parent::getXPathValue($sxe, "entry[position()=1]/link[@a:type='meta']/@href"); - + + $new_ver = $app_version.'-'.$app_release; + $local_intf_folder = $this->interface_pkg_dir.'/'.$app_name.'-'.$new_ver.'.app.zip/'; + + // Proceed if a newer or at least equal version has been found with server mode or + // interface mode is activated and there are no valid APP-META.xml and PKG_URL existing yet + if((!$this->interface_mode && version_compare($new_ver, $ex_ver) >= 0) || ($this->interface_mode && (!file_exists($local_intf_folder.'APP-META.xml') || filesize($local_intf_folder.'APP-META.xml') == 0 || !file_exists($local_intf_folder.'PKG_URL') || filesize($local_intf_folder.'PKG_URL') == 0))){ + // Check if we already have an old version of this app + if(!empty($ex_ver) && version_compare($new_ver, $ex_ver) == 1) $apps_updated++; + + $app_dl = parent::getXPathValue($sxe, "entry[position()=1]/link[@a:type='aps']/@href"); + $app_filesize = parent::getXPathValue($sxe, "entry[position()=1]/link[@a:type='aps']/@length"); + $app_metafile = parent::getXPathValue($sxe, "entry[position()=1]/link[@a:type='meta']/@href"); + //$this->app_download_url_list[$app_name.'-'.$new_ver.'.app.zip'] = $app_dl; - // Skip ASP.net packages because they can't be used at all - $asp_handler = parent::getXPathValue($sxe, '//aspnet:handler'); - $asp_permissions = parent::getXPathValue($sxe, '//aspnet:permissions'); - $asp_version = parent::getXPathValue($sxe, '//aspnet:version'); - if(!empty($asp_handler) || !empty($asp_permissions) || !empty($asp_version)) continue; - - // Interface mode (download only parts) - if($this->interface_mode) - { - // Delete an obviously out-dated version from the system and DB - if(!empty($ex_ver) && version_compare($new_ver, $ex_ver) == 1) - { - $old_folder = $this->interface_pkg_dir.'/'.$app_name.'-'.$ex_ver.'.app.zip'; - if(file_exists($old_folder)) $this->removeDirectory($old_folder); - + // Skip ASP.net packages because they can't be used at all + $asp_handler = parent::getXPathValue($sxe, '//aspnet:handler'); + $asp_permissions = parent::getXPathValue($sxe, '//aspnet:permissions'); + $asp_version = parent::getXPathValue($sxe, '//aspnet:version'); + if(!empty($asp_handler) || !empty($asp_permissions) || !empty($asp_version)) continue; + + // Interface mode (download only parts) + if($this->interface_mode) + { + // Delete an obviously out-dated version from the system and DB + if(!empty($ex_ver) && version_compare($new_ver, $ex_ver) == 1) + { + $old_folder = $this->interface_pkg_dir.'/'.$app_name.'-'.$ex_ver.'.app.zip'; + if(file_exists($old_folder)) $this->removeDirectory($old_folder); + /* $app->db->query("UPDATE aps_packages SET package_status = '".PACKAGE_OUTDATED."' WHERE name = '". $app->db->quote($app_name)."' AND CONCAT(version, '-', CAST(`release` AS CHAR)) = '". $app->db->quote($ex_ver)."';"); */ $tmp = $app->db->queryOneRecord("SELECT id FROM aps_packages WHERE name = '". - $app->db->quote($app_name)."' AND CONCAT(version, '-', CAST(`release` AS CHAR)) = '". - $app->db->quote($ex_ver)."';"); + $app->db->quote($app_name)."' AND CONCAT(version, '-', CAST(`release` AS CHAR)) = '". + $app->db->quote($ex_ver)."';"); $app->db->datalogUpdate('aps_packages', "package_status = ".PACKAGE_OUTDATED, 'id', $tmp['id']); unset($tmp); - } - - // Create the local folder if not yet existing - if(!file_exists($local_intf_folder)) @mkdir($local_intf_folder, 0777, true); - + } + + // Create the local folder if not yet existing + if(!file_exists($local_intf_folder)) @mkdir($local_intf_folder, 0777, true); + // Save the package URL in an extra file because it's not part of the APP-META.xml file @file_put_contents($local_intf_folder.'PKG_URL', $app_dl); - - // Download the meta file - $local_metafile = $local_intf_folder.'APP-META.xml'; - if(!file_exists($local_metafile) || filesize($local_metafile) == 0) - { - $apps_to_dl[] = array('name' => 'APP-META.xml', - 'url' => $app_metafile, - 'filesize' => 0, - 'localtarget' => $local_metafile); - $apps_downloaded++; - } - - // Download package license - $license = parent::getXPathValue($sxe, "entry[position()=1]/link[@a:type='eula']/@href"); - if($license != '') - { - $local_license = $local_intf_folder.'LICENSE'; - if(!file_exists($local_license) || filesize($local_license) == 0) - { - $apps_to_dl[] = array('name' => basename($license), - 'url' => $license, - 'filesize' => 0, - 'localtarget' => $local_license); - } - } - - // Download package icon - $icon = parent::getXPathValue($sxe, "entry[position()=1]/link[@a:type='icon']/@href"); - if($icon != '') - { - $local_icon = $local_intf_folder.basename($icon); - if(!file_exists($local_icon) || filesize($local_icon) == 0) - { - $apps_to_dl[] = array('name' => basename($icon), - 'url' => $icon, - 'filesize' => 0, - 'localtarget' => $local_icon); - } - } - - // Download available screenshots - $screenshots = parent::getXPathValue($sxe, "entry[position()=1]/link[@a:type='screenshot']", true); - if(!empty($screenshots)) - { - foreach($screenshots as $screen) - { - $local_screen = $local_intf_folder.basename($screen['href']); - if(!file_exists($local_screen) || filesize($local_screen) == 0) - { - $apps_to_dl[] = array('name' => basename($screen['href']), - 'url' => $screen['href'], - 'filesize' => 0, - 'localtarget' => $local_screen); - } - } - } - } - else // Server mode (download whole ZIP archive) - { - // Delete an obviously out-dated version from the system - if(!empty($ex_ver) && version_compare($new_ver, $ex_ver) == 1) - { - $old_file = $this->packages_dir.'/'.$app_name.'-'.$ex_ver.'.app.zip'; - if(file_exists($old_file)) $this->removeDirectory($old_file); - } - - // Attention: $new_ver can also be == $ex_ver (according to version_compare >= 0) - $local_zip = $this->packages_dir.'/'.$app_name.'-'.$new_ver.'.app.zip'; - - // Before re-downloading a file, make sure it's not yet existing on HDD (due to DB inconsistency) - if((file_exists($local_zip) && (filesize($local_zip) == $app_filesize)) === false) - { - $apps_to_dl[] = array('name' => $app_name, - 'url' => $app_dl, - 'filesize' => $app_filesize, - 'localtarget' => $local_zip); - $apps_downloaded++; - } - } - } - - unset($sxe); - $apps_in_repo++; - } - } - //var_dump($apps); - - // For memory reasons, unset the current vendor and his apps - unset($apps); - } - - // Shuffle the download array (in order to compensate unexpected php aborts) - shuffle($apps_to_dl); - - // After collecting all provisioned apps, download them - $apps_to_dl_chunks = array_chunk($apps_to_dl, 10); - - for($i = 0; $i < count($apps_to_dl_chunks); $i++) - { - $this->fetchFiles($apps_to_dl_chunks[$i]); - - // Check the integrity of all downloaded files - // but exclude cases where no filesize is available (i.e. screenshot or metafile download) - for($j = 0; $j < count($apps_to_dl_chunks[$i]); $j++) - { - if($apps_to_dl_chunks[$i][$j]['filesize'] != 0 && - $apps_to_dl_chunks[$i][$j]['filesize'] != filesize($apps_to_dl_chunks[$i][$j]['localtarget'])) - { - $app->log($this->log_prefix.' The filesize of the package "'. - $apps_to_dl_chunks[$i][$j]['name'].'" is wrong. Download failure?', LOGLEVEL_WARN); - } - } - } - - $app->log($this->log_prefix.'Processed '.$apps_in_repo. - ' apps from the repo. Downloaded '.$apps_updated. - ' updates, '.$apps_downloaded.' new apps'); - } - catch(Exception $e) - { - $app->log($this->log_prefix.$e->getMessage(), LOGLEVEL_ERROR); - return false; - } - } - - /** - * Read in all possible packages from the interface packages folder and - * check if they are not ASP.net code (as this can't be processed). - * - * Note: There's no need to check if the packages to register are newer - * than those in the database because this already happended in startCrawler() - */ - public function parseFolderToDB() - { - global $app; - - try - { - // This method must be used in interface mode - if(!$this->interface_mode) return false; - - $pkg_list = array(); - - // Read in every package having a correct filename - $temp_handle = @dir($this->interface_pkg_dir); - if(!$temp_handle) throw new Exception('The temp directory is not accessible'); - while($folder = $temp_handle->read()) - if(substr($folder, -8) == '.app.zip') $pkg_list[] = $folder; - $temp_handle->close(); - - // If no packages are available -> exception (because at this point there should exist packages) - if(empty($pkg_list)) throw new Exception('No packages to read in'); - - // Get registered packages and mark non-existant packages with an error code to omit the install - $existing_packages = array(); - $path_query = $app->db->queryAllRecords('SELECT path AS Path FROM aps_packages;'); - foreach($path_query as $path) $existing_packages[] = $path['Path']; - $diff = array_diff($existing_packages, $pkg_list); - foreach($diff as $todelete) { - /*$app->db->query("UPDATE aps_packages SET package_status = '".PACKAGE_ERROR_NOMETA."' + + // Download the meta file + $local_metafile = $local_intf_folder.'APP-META.xml'; + if(!file_exists($local_metafile) || filesize($local_metafile) == 0) + { + $apps_to_dl[] = array('name' => 'APP-META.xml', + 'url' => $app_metafile, + 'filesize' => 0, + 'localtarget' => $local_metafile); + $apps_downloaded++; + } + + // Download package license + $license = parent::getXPathValue($sxe, "entry[position()=1]/link[@a:type='eula']/@href"); + if($license != '') + { + $local_license = $local_intf_folder.'LICENSE'; + if(!file_exists($local_license) || filesize($local_license) == 0) + { + $apps_to_dl[] = array('name' => basename($license), + 'url' => $license, + 'filesize' => 0, + 'localtarget' => $local_license); + } + } + + // Download package icon + $icon = parent::getXPathValue($sxe, "entry[position()=1]/link[@a:type='icon']/@href"); + if($icon != '') + { + $local_icon = $local_intf_folder.basename($icon); + if(!file_exists($local_icon) || filesize($local_icon) == 0) + { + $apps_to_dl[] = array('name' => basename($icon), + 'url' => $icon, + 'filesize' => 0, + 'localtarget' => $local_icon); + } + } + + // Download available screenshots + $screenshots = parent::getXPathValue($sxe, "entry[position()=1]/link[@a:type='screenshot']", true); + if(!empty($screenshots)) + { + foreach($screenshots as $screen) + { + $local_screen = $local_intf_folder.basename($screen['href']); + if(!file_exists($local_screen) || filesize($local_screen) == 0) + { + $apps_to_dl[] = array('name' => basename($screen['href']), + 'url' => $screen['href'], + 'filesize' => 0, + 'localtarget' => $local_screen); + } + } + } + } + else // Server mode (download whole ZIP archive) + { + // Delete an obviously out-dated version from the system + if(!empty($ex_ver) && version_compare($new_ver, $ex_ver) == 1) + { + $old_file = $this->packages_dir.'/'.$app_name.'-'.$ex_ver.'.app.zip'; + if(file_exists($old_file)) $this->removeDirectory($old_file); + } + + // Attention: $new_ver can also be == $ex_ver (according to version_compare >= 0) + $local_zip = $this->packages_dir.'/'.$app_name.'-'.$new_ver.'.app.zip'; + + // Before re-downloading a file, make sure it's not yet existing on HDD (due to DB inconsistency) + if((file_exists($local_zip) && (filesize($local_zip) == $app_filesize)) === false) + { + $apps_to_dl[] = array('name' => $app_name, + 'url' => $app_dl, + 'filesize' => $app_filesize, + 'localtarget' => $local_zip); + $apps_downloaded++; + } + } + } + + unset($sxe); + $apps_in_repo++; + } + } + //var_dump($apps); + + // For memory reasons, unset the current vendor and his apps + unset($apps); + } + + // Shuffle the download array (in order to compensate unexpected php aborts) + shuffle($apps_to_dl); + + // After collecting all provisioned apps, download them + $apps_to_dl_chunks = array_chunk($apps_to_dl, 10); + + for($i = 0; $i < count($apps_to_dl_chunks); $i++) + { + $this->fetchFiles($apps_to_dl_chunks[$i]); + + // Check the integrity of all downloaded files + // but exclude cases where no filesize is available (i.e. screenshot or metafile download) + for($j = 0; $j < count($apps_to_dl_chunks[$i]); $j++) + { + if($apps_to_dl_chunks[$i][$j]['filesize'] != 0 && + $apps_to_dl_chunks[$i][$j]['filesize'] != filesize($apps_to_dl_chunks[$i][$j]['localtarget'])) + { + $app->log($this->log_prefix.' The filesize of the package "'. + $apps_to_dl_chunks[$i][$j]['name'].'" is wrong. Download failure?', LOGLEVEL_WARN); + } + } + } + + $app->log($this->log_prefix.'Processed '.$apps_in_repo. + ' apps from the repo. Downloaded '.$apps_updated. + ' updates, '.$apps_downloaded.' new apps'); + } + + catch(Exception $e) + { + $app->log($this->log_prefix.$e->getMessage(), LOGLEVEL_ERROR); + return false; + } + } + + + + /** + * Read in all possible packages from the interface packages folder and + * check if they are not ASP.net code (as this can't be processed). + * + * Note: There's no need to check if the packages to register are newer + * than those in the database because this already happended in startCrawler() + */ + public function parseFolderToDB() + { + global $app; + + try + { + // This method must be used in interface mode + if(!$this->interface_mode) return false; + + $pkg_list = array(); + + // Read in every package having a correct filename + $temp_handle = @dir($this->interface_pkg_dir); + if(!$temp_handle) throw new Exception('The temp directory is not accessible'); + while($folder = $temp_handle->read()) + if(substr($folder, -8) == '.app.zip') $pkg_list[] = $folder; + $temp_handle->close(); + + // If no packages are available -> exception (because at this point there should exist packages) + if(empty($pkg_list)) throw new Exception('No packages to read in'); + + // Get registered packages and mark non-existant packages with an error code to omit the install + $existing_packages = array(); + $path_query = $app->db->queryAllRecords('SELECT path AS Path FROM aps_packages;'); + foreach($path_query as $path) $existing_packages[] = $path['Path']; + $diff = array_diff($existing_packages, $pkg_list); + foreach($diff as $todelete) { + /*$app->db->query("UPDATE aps_packages SET package_status = '".PACKAGE_ERROR_NOMETA."' WHERE path = '".$app->db->quote($todelete)."';");*/ $tmp = $app->db->queryOneRecord("SELECT id FROM aps_packages WHERE path = '".$app->db->quote($todelete)."';"); $app->db->datalogUpdate('aps_packages', "package_status = ".PACKAGE_ERROR_NOMETA, 'id', $tmp['id']); unset($tmp); } - - // Register all new packages - $new_packages = array_diff($pkg_list, $existing_packages); - foreach($new_packages as $pkg) - { - // Load in meta file if existing and register its namespaces - $metafile = $this->interface_pkg_dir.'/'.$pkg.'/APP-META.xml'; - if(!file_exists($metafile)) - { - $app->log($this->log_prefix.'Cannot read metadata from '.$pkg, LOGLEVEL_ERROR); - continue; - } - - $metadata = file_get_contents($metafile); - $metadata = str_replace("xmlns=", "ns=", $metadata); - $sxe = new SimpleXMLElement($metadata); - $namespaces = $sxe->getDocNamespaces(true); - foreach($namespaces as $ns => $url) $sxe->registerXPathNamespace($ns, $url); - - // Insert the new package - $pkg_name = parent::getXPathValue($sxe, 'name'); - $pkg_category = parent::getXPathValue($sxe, '//category'); - $pkg_version = parent::getXPathValue($sxe, 'version'); - $pkg_release = parent::getXPathValue($sxe, 'release'); + + // Register all new packages + $new_packages = array_diff($pkg_list, $existing_packages); + foreach($new_packages as $pkg) + { + // Load in meta file if existing and register its namespaces + $metafile = $this->interface_pkg_dir.'/'.$pkg.'/APP-META.xml'; + if(!file_exists($metafile)) + { + $app->log($this->log_prefix.'Cannot read metadata from '.$pkg, LOGLEVEL_ERROR); + continue; + } + + $metadata = file_get_contents($metafile); + $metadata = str_replace("xmlns=", "ns=", $metadata); + $sxe = new SimpleXMLElement($metadata); + $namespaces = $sxe->getDocNamespaces(true); + foreach($namespaces as $ns => $url) $sxe->registerXPathNamespace($ns, $url); + + // Insert the new package + $pkg_name = parent::getXPathValue($sxe, 'name'); + $pkg_category = parent::getXPathValue($sxe, '//category'); + $pkg_version = parent::getXPathValue($sxe, 'version'); + $pkg_release = parent::getXPathValue($sxe, 'release'); //$pkg_url = $this->app_download_url_list[$pkg]; $pkg_url = @file_get_contents($this->interface_pkg_dir.'/'.$pkg.'/PKG_URL'); - + /* - $app->db->query("INSERT INTO `aps_packages` - (`path`, `name`, `category`, `version`, `release`, `package_status`) VALUES + $app->db->query("INSERT INTO `aps_packages` + (`path`, `name`, `category`, `version`, `release`, `package_status`) VALUES ('".$app->db->quote($pkg)."', '".$app->db->quote($pkg_name)."', '".$app->db->quote($pkg_category)."', '".$app->db->quote($pkg_version)."', ".$app->db->quote($pkg_release).", ".PACKAGE_ENABLED.");"); */ // Insert only if data is complete if($pkg != '' && $pkg_name != '' && $pkg_category != '' && $pkg_version != '' && $pkg_release != '' && $pkg_url){ - $insert_data = "(`path`, `name`, `category`, `version`, `release`, `package_url`, `package_status`) VALUES + $insert_data = "(`path`, `name`, `category`, `version`, `release`, `package_url`, `package_status`) VALUES ('".$app->db->quote($pkg)."', '".$app->db->quote($pkg_name)."', '".$app->db->quote($pkg_category)."', '".$app->db->quote($pkg_version)."', ".$app->db->quote($pkg_release).", '".$app->db->quote($pkg_url)."', ".PACKAGE_ENABLED.");"; - + $app->db->datalogInsert('aps_packages', $insert_data, 'id'); } else { if(file_exists($this->interface_pkg_dir.'/'.$pkg)) $this->removeDirectory($this->interface_pkg_dir.'/'.$pkg); } - } - } - catch(Exception $e) - { - $app->log($this->log_prefix.$e->getMessage(), LOGLEVEL_ERROR); + } + } + + catch(Exception $e) + { + $app->log($this->log_prefix.$e->getMessage(), LOGLEVEL_ERROR); $app->error($e->getMessage()); - return false; - } - } - + return false; + } + } + + + /** - * Add missing package URLs to database - */ - public function fixURLs() - { - global $app; - - try - { - // This method must be used in interface mode - if(!$this->interface_mode) return false; - - $incomplete_pkgs = $app->db->queryAllRecords("SELECT * FROM aps_packages WHERE package_url = ''"); + * Add missing package URLs to database + */ + public function fixURLs() + { + global $app; + + try + { + // This method must be used in interface mode + if(!$this->interface_mode) return false; + + $incomplete_pkgs = $app->db->queryAllRecords("SELECT * FROM aps_packages WHERE package_url = ''"); if(is_array($incomplete_pkgs) && !empty($incomplete_pkgs)){ foreach($incomplete_pkgs as $incomplete_pkg){ $pkg_url = @file_get_contents($this->interface_pkg_dir.'/'.$incomplete_pkg['path'].'/PKG_URL'); @@ -580,13 +599,16 @@ class ApsCrawler extends ApsBase } } } - } - catch(Exception $e) - { - $app->log($this->log_prefix.$e->getMessage(), LOGLEVEL_ERROR); + } + + catch(Exception $e) + { + $app->log($this->log_prefix.$e->getMessage(), LOGLEVEL_ERROR); $app->error($e->getMessage()); - return false; - } - } + return false; + } + } + } -?> \ No newline at end of file + +?> diff --git a/interface/lib/classes/aps_guicontroller.inc.php b/interface/lib/classes/aps_guicontroller.inc.php index 1e106a1e14ea2575532e0a9e7b12c02907205999..47f5bd25fbf59955c802d8e07bb03bd9bfad294c 100644 --- a/interface/lib/classes/aps_guicontroller.inc.php +++ b/interface/lib/classes/aps_guicontroller.inc.php @@ -27,199 +27,215 @@ OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -require_once('aps_base.inc.php'); +require_once 'aps_base.inc.php'; class ApsGUIController extends ApsBase { - /** - * Constructor - * - * @param $app the application instance (db handle) - */ - public function __construct($app) - { - parent::__construct($app); - } - - /** - * Reads in a package metadata file and registers it's namespaces - * - * @param $filename the file to read - * @return $sxe a SimpleXMLElement handle - */ - private function readInMetaFile($filename) - { - $metadata = file_get_contents($filename); - $metadata = str_replace("xmlns=", "ns=", $metadata); - $sxe = new SimpleXMLElement($metadata); - $namespaces = $sxe->getDocNamespaces(true); - foreach($namespaces as $ns => $url) $sxe->registerXPathNamespace($ns, $url); - - return $sxe; - } - - /** - * Applies a RegEx pattern onto a location path in order to secure it against - * code injections and invalid input - * - * @param $location_unfiltered the file path to secure - * @return $location - */ - private function secureLocation($location_unfiltered) - { - // Filter invalid slashes from string - $location = preg_replace(array('#/+#', '#\.+#', '#\0+#', '#\\\\+#'), - array('/', '', '', '/'), - $location_unfiltered); - - // Remove a beginning or trailing slash - if(substr($location, -1) == '/') $location = substr($location, 0, strlen($location) - 1); - if(substr($location, 0, 1) == '/') $location = substr($location, 1); - - return $location; - } - - /** - * Gets the CustomerID (ClientID) which belongs to a specific domain - * - * @param $domain the domain - * @return $customerid - */ - private function getCustomerIDFromDomain($domain) - { - global $app; - $customerid = 0; - - $customerdata = $app->db->queryOneRecord("SELECT client_id FROM sys_group, web_domain - WHERE web_domain.sys_groupid = sys_group.groupid + /** + * Constructor + * + * @param $app the application instance (db handle) + */ + + + public function __construct($app) + { + parent::__construct($app); + } + + + + /** + * Reads in a package metadata file and registers it's namespaces + * + * @param $filename the file to read + * @return $sxe a SimpleXMLElement handle + */ + private function readInMetaFile($filename) + { + $metadata = file_get_contents($filename); + $metadata = str_replace("xmlns=", "ns=", $metadata); + $sxe = new SimpleXMLElement($metadata); + $namespaces = $sxe->getDocNamespaces(true); + foreach($namespaces as $ns => $url) $sxe->registerXPathNamespace($ns, $url); + + return $sxe; + } + + + + /** + * Applies a RegEx pattern onto a location path in order to secure it against + * code injections and invalid input + * + * @param $location_unfiltered the file path to secure + * @return $location + */ + private function secureLocation($location_unfiltered) + { + // Filter invalid slashes from string + $location = preg_replace(array('#/+#', '#\.+#', '#\0+#', '#\\\\+#'), + array('/', '', '', '/'), + $location_unfiltered); + + // Remove a beginning or trailing slash + if(substr($location, -1) == '/') $location = substr($location, 0, strlen($location) - 1); + if(substr($location, 0, 1) == '/') $location = substr($location, 1); + + return $location; + } + + + + /** + * Gets the CustomerID (ClientID) which belongs to a specific domain + * + * @param $domain the domain + * @return $customerid + */ + private function getCustomerIDFromDomain($domain) + { + global $app; + $customerid = 0; + + $customerdata = $app->db->queryOneRecord("SELECT client_id FROM sys_group, web_domain + WHERE web_domain.sys_groupid = sys_group.groupid AND web_domain.domain = '".$app->db->quote($domain)."';"); - if(!empty($customerdata)) $customerid = $customerdata['client_id']; - - return $customerid; - } - - /** - * Returns the server_id for an already installed instance. Is actually - * just a little helper method to avoid redundant code - * - * @param $instanceid the instance to process - * @return $webserver_id the server_id - */ - private function getInstanceDataForDatalog($instanceid) - { - global $app; - $webserver_id = ''; - - $websrv = $app->db->queryOneRecord("SELECT server_id FROM web_domain - WHERE domain = (SELECT value FROM aps_instances_settings + if(!empty($customerdata)) $customerid = $customerdata['client_id']; + + return $customerid; + } + + + + /** + * Returns the server_id for an already installed instance. Is actually + * just a little helper method to avoid redundant code + * + * @param $instanceid the instance to process + * @return $webserver_id the server_id + */ + private function getInstanceDataForDatalog($instanceid) + { + global $app; + $webserver_id = ''; + + $websrv = $app->db->queryOneRecord("SELECT server_id FROM web_domain + WHERE domain = (SELECT value FROM aps_instances_settings WHERE name = 'main_domain' AND instance_id = ".$app->db->quote($instanceid).");"); - // If $websrv is empty, an error has occured. Domain no longer existing? Settings table damaged? - // Anyhow, remove this instance record because it's not useful at all - if(empty($websrv)) - { - $app->db->query("DELETE FROM aps_instances WHERE id = ".$app->db->quote($instanceid).";"); - $app->db->query("DELETE FROM aps_instances_settings WHERE instance_id = ".$app->db->quote($instanceid).";"); - } - else $webserver_id = $websrv['server_id']; - - return $webserver_id; - } - - /** - * Finds out if there is a newer package version for - * a given (possibly valid) package ID - * - * @param $id the ID to check - * @return $newer_pkg_id the newer package ID - */ - public function getNewestPackageID($id) - { - global $app; - - if(preg_match('/^[0-9]+$/', $id) != 1) return 0; - - $result = $app->db->queryOneRecord("SELECT id, name, - CONCAT(version, '-', CAST(`release` AS CHAR)) AS current_version - FROM aps_packages - WHERE name = (SELECT name FROM aps_packages WHERE id = ".$app->db->quote($id).") + // If $websrv is empty, an error has occured. Domain no longer existing? Settings table damaged? + // Anyhow, remove this instance record because it's not useful at all + if(empty($websrv)) + { + $app->db->query("DELETE FROM aps_instances WHERE id = ".$app->db->quote($instanceid).";"); + $app->db->query("DELETE FROM aps_instances_settings WHERE instance_id = ".$app->db->quote($instanceid).";"); + } + else $webserver_id = $websrv['server_id']; + + return $webserver_id; + } + + + + /** + * Finds out if there is a newer package version for + * a given (possibly valid) package ID + * + * @param $id the ID to check + * @return $newer_pkg_id the newer package ID + */ + public function getNewestPackageID($id) + { + global $app; + + if(preg_match('/^[0-9]+$/', $id) != 1) return 0; + + $result = $app->db->queryOneRecord("SELECT id, name, + CONCAT(version, '-', CAST(`release` AS CHAR)) AS current_version + FROM aps_packages + WHERE name = (SELECT name FROM aps_packages WHERE id = ".$app->db->quote($id).") ORDER BY REPLACE(version, '.', '')+0 DESC, `release` DESC"); - - if(!empty($result) && ($id != $result['id'])) return $result['id']; - - return 0; - } - - /** - * Validates a given package ID - * - * @param $id the ID to check - * @param $is_admin a flag to allow locked IDs too (for admin calls) - * @return boolean - */ - public function isValidPackageID($id, $is_admin = false) - { - global $app; - - if(preg_match('/^[0-9]+$/', $id) != 1) return false; - - $sql_ext = (!$is_admin) ? - 'package_status = '.PACKAGE_ENABLED.' AND' : - '(package_status = '.PACKAGE_ENABLED.' OR package_status = '.PACKAGE_LOCKED.') AND'; - - $result = $app->db->queryOneRecord("SELECT id FROM aps_packages WHERE ".$sql_ext." id = ".$app->db->quote($id).";"); - if(!$result) return false; - - return true; - } - - /** - * Validates a given instance ID - * - * @param $id the ID to check - * @param $client_id the calling client ID - * @param $is_admin a flag to ignore the client ID check for admins - * @return boolean - */ - public function isValidInstanceID($id, $client_id, $is_admin = false) - { - global $app; - - if(preg_match('/^[0-9]+$/', $id) != 1) return false; - - // Only filter if not admin - $sql_ext = (!$is_admin) ? 'customer_id = '.$app->db->quote($client_id).' AND' : ''; - - $result = $app->db->queryOneRecord('SELECT id FROM aps_instances WHERE '.$sql_ext.' id = '.$app->db->quote($id).';'); - if(!$result) return false; - - return true; - } - - /** - * Creates a new database record for the package instance and - * an install task - * - * @param $settings the settings to enter into the DB - * @param $packageid the PackageID - */ - public function createPackageInstance($settings, $packageid) - { + + if(!empty($result) && ($id != $result['id'])) return $result['id']; + + return 0; + } + + /** + * Validates a given package ID + * + * @param $id the ID to check + * @param $is_admin a flag to allow locked IDs too (for admin calls) + * @return boolean + */ + public function isValidPackageID($id, $is_admin = false) + { global $app; - + + if(preg_match('/^[0-9]+$/', $id) != 1) return false; + + $sql_ext = (!$is_admin) ? + 'package_status = '.PACKAGE_ENABLED.' AND' : + '(package_status = '.PACKAGE_ENABLED.' OR package_status = '.PACKAGE_LOCKED.') AND'; + + $result = $app->db->queryOneRecord("SELECT id FROM aps_packages WHERE ".$sql_ext." id = ".$app->db->quote($id).";"); + if(!$result) return false; + + return true; + } + + + + /** + * Validates a given instance ID + * + * @param $id the ID to check + * @param $client_id the calling client ID + * @param $is_admin a flag to ignore the client ID check for admins + * @return boolean + */ + public function isValidInstanceID($id, $client_id, $is_admin = false) + { + global $app; + + if(preg_match('/^[0-9]+$/', $id) != 1) return false; + + // Only filter if not admin + $sql_ext = (!$is_admin) ? 'customer_id = '.$app->db->quote($client_id).' AND' : ''; + + $result = $app->db->queryOneRecord('SELECT id FROM aps_instances WHERE '.$sql_ext.' id = '.$app->db->quote($id).';'); + if(!$result) return false; + + return true; + } + + + + /** + * Creates a new database record for the package instance and + * an install task + * + * @param $settings the settings to enter into the DB + * @param $packageid the PackageID + */ + public function createPackageInstance($settings, $packageid) + { + global $app; + $app->uses('tools_sites'); - + $webserver_id = 0; - $websrv = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain = '".$app->db->quote($settings['main_domain'])."';"); - if(!empty($websrv)) $webserver_id = $websrv['server_id']; - $customerid = $this->getCustomerIDFromDomain($settings['main_domain']); - - if(empty($settings) || empty($webserver_id)) return false; - + $websrv = $app->db->queryOneRecord("SELECT * FROM web_domain WHERE domain = '".$app->db->quote($settings['main_domain'])."';"); + if(!empty($websrv)) $webserver_id = $websrv['server_id']; + $customerid = $this->getCustomerIDFromDomain($settings['main_domain']); + + if(empty($settings) || empty($webserver_id)) return false; + //* Get server config of the web server $app->uses("getconf"); - $web_config = $app->getconf->get_server_config($app->functions->intval($websrv["server_id"]),'web'); - + $web_config = $app->getconf->get_server_config($app->functions->intval($websrv["server_id"]), 'web'); + //* Set PHP mode to php-fcgi and enable suexec in website on apache servers / set PHP mode to PHP-FPM on nginx servers if($web_config['server_type'] == 'apache') { if(($websrv['php'] != 'fast-cgi' || $websrv['suexec'] != 'y') && $websrv['php'] != 'php-fpm') { @@ -231,59 +247,59 @@ class ApsGUIController extends ApsBase $app->db->datalogUpdate('web_domain', "php = 'php-fpm'", 'domain_id', $websrv['domain_id']); } } - - + + //* Create the MySQL database for the application $pkg = $app->db->queryOneRecord('SELECT * FROM aps_packages WHERE id = '.$app->db->quote($packageid).';'); $metafile = $this->interface_pkg_dir.'/'.$pkg['path'].'/APP-META.xml'; $sxe = $this->readInMetaFile($metafile); - + $db_id = parent::getXPathValue($sxe, '//db:id'); if (!empty($db_id)) { $global_config = $app->getconf->get_global_config('sites'); - + $tmp = array(); $tmp['parent_domain_id'] = $websrv['domain_id']; $tmp['sys_groupid'] = $websrv['sys_groupid']; $dbname_prefix = $app->tools_sites->replacePrefix($global_config['dbname_prefix'], $tmp); $dbuser_prefix = $app->tools_sites->replacePrefix($global_config['dbuser_prefix'], $tmp); unset($tmp); - - // get information if the webserver is a db server, too - $web_server = $app->db->queryOneRecord("SELECT server_id,server_name,db_server FROM server WHERE server_id = ".$websrv['server_id']); - if($web_server['db_server'] == 1) { - // create database on "localhost" (webserver) + + // get information if the webserver is a db server, too + $web_server = $app->db->queryOneRecord("SELECT server_id,server_name,db_server FROM server WHERE server_id = ".$websrv['server_id']); + if($web_server['db_server'] == 1) { + // create database on "localhost" (webserver) $mysql_db_server_id = $websrv['server_id']; $mysql_db_host = 'localhost'; $mysql_db_remote_access = 'n'; $mysql_db_remote_ips = ''; - } else { - //* get the default database server of the client - $client = $app->db->queryOneRecord("SELECT default_dbserver FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = ".$websrv['sys_groupid']); - if(is_array($client) && $client['default_dbserver'] > 0 && $client['default_dbserver'] != $websrv['server_id']) { - $mysql_db_server_id = $client['default_dbserver']; - $dbserver_config = $web_config = $app->getconf->get_server_config($app->functions->intval($mysql_db_server_id),'server'); - $mysql_db_host = $dbserver_config['ip_address']; - $mysql_db_remote_access = 'y'; - $webserver_config = $app->getconf->get_server_config($app->functions->intval($websrv['server_id']),'server'); - $mysql_db_remote_ips = $webserver_config['ip_address']; - } else { - /* I left this in place for a fallback that should NEVER! happen. + } else { + //* get the default database server of the client + $client = $app->db->queryOneRecord("SELECT default_dbserver FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = ".$websrv['sys_groupid']); + if(is_array($client) && $client['default_dbserver'] > 0 && $client['default_dbserver'] != $websrv['server_id']) { + $mysql_db_server_id = $client['default_dbserver']; + $dbserver_config = $web_config = $app->getconf->get_server_config($app->functions->intval($mysql_db_server_id), 'server'); + $mysql_db_host = $dbserver_config['ip_address']; + $mysql_db_remote_access = 'y'; + $webserver_config = $app->getconf->get_server_config($app->functions->intval($websrv['server_id']), 'server'); + $mysql_db_remote_ips = $webserver_config['ip_address']; + } else { + /* I left this in place for a fallback that should NEVER! happen. * if we reach this point it means that there is NO default db server for the client * AND the webserver has NO db service enabled. * We have to abort the aps installation here... so I added a return false * although this does not present any error message to the user. */ - return false; - - /*$mysql_db_server_id = $websrv['server_id']; + return false; + + /*$mysql_db_server_id = $websrv['server_id']; $mysql_db_host = 'localhost'; $mysql_db_remote_access = 'n'; $mysql_db_remote_ips = '';*/ - } - } - - //* Find a free db name for the app + } + } + + //* Find a free db name for the app for($n = 1; $n <= 1000; $n++) { $mysql_db_name = ($dbname_prefix != '' ? $dbname_prefix.'aps'.$n : uniqid('aps')); $tmp = $app->db->queryOneRecord("SELECT count(database_id) as number FROM web_database WHERE database_name = '".$app->db->quote($mysql_db_name)."'"); @@ -295,30 +311,30 @@ class ApsGUIController extends ApsBase $tmp = $app->db->queryOneRecord("SELECT count(database_user_id) as number FROM web_database_user WHERE database_user = '".$app->db->quote($mysql_db_user)."'"); if($tmp['number'] == 0) break; } - + $mysql_db_password = $settings['main_database_password']; - + //* Create the mysql database user - $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `database_user`, `database_user_prefix`, `database_password`) + $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `database_user`, `database_user_prefix`, `database_password`) VALUES( ".$websrv['sys_userid'].", ".$websrv['sys_groupid'].", 'riud', '".$websrv['sys_perm_group']."', '', 0, '$mysql_db_user', '".$app->db->quote($dbuser_prefix) . "', PASSWORD('$mysql_db_password'))"; $mysql_db_user_id = $app->db->datalogInsert('web_database_user', $insert_data, 'database_user_id'); - + //* Create the mysql database - $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `parent_domain_id`, `type`, `database_name`, `database_name_prefix`, `database_user_id`, `database_ro_user_id`, `database_charset`, `remote_access`, `remote_ips`, `backup_copies`, `active`, `backup_interval`) + $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `parent_domain_id`, `type`, `database_name`, `database_name_prefix`, `database_user_id`, `database_ro_user_id`, `database_charset`, `remote_access`, `remote_ips`, `backup_copies`, `active`, `backup_interval`) VALUES( ".$websrv['sys_userid'].", ".$websrv['sys_groupid'].", 'riud', '".$websrv['sys_perm_group']."', '', $mysql_db_server_id, ".$websrv['domain_id'].", 'mysql', '$mysql_db_name', '" . $app->db->quote($dbname_prefix) . "', '$mysql_db_user_id', 0, '', '$mysql_db_remote_access', '$mysql_db_remote_ips', ".$websrv['backup_copies'].", 'y', '".$websrv['backup_interval']."')"; $app->db->datalogInsert('web_database', $insert_data, 'database_id'); - + //* Add db details to package settings $settings['main_database_host'] = $mysql_db_host; $settings['main_database_name'] = $mysql_db_name; $settings['main_database_login'] = $mysql_db_user; - + } - + //* Insert new package instance $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `customer_id`, `package_id`, `instance_status`) VALUES (".$websrv['sys_userid'].", ".$websrv['sys_groupid'].", 'riud', '".$websrv['sys_perm_group']."', '', ".$app->db->quote($webserver_id).",".$app->db->quote($customerid).", ".$app->db->quote($packageid).", ".INSTANCE_PENDING.")"; $InstanceID = $app->db->datalogInsert('aps_instances', $insert_data, 'id'); - + //* Insert all package settings if(is_array($settings)) { foreach($settings as $key => $value) { @@ -326,520 +342,530 @@ class ApsGUIController extends ApsBase $app->db->datalogInsert('aps_instances_settings', $insert_data, 'id'); } } - + //* Set package status to install afetr we inserted the settings $app->db->datalogUpdate('aps_instances', "instance_status = ".INSTANCE_INSTALL, 'id', $InstanceID); - } - - /** - * Sets the status of an instance to "should be removed" and creates a - * datalog entry to give the ISPConfig server a real removal advice - * - * @param $instanceid the instance to delete - */ - public function deleteInstance($instanceid) - { - global $app; + } + + + + /** + * Sets the status of an instance to "should be removed" and creates a + * datalog entry to give the ISPConfig server a real removal advice + * + * @param $instanceid the instance to delete + */ + public function deleteInstance($instanceid) + { + global $app; /* $app->db->query("UPDATE aps_instances SET instance_status = ".INSTANCE_REMOVE." WHERE id = ".$instanceid.";"); - + $webserver_id = $this->getInstanceDataForDatalog($instanceid); if($webserver_id == '') return; - + // Create a sys_datalog entry for deletion $datalog = array('Instance_id' => $instanceid, 'server_id' => $webserver_id); $app->db->datalogSave('aps', 'DELETE', 'id', $instanceid, array(), $datalog); */ - + $sql = "SELECT web_database.database_id as database_id, web_database.database_user_id as `database_user_id` FROM aps_instances_settings, web_database WHERE aps_instances_settings.value = web_database.database_name AND aps_instances_settings.name = 'main_database_name' AND aps_instances_settings.instance_id = ".$instanceid." LIMIT 0,1"; $tmp = $app->db->queryOneRecord($sql); if($tmp['database_id'] > 0) $app->db->datalogDelete('web_database', 'database_id', $tmp['database_id']); - - $database_user = $tmp['database_user_id']; - $tmp = $app->db->queryOneRecord("SELECT COUNT(*) as `cnt` FROM `web_database` WHERE `database_user_id` = '" . $app->functions->intval($database_user) . "' OR `database_ro_user_id` = '" . $app->functions->intval($database_user) . "'"); - if($tmp['cnt'] < 1) $app->db->datalogDelete('web_database_user', 'database_user_id', $database_user); - + + $database_user = $tmp['database_user_id']; + $tmp = $app->db->queryOneRecord("SELECT COUNT(*) as `cnt` FROM `web_database` WHERE `database_user_id` = '" . $app->functions->intval($database_user) . "' OR `database_ro_user_id` = '" . $app->functions->intval($database_user) . "'"); + if($tmp['cnt'] < 1) $app->db->datalogDelete('web_database_user', 'database_user_id', $database_user); + $app->db->datalogUpdate('aps_instances', "instance_status = ".INSTANCE_REMOVE, 'id', $instanceid); - } - - /** - * Sets the status of an instance to "installation planned" and creates a - * datalog entry to re-install the package. The existing package is simply overwritten. - * - * @param $instanceid the instance to delete - */ - public function reinstallInstance($instanceid) - { - global $app; - - /* + } + + + + /** + * Sets the status of an instance to "installation planned" and creates a + * datalog entry to re-install the package. The existing package is simply overwritten. + * + * @param $instanceid the instance to delete + */ + public function reinstallInstance($instanceid) + { + global $app; + + /* $app->db->query("UPDATE aps_instances SET instance_status = ".INSTANCE_INSTALL." WHERE id = ".$instanceid.";"); - + $webserver_id = $this->getInstanceDataForDatalog($instanceid); if($webserver_id == '') return; - + // Create a sys_datalog entry for re-installation $datalog = array('instance_id' => $instanceid, 'server_id' => $webserver_id); $app->db->datalogSave('aps', 'INSERT', 'id', $instanceid, array(), $datalog); */ - + $sql = "SELECT web_database.database_id as database_id FROM aps_instances_settings, web_database WHERE aps_instances_settings.value = web_database.database_name AND aps_instances_settings.value = aps_instances_settings.name = 'main_database_name' AND aps_instances_settings.instance_id = ".$instanceid." LIMIT 0,1"; $tmp = $app->db->queryOneRecord($sql); if($tmp['database_id'] > 0) $app->db->datalogDelete('web_database', 'database_id', $tmp['database_id']); - + $app->db->datalogUpdate('aps_instances', "instance_status = ".INSTANCE_INSTALL, 'id', $instanceid); - } - - /** - * Read the settings to be filled when installing - * - * @param $id the internal ID of the package - * @return array - */ - public function getPackageSettings($id) - { - global $app; - - $pkg = $app->db->queryOneRecord('SELECT * FROM aps_packages WHERE id = '.$app->db->quote($id).';'); - - // Load in meta file if existing and register its namespaces - $metafile = $this->interface_pkg_dir.'/'.$pkg['path'].'/APP-META.xml'; - if(!file_exists($metafile)) - return array('error' => 'The metafile for '.$settings['Name'].' couldn\'t be found'); - - $sxe = $this->readInMetaFile($metafile); - - $groupsettings = parent::getXPathValue($sxe, '//settings/group/setting', true); - if(empty($groupsettings)) return array(); - - $settings = array(); - foreach($groupsettings as $setting) - { - $setting_id = strval($setting['id']); - - if($setting['type'] == 'string' || $setting['type'] == 'email' || $setting['type'] == 'integer' - || $setting['type'] == 'float' || $setting['type'] == 'domain-name') - { - $settings[] = array('SettingID' => $setting_id, - 'SettingName' => $setting->name, - 'SettingDescription' => $setting->description, - 'SettingType' => $setting['type'], - 'SettingInputType' => 'string', - 'SettingDefaultValue' => strval($setting['default-value']), - 'SettingRegex' => $setting['regex'], - 'SettingMinLength' => $setting['min-length'], - 'SettingMaxLength' => $setting['max-length']); - } - else if($setting['type'] == 'password') - { - $settings[] = array('SettingID' => $setting_id, - 'SettingName' => $setting->name, - 'SettingDescription' => $setting->description, - 'SettingType' => 'password', - 'SettingInputType' => 'password', - 'SettingDefaultValue' => '', - 'SettingRegex' => $setting['regex'], - 'SettingMinLength' => $setting['min-length'], - 'SettingMaxLength' => $setting['max-length']); - } - else if($setting['type'] == 'boolean') - { - $settings[] = array('SettingID' => $setting_id, - 'SettingName' => $setting->name, - 'SettingDescription' => $setting->description, - 'SettingType' => 'boolean', - 'SettingInputType' => 'checkbox', - 'SettingDefaultValue' => strval($setting['default-value'])); - } - else if($setting['type'] == 'enum') - { - $choices = array(); - foreach($setting->choice as $choice) - { - $choices[] = array('EnumID' => strval($choice['id']), - 'EnumName' => $choice->name); - } - $settings[] = array('SettingID' => $setting_id, - 'SettingName' => $setting->name, - 'SettingDescription' => $setting->description, - 'SettingType' => 'enum', - 'SettingInputType' => 'select', - 'SettingDefaultValue' => strval($setting['default-value']), - 'SettingChoices' => $choices); - } - } - - return $settings; - } - - /** - * Validates the user input according to the settings array and - * delivers errors if occurring - * - * @param $input the user $_POST array - * @param $pkg_details the package details - * @param $settings the package settings array - * @return array in this structure: - * array(2) { - * ["input"]=> ... - * ["errors"]=> ... - * } - */ - public function validateInstallerInput($postinput, $pkg_details, $domains, $settings = array()) - { - global $app; - - $ret = array(); - $input = array(); - $error = array(); - - // Main domain (obligatory) - if(isset($postinput['main_domain'])) - { - if(!in_array($postinput['main_domain'], $domains)) $error[] = $app->lng('error_main_domain'); - else $input['main_domain'] = $postinput['main_domain']; - } - else $error[] = $app->lng('error_main_domain'); - - // Main location (not obligatory but must be supplied) - if(isset($postinput['main_location'])) - { - $temp_errstr = ''; - // It can be empty but if the user did write something, check it - $userinput = false; - if(strlen($postinput['main_location']) > 0) $userinput = true; - - // Filter invalid input slashes (twice!) - $main_location = $this->secureLocation($postinput['main_location']); - $main_location = $this->secureLocation($main_location); - // Only allow digits, words, / and - - $main_location = preg_replace("/[^\d\w\/\-]/i", "", $main_location); - if($userinput && (strlen($main_location) == 0)) $temp_errstr = $app->lng('error_inv_main_location'); - - // Find out document_root and make sure no apps are installed twice to one location - if(in_array($postinput['main_domain'], $domains)) - { - $docroot = $app->db->queryOneRecord("SELECT document_root FROM web_domain + } + + /** + * Read the settings to be filled when installing + * + * @param $id the internal ID of the package + * @return array + */ + public function getPackageSettings($id) + { + global $app; + + $pkg = $app->db->queryOneRecord('SELECT * FROM aps_packages WHERE id = '.$app->db->quote($id).';'); + + // Load in meta file if existing and register its namespaces + $metafile = $this->interface_pkg_dir.'/'.$pkg['path'].'/APP-META.xml'; + if(!file_exists($metafile)) + return array('error' => 'The metafile for '.$settings['Name'].' couldn\'t be found'); + + $sxe = $this->readInMetaFile($metafile); + + $groupsettings = parent::getXPathValue($sxe, '//settings/group/setting', true); + if(empty($groupsettings)) return array(); + + $settings = array(); + foreach($groupsettings as $setting) + { + $setting_id = strval($setting['id']); + + if($setting['type'] == 'string' || $setting['type'] == 'email' || $setting['type'] == 'integer' + || $setting['type'] == 'float' || $setting['type'] == 'domain-name') + { + $settings[] = array('SettingID' => $setting_id, + 'SettingName' => $setting->name, + 'SettingDescription' => $setting->description, + 'SettingType' => $setting['type'], + 'SettingInputType' => 'string', + 'SettingDefaultValue' => strval($setting['default-value']), + 'SettingRegex' => $setting['regex'], + 'SettingMinLength' => $setting['min-length'], + 'SettingMaxLength' => $setting['max-length']); + } + else if($setting['type'] == 'password') + { + $settings[] = array('SettingID' => $setting_id, + 'SettingName' => $setting->name, + 'SettingDescription' => $setting->description, + 'SettingType' => 'password', + 'SettingInputType' => 'password', + 'SettingDefaultValue' => '', + 'SettingRegex' => $setting['regex'], + 'SettingMinLength' => $setting['min-length'], + 'SettingMaxLength' => $setting['max-length']); + } + else if($setting['type'] == 'boolean') + { + $settings[] = array('SettingID' => $setting_id, + 'SettingName' => $setting->name, + 'SettingDescription' => $setting->description, + 'SettingType' => 'boolean', + 'SettingInputType' => 'checkbox', + 'SettingDefaultValue' => strval($setting['default-value'])); + } + else if($setting['type'] == 'enum') + { + $choices = array(); + foreach($setting->choice as $choice) + { + $choices[] = array('EnumID' => strval($choice['id']), + 'EnumName' => $choice->name); + } + $settings[] = array('SettingID' => $setting_id, + 'SettingName' => $setting->name, + 'SettingDescription' => $setting->description, + 'SettingType' => 'enum', + 'SettingInputType' => 'select', + 'SettingDefaultValue' => strval($setting['default-value']), + 'SettingChoices' => $choices); + } + } + + return $settings; + } + + + + /** + * Validates the user input according to the settings array and + * delivers errors if occurring + * + * @param $input the user $_POST array + * @param $pkg_details the package details + * @param $settings the package settings array + * @return array in this structure: + * array(2) { + * ["input"]=> ... + * ["errors"]=> ... + * } + */ + public function validateInstallerInput($postinput, $pkg_details, $domains, $settings = array()) + { + global $app; + + $ret = array(); + $input = array(); + $error = array(); + + // Main domain (obligatory) + if(isset($postinput['main_domain'])) + { + if(!in_array($postinput['main_domain'], $domains)) $error[] = $app->lng('error_main_domain'); + else $input['main_domain'] = $postinput['main_domain']; + } + else $error[] = $app->lng('error_main_domain'); + + // Main location (not obligatory but must be supplied) + if(isset($postinput['main_location'])) + { + $temp_errstr = ''; + // It can be empty but if the user did write something, check it + $userinput = false; + if(strlen($postinput['main_location']) > 0) $userinput = true; + + // Filter invalid input slashes (twice!) + $main_location = $this->secureLocation($postinput['main_location']); + $main_location = $this->secureLocation($main_location); + // Only allow digits, words, / and - + $main_location = preg_replace("/[^\d\w\/\-]/i", "", $main_location); + if($userinput && (strlen($main_location) == 0)) $temp_errstr = $app->lng('error_inv_main_location'); + + // Find out document_root and make sure no apps are installed twice to one location + if(in_array($postinput['main_domain'], $domains)) + { + $docroot = $app->db->queryOneRecord("SELECT document_root FROM web_domain WHERE domain = '".$app->db->quote($postinput['main_domain'])."';"); - $new_path = $docroot['document_root']; - if(substr($new_path, -1) != '/') $new_path .= '/'; - $new_path .= $main_location; - - // Get the $customerid which belongs to the selected domain - $customerid = $this->getCustomerIDFromDomain($postinput['main_domain']); - - // First get all domains used for an install, then their loop them - // and get the corresponding document roots as well as the defined - // locations. If an existing doc_root + location matches with the - // new one -> error - $instance_domains = $app->db->queryAllRecords("SELECT instance_id, s.value AS domain - FROM aps_instances AS i, aps_instances_settings AS s - WHERE i.id = s.instance_id AND s.name = 'main_domain' + $new_path = $docroot['document_root']; + if(substr($new_path, -1) != '/') $new_path .= '/'; + $new_path .= $main_location; + + // Get the $customerid which belongs to the selected domain + $customerid = $this->getCustomerIDFromDomain($postinput['main_domain']); + + // First get all domains used for an install, then their loop them + // and get the corresponding document roots as well as the defined + // locations. If an existing doc_root + location matches with the + // new one -> error + $instance_domains = $app->db->queryAllRecords("SELECT instance_id, s.value AS domain + FROM aps_instances AS i, aps_instances_settings AS s + WHERE i.id = s.instance_id AND s.name = 'main_domain' AND i.customer_id = '".$app->db->quote($customerid)."';"); - for($i = 0; $i < count($instance_domains); $i++) - { - $used_path = ''; - - $doc_root = $app->db->queryOneRecord("SELECT document_root FROM web_domain + for($i = 0; $i < count($instance_domains); $i++) + { + $used_path = ''; + + $doc_root = $app->db->queryOneRecord("SELECT document_root FROM web_domain WHERE domain = '".$app->db->quote($instance_domains[$i]['domain'])."';"); - // Probably the domain settings were changed later, so make sure the doc_root - // is not empty for further validation - if(!empty($doc_root)) - { - $used_path = $doc_root['document_root']; - if(substr($used_path, -1) != '/') $used_path .= '/'; - - $location_for_domain = $app->db->queryOneRecord("SELECT value - FROM aps_instances_settings WHERE name = 'main_location' + // Probably the domain settings were changed later, so make sure the doc_root + // is not empty for further validation + if(!empty($doc_root)) + { + $used_path = $doc_root['document_root']; + if(substr($used_path, -1) != '/') $used_path .= '/'; + + $location_for_domain = $app->db->queryOneRecord("SELECT value + FROM aps_instances_settings WHERE name = 'main_location' AND instance_id = '".$app->db->quote($instance_domains[$i]['instance_id'])."';"); - - // The location might be empty but the DB return must not be false! - if($location_for_domain) $used_path .= $location_for_domain['value']; - - if($new_path == $used_path) - { - $temp_errstr = $app->lng('error_used_location'); - break; - } - } - } - } - else $temp_errstr = $app->lng('error_main_domain'); - - if($temp_errstr == '') $input['main_location'] = htmlspecialchars($main_location); - else $error[] = $temp_errstr; - } - else $error[] = $app->lng('error_no_main_location'); - - // License (the checkbox must be set) - if(isset($pkg_details['License need agree']) - && $pkg_details['License need agree'] == 'true') - { - if(isset($postinput['license']) && $postinput['license'] == 'on') $input['license'] = 'true'; - else $error[] = $app->lng('error_license_agreement'); - } - - // Database - if(isset($pkg_details['Requirements Database']) - && $pkg_details['Requirements Database'] != '') - { - if(isset($postinput['main_database_password'])) - { - if($postinput['main_database_password'] == '') $error[] = $app->lng('error_no_database_pw'); - else if(strlen($postinput['main_database_password']) > 8) - $input['main_database_password'] = htmlspecialchars($postinput['main_database_password']); - else $error[] = $app->lng('error_short_database_pw'); - } - else $error[] = $app->lng('error_no_database_pw'); - } - - // Validate the package settings - foreach($settings as $setting) - { - $temp_errstr = ''; - $setting_id = strval($setting['SettingID']); - - // We assume that every setting must be set - if((isset($postinput[$setting_id]) && ($postinput[$setting_id] != '')) - || ($setting['SettingType'] == 'boolean')) - { - if($setting['SettingType'] == 'string' || $setting['SettingType'] == 'password') - { - if($app->functions->intval($setting['SettingMinLength'], true) != 0 - && strlen($postinput[$setting_id]) < $app->functions->intval($setting['SettingMinLength'], true)) - $temp_errstr = sprintf($app->lng('error_short_value_for'), $setting['setting_name']); - - if($app->functions->intval($setting['SettingMaxLength'], true) != 0 - && strlen($postinput[$setting_id]) > $app->functions->intval($setting['SettingMaxLength'], true)) - $temp_errstr = sprintf($app->lng('error_long_value_for'), $setting['setting_name']); - - if(isset($setting['SettingRegex']) - && !preg_match("/".$setting['SettingRegex']."/", $postinput[$setting_id])) - $temp_errstr = sprintf($app->lng('error_inv_value_for'), $setting['setting_name']); - } - else if($setting['SettingType'] == 'email') - { - if(filter_var(strtolower($postinput[$setting_id]), FILTER_VALIDATE_EMAIL) === false) - $temp_errstr = sprintf($app->lng('error_inv_email_for'), $setting['setting_name']); - } - else if($setting['SettingType'] == 'domain-name') - { - if(!preg_match("^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$", - $postinput[$setting_id])) - $temp_errstr = sprintf($app->lng('error_inv_domain_for'), $setting['setting_name']); - } - else if($setting['SettingType'] == 'integer') - { - if(filter_var($postinput[$setting_id], FILTER_VALIDATE_INT) === false) - $temp_errstr = sprintf($app->lng('error_inv_integer_for'), $setting['setting_name']); - } - else if($setting['SettingType'] == 'float') - { - if(filter_var($postinput[$setting_id], FILTER_VALIDATE_FLOAT) === false) - $temp_errstr = sprintf($app->lng('error_inv_float_for'), $setting['setting_name']); - } - else if($setting['SettingType'] == 'boolean') - { - // If we have a boolean value set, it must be either true or false - if(!isset($postinput[$setting_id])) $postinput[$setting_id] = 'false'; - else if(isset($postinput[$setting_id]) && $postinput[$setting_id] != 'true') - $postinput[$setting_id] = 'true'; - } - else if($setting['SettingType'] == 'enum') - { - $found = false; - for($i = 0; $i < count($setting['SettingChoices']); $i++) - { - if($setting['SettingChoices'][$i]['EnumID'] == $postinput[$setting_id]) - $found = true; - } - if(!$found) $temp_errstr = sprintf($app->lng('error_inv_value_for'), $setting['SettingName']); - } - - if($temp_errstr == '') $input[$setting_id] = $postinput[$setting_id]; - else $error[] = $temp_errstr; - } - else $error[] = sprintf($app->lng('error_no_value_for'), $setting['SettingName']); - } - - $ret['input'] = $input; - $ret['error'] = array_unique($error); - - return $ret; - } - - /** - * Read the metadata of a package and returns some content - * - * @param $id the internal ID of the package - * @return array - */ - public function getPackageDetails($id) - { - global $app; - - $pkg = $app->db->queryOneRecord('SELECT * FROM aps_packages WHERE id = '.$app->db->quote($id).';'); - - // Load in meta file if existing and register its namespaces - $metafile = $this->interface_pkg_dir.'/'.$pkg['path'].'/APP-META.xml'; - if(!file_exists($metafile)) - return array('error' => 'The metafile for '.$pkg['name'].' couldn\'t be found'); - - $metadata = file_get_contents($metafile); - $metadata = str_replace("xmlns=", "ns=", $metadata); - $sxe = new SimpleXMLElement($metadata); - $namespaces = $sxe->getDocNamespaces(true); - foreach($namespaces as $ns => $url) $sxe->registerXPathNamespace($ns, $url); - - $pkg['Summary'] = htmlspecialchars(parent::getXPathValue($sxe, '//summary')); - $pkg['Homepage'] = parent::getXPathValue($sxe, '//homepage'); - $pkg['Description'] = nl2br(htmlspecialchars(trim(parent::getXPathValue($sxe, '//description')))); - $pkg['Config script'] = strtoupper(parent::getXPathValue($sxe, '//configuration-script-language')); - $installed_size = parent::getXPathValue($sxe, '//installed-size'); - $pkg['Installed Size'] = (!empty($installed_size)) ? parent::convertSize((int)$installed_size) : ''; - - // License - $pkg['License need agree'] = parent::getXPathValue($sxe, '//license/@must-accept'); - $pkg['License name'] = parent::getXPathValue($sxe, '//license/text/name'); // might be empty - $pkg['License type'] = 'file'; // default type - $pkg['License content'] = ''; // default license filename on local system - $license_url = parent::getXPathValue($sxe, '//license/text/url'); - if(!empty($license_url)) - { - $pkg['License type'] = 'url'; - $pkg['License content'] = htmlspecialchars($license_url); - } - else - { - $lic = @file_get_contents($this->interface_pkg_dir.'/'.$pkg['path'].'/LICENSE'); - $pkg['License content'] = htmlentities($lic, ENT_QUOTES, 'ISO-8859-1'); - } - - // Languages - $languages = parent::getXPathValue($sxe, '//languages/language', true); - $pkg['Languages'] = (is_array($languages)) ? implode(' ', $languages) : ''; - - // Icon - $icon = parent::getXPathValue($sxe, '//icon/@path'); - if(!empty($icon)) - { - // Using parse_url() to filter malformed URLs - $path = dirname(parse_url($_SERVER['PHP_SELF'], PHP_URL_PATH)).'/'. - basename($this->interface_pkg_dir).'/'.$pkg['path'].'/'.basename((string)$icon); + + // The location might be empty but the DB return must not be false! + if($location_for_domain) $used_path .= $location_for_domain['value']; + + if($new_path == $used_path) + { + $temp_errstr = $app->lng('error_used_location'); + break; + } + } + } + } + else $temp_errstr = $app->lng('error_main_domain'); + + if($temp_errstr == '') $input['main_location'] = htmlspecialchars($main_location); + else $error[] = $temp_errstr; + } + else $error[] = $app->lng('error_no_main_location'); + + // License (the checkbox must be set) + if(isset($pkg_details['License need agree']) + && $pkg_details['License need agree'] == 'true') + { + if(isset($postinput['license']) && $postinput['license'] == 'on') $input['license'] = 'true'; + else $error[] = $app->lng('error_license_agreement'); + } + + // Database + if(isset($pkg_details['Requirements Database']) + && $pkg_details['Requirements Database'] != '') + { + if(isset($postinput['main_database_password'])) + { + if($postinput['main_database_password'] == '') $error[] = $app->lng('error_no_database_pw'); + else if(strlen($postinput['main_database_password']) > 8) + $input['main_database_password'] = htmlspecialchars($postinput['main_database_password']); + else $error[] = $app->lng('error_short_database_pw'); + } + else $error[] = $app->lng('error_no_database_pw'); + } + + // Validate the package settings + foreach($settings as $setting) + { + $temp_errstr = ''; + $setting_id = strval($setting['SettingID']); + + // We assume that every setting must be set + if((isset($postinput[$setting_id]) && ($postinput[$setting_id] != '')) + || ($setting['SettingType'] == 'boolean')) + { + if($setting['SettingType'] == 'string' || $setting['SettingType'] == 'password') + { + if($app->functions->intval($setting['SettingMinLength'], true) != 0 + && strlen($postinput[$setting_id]) < $app->functions->intval($setting['SettingMinLength'], true)) + $temp_errstr = sprintf($app->lng('error_short_value_for'), $setting['setting_name']); + + if($app->functions->intval($setting['SettingMaxLength'], true) != 0 + && strlen($postinput[$setting_id]) > $app->functions->intval($setting['SettingMaxLength'], true)) + $temp_errstr = sprintf($app->lng('error_long_value_for'), $setting['setting_name']); + + if(isset($setting['SettingRegex']) + && !preg_match("/".$setting['SettingRegex']."/", $postinput[$setting_id])) + $temp_errstr = sprintf($app->lng('error_inv_value_for'), $setting['setting_name']); + } + else if($setting['SettingType'] == 'email') + { + if(filter_var(strtolower($postinput[$setting_id]), FILTER_VALIDATE_EMAIL) === false) + $temp_errstr = sprintf($app->lng('error_inv_email_for'), $setting['setting_name']); + } + else if($setting['SettingType'] == 'domain-name') + { + if(!preg_match("^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$", + $postinput[$setting_id])) + $temp_errstr = sprintf($app->lng('error_inv_domain_for'), $setting['setting_name']); + } + else if($setting['SettingType'] == 'integer') + { + if(filter_var($postinput[$setting_id], FILTER_VALIDATE_INT) === false) + $temp_errstr = sprintf($app->lng('error_inv_integer_for'), $setting['setting_name']); + } + else if($setting['SettingType'] == 'float') + { + if(filter_var($postinput[$setting_id], FILTER_VALIDATE_FLOAT) === false) + $temp_errstr = sprintf($app->lng('error_inv_float_for'), $setting['setting_name']); + } + else if($setting['SettingType'] == 'boolean') + { + // If we have a boolean value set, it must be either true or false + if(!isset($postinput[$setting_id])) $postinput[$setting_id] = 'false'; + else if(isset($postinput[$setting_id]) && $postinput[$setting_id] != 'true') + $postinput[$setting_id] = 'true'; + } + else if($setting['SettingType'] == 'enum') + { + $found = false; + for($i = 0; $i < count($setting['SettingChoices']); $i++) + { + if($setting['SettingChoices'][$i]['EnumID'] == $postinput[$setting_id]) + $found = true; + } + if(!$found) $temp_errstr = sprintf($app->lng('error_inv_value_for'), $setting['SettingName']); + } + + if($temp_errstr == '') $input[$setting_id] = $postinput[$setting_id]; + else $error[] = $temp_errstr; + } + else $error[] = sprintf($app->lng('error_no_value_for'), $setting['SettingName']); + } + + $ret['input'] = $input; + $ret['error'] = array_unique($error); + + return $ret; + } + + + + /** + * Read the metadata of a package and returns some content + * + * @param $id the internal ID of the package + * @return array + */ + public function getPackageDetails($id) + { + global $app; + + $pkg = $app->db->queryOneRecord('SELECT * FROM aps_packages WHERE id = '.$app->db->quote($id).';'); + + // Load in meta file if existing and register its namespaces + $metafile = $this->interface_pkg_dir.'/'.$pkg['path'].'/APP-META.xml'; + if(!file_exists($metafile)) + return array('error' => 'The metafile for '.$pkg['name'].' couldn\'t be found'); + + $metadata = file_get_contents($metafile); + $metadata = str_replace("xmlns=", "ns=", $metadata); + $sxe = new SimpleXMLElement($metadata); + $namespaces = $sxe->getDocNamespaces(true); + foreach($namespaces as $ns => $url) $sxe->registerXPathNamespace($ns, $url); + + $pkg['Summary'] = htmlspecialchars(parent::getXPathValue($sxe, '//summary')); + $pkg['Homepage'] = parent::getXPathValue($sxe, '//homepage'); + $pkg['Description'] = nl2br(htmlspecialchars(trim(parent::getXPathValue($sxe, '//description')))); + $pkg['Config script'] = strtoupper(parent::getXPathValue($sxe, '//configuration-script-language')); + $installed_size = parent::getXPathValue($sxe, '//installed-size'); + $pkg['Installed Size'] = (!empty($installed_size)) ? parent::convertSize((int)$installed_size) : ''; + + // License + $pkg['License need agree'] = parent::getXPathValue($sxe, '//license/@must-accept'); + $pkg['License name'] = parent::getXPathValue($sxe, '//license/text/name'); // might be empty + $pkg['License type'] = 'file'; // default type + $pkg['License content'] = ''; // default license filename on local system + $license_url = parent::getXPathValue($sxe, '//license/text/url'); + if(!empty($license_url)) + { + $pkg['License type'] = 'url'; + $pkg['License content'] = htmlspecialchars($license_url); + } + else + { + $lic = @file_get_contents($this->interface_pkg_dir.'/'.$pkg['path'].'/LICENSE'); + $pkg['License content'] = htmlentities($lic, ENT_QUOTES, 'ISO-8859-1'); + } + + // Languages + $languages = parent::getXPathValue($sxe, '//languages/language', true); + $pkg['Languages'] = (is_array($languages)) ? implode(' ', $languages) : ''; + + // Icon + $icon = parent::getXPathValue($sxe, '//icon/@path'); + if(!empty($icon)) + { + // Using parse_url() to filter malformed URLs + $path = dirname(parse_url($_SERVER['PHP_SELF'], PHP_URL_PATH)).'/'. + basename($this->interface_pkg_dir).'/'.$pkg['path'].'/'.basename((string)$icon); // nginx: if $_SERVER['PHP_SELF'] is doubled, remove /sites/aps_packagedetails_show.php from beginning of path $path = preg_replace('@^/sites/aps_packagedetails_show.php(.*)@', '$1', $path); - $pkg['Icon'] = $path; - } - else $pkg['Icon'] = ''; - - // Screenshots - $screenshots = parent::getXPathValue($sxe, '//screenshot', true); - if(!empty($screenshots)) - { - foreach($screenshots as $screen) - { - // Using parse_url() to filter malformed URLs - $path = dirname(parse_url($_SERVER['PHP_SELF'], PHP_URL_PATH)).'/'. - basename($this->interface_pkg_dir).'/'.$pkg['path'].'/'.basename((string)$screen['path']); - // nginx: if $_SERVER['PHP_SELF'] is doubled, remove /sites/aps_packagedetails_show.php from beginning of path + $pkg['Icon'] = $path; + } + else $pkg['Icon'] = ''; + + // Screenshots + $screenshots = parent::getXPathValue($sxe, '//screenshot', true); + if(!empty($screenshots)) + { + foreach($screenshots as $screen) + { + // Using parse_url() to filter malformed URLs + $path = dirname(parse_url($_SERVER['PHP_SELF'], PHP_URL_PATH)).'/'. + basename($this->interface_pkg_dir).'/'.$pkg['path'].'/'.basename((string)$screen['path']); + // nginx: if $_SERVER['PHP_SELF'] is doubled, remove /sites/aps_packagedetails_show.php from beginning of path $path = preg_replace('@^/sites/aps_packagedetails_show.php(.*)@', '$1', $path); - $pkg['Screenshots'][] = array('ScreenPath' => $path, - 'ScreenDescription' => htmlspecialchars(trim((string)$screen->description))); - } - } - else $pkg['Screenshots'] = ''; // if no screenshots are available, set the variable though - - // Changelog - $changelog = parent::getXPathValue($sxe, '//changelog/version', true); - if(!empty($changelog)) - { - foreach($changelog as $change) - { - $entries = array(); - foreach($change->entry as $entry) $entries[] = htmlspecialchars(trim((string)$entry)); - - $pkg['Changelog'][] = array('ChangelogVersion' => (string)$change['version'], - 'ChangelogDescription' => implode('
', $entries)); - } - } - - else $pkg['Changelog'] = ''; - - // PHP extensions - $php_extensions = parent::getXPathValue($sxe, '//php:extension', true); - $php_ext = ''; - if(!empty($php_extensions)) - { - foreach($php_extensions as $extension) - { - if(strtolower($extension) == 'php') continue; - $php_ext .= $extension.' '; - } - } - $pkg['Requirements PHP extensions'] = trim($php_ext); - - // PHP bool options - $pkg['Requirements PHP settings'] = ''; - $php_bool_options = array('allow-url-fopen', 'file-uploads', 'magic-quotes-gpc', - 'register-globals', 'safe-mode', 'short-open-tag'); - foreach($php_bool_options as $option) - { - $value = parent::getXPathValue($sxe, '//php:'.$option); - if(!empty($value)) - { - $option = str_replace('-', '_', $option); - $value = str_replace(array('false', 'true'), array('off', 'on'), $value); - $pkg['Requirements PHP settings'][] = array('PHPSettingName' => $option, - 'PHPSettingValue' => $value); - } - } - - // PHP integer value settings - $memory_limit = parent::getXPathValue($sxe, '//php:memory-limit'); - if(!empty($memory_limit)) - $pkg['Requirements PHP settings'][] = array('PHPSettingName' => 'memory_limit', - 'PHPSettingValue' => parent::convertSize((int)$memory_limit)); - - $max_exec_time = parent::getXPathValue($sxe, '//php:max-execution-time'); - if(!empty($max_exec_time)) - $pkg['Requirements PHP settings'][] = array('PHPSettingName' => 'max-execution-time', - 'PHPSettingValue' => $max_exec_time); - - $post_max_size = parent::getXPathValue($sxe, '//php:post-max-size'); - if(!empty($post_max_size)) - $pkg['Requirements PHP settings'][] = array('PHPSettingName' => 'post_max_size', - 'PHPSettingValue' => parent::convertSize((int)$post_max_size)); - - // Get supported PHP versions - $pkg['Requirements Supported PHP versions'] = ''; - $php_min_version = parent::getXPathValue($sxe, '//php:version/@min'); - $php_max_not_including = parent::getXPathValue($sxe, '//php:version/@max-not-including'); - if(!empty($php_min_version) && !empty($php_max_not_including)) - $pkg['Requirements Supported PHP versions'] = $php_min_version.' - '.$php_max_not_including; - else if(!empty($php_min_version)) - $pkg['Requirements Supported PHP versions'] = '> '.$php_min_version; - else if(!empty($php_max_not_including)) - $pkg['Requirements Supported PHP versions'] = '< '.$php_min_version; - - // Database - $db_id = parent::getXPathValue($sxe, '//db:id'); - $db_server_type = parent::getXPathValue($sxe, '//db:server-type'); - $db_min_version = parent::getXPathValue($sxe, '//db:server-min-version'); - if(!empty($db_id)) - { - $db_server_type = str_replace('postgresql', 'PostgreSQL', $db_server_type); - $db_server_type = str_replace('microsoft:sqlserver', 'MSSQL', $db_server_type); - $db_server_type = str_replace('mysql', 'MySQL', $db_server_type); - - $pkg['Requirements Database'] = $db_server_type; - if(!empty($db_min_version)) $pkg['Requirements Database'] .= ' > '.$db_min_version; - } - else $pkg['Requirements Database'] = ''; - - return $pkg; - } + $pkg['Screenshots'][] = array('ScreenPath' => $path, + 'ScreenDescription' => htmlspecialchars(trim((string)$screen->description))); + } + } + else $pkg['Screenshots'] = ''; // if no screenshots are available, set the variable though + + // Changelog + $changelog = parent::getXPathValue($sxe, '//changelog/version', true); + if(!empty($changelog)) + { + foreach($changelog as $change) + { + $entries = array(); + foreach($change->entry as $entry) $entries[] = htmlspecialchars(trim((string)$entry)); + + $pkg['Changelog'][] = array('ChangelogVersion' => (string)$change['version'], + 'ChangelogDescription' => implode('
', $entries)); + } + } + + else $pkg['Changelog'] = ''; + + // PHP extensions + $php_extensions = parent::getXPathValue($sxe, '//php:extension', true); + $php_ext = ''; + if(!empty($php_extensions)) + { + foreach($php_extensions as $extension) + { + if(strtolower($extension) == 'php') continue; + $php_ext .= $extension.' '; + } + } + $pkg['Requirements PHP extensions'] = trim($php_ext); + + // PHP bool options + $pkg['Requirements PHP settings'] = ''; + $php_bool_options = array('allow-url-fopen', 'file-uploads', 'magic-quotes-gpc', + 'register-globals', 'safe-mode', 'short-open-tag'); + foreach($php_bool_options as $option) + { + $value = parent::getXPathValue($sxe, '//php:'.$option); + if(!empty($value)) + { + $option = str_replace('-', '_', $option); + $value = str_replace(array('false', 'true'), array('off', 'on'), $value); + $pkg['Requirements PHP settings'][] = array('PHPSettingName' => $option, + 'PHPSettingValue' => $value); + } + } + + // PHP integer value settings + $memory_limit = parent::getXPathValue($sxe, '//php:memory-limit'); + if(!empty($memory_limit)) + $pkg['Requirements PHP settings'][] = array('PHPSettingName' => 'memory_limit', + 'PHPSettingValue' => parent::convertSize((int)$memory_limit)); + + $max_exec_time = parent::getXPathValue($sxe, '//php:max-execution-time'); + if(!empty($max_exec_time)) + $pkg['Requirements PHP settings'][] = array('PHPSettingName' => 'max-execution-time', + 'PHPSettingValue' => $max_exec_time); + + $post_max_size = parent::getXPathValue($sxe, '//php:post-max-size'); + if(!empty($post_max_size)) + $pkg['Requirements PHP settings'][] = array('PHPSettingName' => 'post_max_size', + 'PHPSettingValue' => parent::convertSize((int)$post_max_size)); + + // Get supported PHP versions + $pkg['Requirements Supported PHP versions'] = ''; + $php_min_version = parent::getXPathValue($sxe, '//php:version/@min'); + $php_max_not_including = parent::getXPathValue($sxe, '//php:version/@max-not-including'); + if(!empty($php_min_version) && !empty($php_max_not_including)) + $pkg['Requirements Supported PHP versions'] = $php_min_version.' - '.$php_max_not_including; + else if(!empty($php_min_version)) + $pkg['Requirements Supported PHP versions'] = '> '.$php_min_version; + else if(!empty($php_max_not_including)) + $pkg['Requirements Supported PHP versions'] = '< '.$php_min_version; + + // Database + $db_id = parent::getXPathValue($sxe, '//db:id'); + $db_server_type = parent::getXPathValue($sxe, '//db:server-type'); + $db_min_version = parent::getXPathValue($sxe, '//db:server-min-version'); + if(!empty($db_id)) + { + $db_server_type = str_replace('postgresql', 'PostgreSQL', $db_server_type); + $db_server_type = str_replace('microsoft:sqlserver', 'MSSQL', $db_server_type); + $db_server_type = str_replace('mysql', 'MySQL', $db_server_type); + + $pkg['Requirements Database'] = $db_server_type; + if(!empty($db_min_version)) $pkg['Requirements Database'] .= ' > '.$db_min_version; + } + else $pkg['Requirements Database'] = ''; + + return $pkg; + } + } -?> \ No newline at end of file + +?> diff --git a/interface/lib/classes/auth.inc.php b/interface/lib/classes/auth.inc.php index 50d49503e2f224f5fa00e4ce49a7c174822b6853..96e30b4da6cd671ab66569b2c858bb6951e2256e 100644 --- a/interface/lib/classes/auth.inc.php +++ b/interface/lib/classes/auth.inc.php @@ -35,18 +35,18 @@ class auth { { return $_SESSION['s']['user']['userid']; } - + public function is_admin() { if($_SESSION['s']['user']['typ'] == 'admin') { return true; } else { return false; } - } - + } + public function has_clients($userid) { global $app, $conf; - + $userid = $app->functions->intval($userid); $client = $app->db->queryOneRecord("SELECT client.limit_client FROM sys_user, client WHERE sys_user.userid = $userid AND sys_user.client_id = client.client_id"); if($client['limit_client'] > 0) { @@ -55,19 +55,19 @@ class auth { return false; } } - + //** This function adds a given group id to a given user. - public function add_group_to_user($userid,$groupid) { + public function add_group_to_user($userid, $groupid) { global $app; - + $userid = $app->functions->intval($userid); $groupid = $app->functions->intval($groupid); - + if($userid > 0 && $groupid > 0) { $user = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE userid = $userid"); - $groups = explode(',',$user['groups']); - if(!in_array($groupid,$groups)) $groups[] = $groupid; - $groups_string = implode(',',$groups); + $groups = explode(',', $user['groups']); + if(!in_array($groupid, $groups)) $groups[] = $groupid; + $groups_string = implode(',', $groups); $sql = "UPDATE sys_user SET groups = '$groups_string' WHERE userid = $userid"; $app->db->query($sql); return true; @@ -80,33 +80,33 @@ class auth { public function get_client_limit($userid, $limitname) { global $app; - + // simple query cache - if($this->client_limits===null) + if($this->client_limits===null) $this->client_limits = $app->db->queryOneRecord("SELECT client.* FROM sys_user, client WHERE sys_user.userid = $userid AND sys_user.client_id = client.client_id"); - + // isn't client -> no limit if(!$this->client_limits) return -1; - + if(isset($this->client_limits['limit_'.$limitname])) { return $this->client_limits['limit_'.$limitname]; - } - } - + } + } + //** This function removes a given group id from a given user. - public function remove_group_from_user($userid,$groupid) { + public function remove_group_from_user($userid, $groupid) { global $app; - + $userid = $app->functions->intval($userid); $groupid = $app->functions->intval($groupid); - + if($userid > 0 && $groupid > 0) { $user = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE userid = $userid"); - $groups = explode(',',$user['groups']); - $key = array_search($groupid,$groups); + $groups = explode(',', $user['groups']); + $key = array_search($groupid, $groups); unset($groups[$key]); - $groups_string = implode(',',$groups); + $groups_string = implode(',', $groups); $sql = "UPDATE sys_user SET groups = '$groups_string' WHERE userid = $userid"; $app->db->query($sql); return true; @@ -114,35 +114,35 @@ class auth { return false; } } - + public function check_module_permissions($module) { // Check if the current user has the permissions to access this module - if(!stristr($_SESSION["s"]["user"]["modules"],$module)) { + if(!stristr($_SESSION["s"]["user"]["modules"], $module)) { // echo "LOGIN_REDIRECT:/index.php"; header("Location: /index.php"); exit; } } - + public function get_random_password($length = 8) { $base64_alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; $password = ''; for ($n=0;$n<$length;$n++) { - $password.=$base64_alphabet[mt_rand(0,63)]; + $password.=$base64_alphabet[mt_rand(0, 63)]; } return $password; } - + public function crypt_password($cleartext_password) { $salt="$1$"; $base64_alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; for ($n=0;$n<8;$n++) { - $salt.=$base64_alphabet[mt_rand(0,63)]; + $salt.=$base64_alphabet[mt_rand(0, 63)]; } $salt.="$"; - return crypt($cleartext_password,$salt); + return crypt($cleartext_password, $salt); } - + } -?> \ No newline at end of file +?> diff --git a/interface/lib/classes/client_templates.inc.php b/interface/lib/classes/client_templates.inc.php index cdd9ea952ba25ab5291c19c1ea1ea4b428675d29..77f6af5642dd0f823c834d9de80383a314bcf4c2 100644 --- a/interface/lib/classes/client_templates.inc.php +++ b/interface/lib/classes/client_templates.inc.php @@ -1,236 +1,239 @@ pixcept KG * @author (original tools.inc.php) Till Brehm, projektfarm Gmbh * @author (original tools.inc.php) Oliver Vogel www.muv.com */ - + + class client_templates { - /** - * - check for old-style templates and change to new style - * - update assigned templates - */ + + /** + * - check for old-style templates and change to new style + * - update assigned templates + */ function update_client_templates($clientId, $templates = array()) { - global $app, $conf; - - if(!is_array($templates)) return false; - - $new_tpl = array(); - $used_assigned = array(); - $needed_types = array(); - $old_style = true; - foreach($templates as $item) { - $item = trim($item); - if($item == '') continue; - - $tpl_id = 0; - $assigned_id = 0; - if(strpos($item, ':') === false) { - $tpl_id = $item; - } else { - $old_style = false; // has new-style assigns - list($assigned_id, $tpl_id) = explode(':', $item, 2); - if(substr($assigned_id, 0, 1) === 'n') $assigned_id = 0; // newly inserted items - } - if(array_key_exists($tpl_id, $needed_types) == false) $needed_types[$tpl_id] = 0; - $needed_types[$tpl_id]++; - - if($assigned_id > 0) { - $used_assigned[] = $assigned_id; // for comparison with database - } else { - $new_tpl[] = $tpl_id; - } - } - - if($old_style == true) { - // we have to take care of this in an other way - $in_db = $app->db->queryAllRecords('SELECT `assigned_template_id`, `client_template_id` FROM `client_template_assigned` WHERE `client_id` = ' . $clientId); - if(is_array($in_db) && count($in_db) > 0) { - foreach($in_db as $item) { - if(array_key_exists($item['client_template_id'], $needed_types) == false) $needed_types[$item['client_template_id']] = 0; - $needed_types[$item['client_template_id']]--; - } - } - - foreach($needed_types as $tpl_id => $count) { - if($count > 0) { - // add new template to client (includes those from old-style without assigned_template_id) - for($i = $count; $i > 0; $i--) { - $app->db->query('INSERT INTO `client_template_assigned` (`client_id`, `client_template_id`) VALUES (' . $clientId . ', ' . $tpl_id . ')'); - } - } elseif($count < 0) { - // remove old ones - for($i = $count; $i < 0; $i++) { - $app->db->query('DELETE FROM `client_template_assigned` WHERE client_id = ' . $clientId . ' AND client_template_id = ' . $tpl_id . ' LIMIT 1'); - } - } - } - } else { - // we have to take care of this in an other way - $in_db = $app->db->queryAllRecords('SELECT `assigned_template_id`, `client_template_id` FROM `client_template_assigned` WHERE `client_id` = ' . $clientId); - if(is_array($in_db) && count($in_db) > 0) { - // check which templates were removed from this client - foreach($in_db as $item) { - if(in_array($item['assigned_template_id'], $used_assigned) == false) { - // delete this one - $app->db->query('DELETE FROM `client_template_assigned` WHERE `assigned_template_id` = ' . $item['assigned_template_id']); - } - } - } - - if(count($new_tpl) > 0) { - foreach($new_tpl as $item) { - // add new template to client (includes those from old-style without assigned_template_id) - $app->db->query('INSERT INTO `client_template_assigned` (`client_id`, `client_template_id`) VALUES (' . $clientId . ', ' . $item . ')'); - } - } - } - - unset($new_tpl); - unset($in_db); - unset($templates); - unset($used_assigned); - return true; - } - - function apply_client_templates($clientId) { - global $app; - - include('../client/form/client.tform.php'); - - /* + global $app, $conf; + + if(!is_array($templates)) return false; + + $new_tpl = array(); + $used_assigned = array(); + $needed_types = array(); + $old_style = true; + foreach($templates as $item) { + $item = trim($item); + if($item == '') continue; + + $tpl_id = 0; + $assigned_id = 0; + if(strpos($item, ':') === false) { + $tpl_id = $item; + } else { + $old_style = false; // has new-style assigns + list($assigned_id, $tpl_id) = explode(':', $item, 2); + if(substr($assigned_id, 0, 1) === 'n') $assigned_id = 0; // newly inserted items + } + if(array_key_exists($tpl_id, $needed_types) == false) $needed_types[$tpl_id] = 0; + $needed_types[$tpl_id]++; + + if($assigned_id > 0) { + $used_assigned[] = $assigned_id; // for comparison with database + } else { + $new_tpl[] = $tpl_id; + } + } + + if($old_style == true) { + // we have to take care of this in an other way + $in_db = $app->db->queryAllRecords('SELECT `assigned_template_id`, `client_template_id` FROM `client_template_assigned` WHERE `client_id` = ' . $clientId); + if(is_array($in_db) && count($in_db) > 0) { + foreach($in_db as $item) { + if(array_key_exists($item['client_template_id'], $needed_types) == false) $needed_types[$item['client_template_id']] = 0; + $needed_types[$item['client_template_id']]--; + } + } + + foreach($needed_types as $tpl_id => $count) { + if($count > 0) { + // add new template to client (includes those from old-style without assigned_template_id) + for($i = $count; $i > 0; $i--) { + $app->db->query('INSERT INTO `client_template_assigned` (`client_id`, `client_template_id`) VALUES (' . $clientId . ', ' . $tpl_id . ')'); + } + } elseif($count < 0) { + // remove old ones + for($i = $count; $i < 0; $i++) { + $app->db->query('DELETE FROM `client_template_assigned` WHERE client_id = ' . $clientId . ' AND client_template_id = ' . $tpl_id . ' LIMIT 1'); + } + } + } + } else { + // we have to take care of this in an other way + $in_db = $app->db->queryAllRecords('SELECT `assigned_template_id`, `client_template_id` FROM `client_template_assigned` WHERE `client_id` = ' . $clientId); + if(is_array($in_db) && count($in_db) > 0) { + // check which templates were removed from this client + foreach($in_db as $item) { + if(in_array($item['assigned_template_id'], $used_assigned) == false) { + // delete this one + $app->db->query('DELETE FROM `client_template_assigned` WHERE `assigned_template_id` = ' . $item['assigned_template_id']); + } + } + } + + if(count($new_tpl) > 0) { + foreach($new_tpl as $item) { + // add new template to client (includes those from old-style without assigned_template_id) + $app->db->query('INSERT INTO `client_template_assigned` (`client_id`, `client_template_id`) VALUES (' . $clientId . ', ' . $item . ')'); + } + } + } + + unset($new_tpl); + unset($in_db); + unset($templates); + unset($used_assigned); + return true; + } + + function apply_client_templates($clientId) { + global $app; + + include '../client/form/client.tform.php'; + + /* * Get the master-template for the client */ - $sql = "SELECT template_master, template_additional FROM client WHERE client_id = " . $app->functions->intval($clientId); - $record = $app->db->queryOneRecord($sql); - $masterTemplateId = $record['template_master']; - - if($record['template_additional'] != '') { - // we have to call the update_client_templates function - $templates = explode('/', $record['template_additional']); - $this->update_client_templates($clientId, $templates); - $app->db->query('UPDATE `client` SET `template_additional` = \'\' WHERE `client_id` = ' . $app->functions->intval($clientId)); - } - - /* + $sql = "SELECT template_master, template_additional FROM client WHERE client_id = " . $app->functions->intval($clientId); + $record = $app->db->queryOneRecord($sql); + $masterTemplateId = $record['template_master']; + + if($record['template_additional'] != '') { + // we have to call the update_client_templates function + $templates = explode('/', $record['template_additional']); + $this->update_client_templates($clientId, $templates); + $app->db->query('UPDATE `client` SET `template_additional` = \'\' WHERE `client_id` = ' . $app->functions->intval($clientId)); + } + + /* * if the master-Template is custom there is NO changing */ - if ($masterTemplateId > 0){ - $sql = "SELECT * FROM client_template WHERE template_id = " . $app->functions->intval($masterTemplateId); - $limits = $app->db->queryOneRecord($sql); - } else { - // if there is no master template it makes NO SENSE adding sub templates. - // adding subtemplates are stored in client limits, so they would add up - // on every save action for the client -> too high limits! - return; - } - - /* + if ($masterTemplateId > 0){ + $sql = "SELECT * FROM client_template WHERE template_id = " . $app->functions->intval($masterTemplateId); + $limits = $app->db->queryOneRecord($sql); + } else { + // if there is no master template it makes NO SENSE adding sub templates. + // adding subtemplates are stored in client limits, so they would add up + // on every save action for the client -> too high limits! + return; + } + + /* * Process the additional tempaltes here (add them to the limits * if != -1) */ - $addTpl = explode('/', $additionalTemplateStr); - $addTpls = $app->db->queryAllRecords('SELECT `client_template_id` FROM `client_template_assigned` WHERE `client_id` = ' . $app->functions->intval($clientId)); - foreach ($addTpls as $addTpl){ - $item = $addTpl['client_template_id']; - $sql = "SELECT * FROM client_template WHERE template_id = " . $app->functions->intval($item); - $addLimits = $app->db->queryOneRecord($sql); - $app->log('Template processing subtemplate ' . $item . ' for client ' . $clientId, LOGLEVEL_DEBUG); - /* maybe the template is deleted in the meantime */ - if (is_array($addLimits)){ - foreach($addLimits as $k => $v){ - /* we can remove this condition, but it is easier to debug with it (don't add ids and other non-limit values) */ - if (strpos($k, 'limit') !== false or $k == 'ssh_chroot' or $k == 'web_php_options' or $k == 'force_suexec'){ - $app->log('Template processing key ' . $k . ' for client ' . $clientId, LOGLEVEL_DEBUG); - - /* process the numerical limits */ - if (is_numeric($v)){ - /* switch for special cases */ - switch ($k){ - case 'limit_cron_frequency': - if ($v < $limits[$k]) $limits[$k] = $v; - /* silent adjustment of the minimum cron frequency to 1 minute */ - /* maybe this control test should be done via validator definition in tform.php file, but I don't know how */ - if ($limits[$k] < 1) $limits[$k] = 1; - break; - - default: - if ($limits[$k] > -1){ - if ($v == -1){ - $limits[$k] = -1; - } - else { - $limits[$k] += $v; - } - } - } - } - /* process the string limits (CHECKBOXARRAY, SELECT etc.) */ - elseif (is_string($v)){ - switch ($form["tabs"]["limits"]["fields"][$k]['formtype']){ - case 'CHECKBOXARRAY': - if (!isset($limits[$k])){ - $limits[$k] = array(); - } - - $limits_values = $limits[$k]; - if (is_string($limits[$k])){ - $limits_values = explode($form["tabs"]["limits"]["fields"][$k]["separator"],$limits[$k]); - } - $additional_values = explode($form["tabs"]["limits"]["fields"][$k]["separator"],$v); - $app->log('Template processing key ' . $k . ' type CHECKBOXARRAY, lim / add: ' . implode(',', $limits_values) . ' / ' . implode(',', $additional_values) . ' for client ' . $clientId, LOGLEVEL_DEBUG); - /* unification of limits_values (master template) and additional_values (additional template) */ - $limits_unified = array(); - foreach($form["tabs"]["limits"]["fields"][$k]["value"] as $key => $val){ - if (in_array($key,$limits_values) || in_array($key,$additional_values)) $limits_unified[] = $key; - } - $limits[$k] = implode($form["tabs"]["limits"]["fields"][$k]["separator"],$limits_unified); - break; - case 'CHECKBOX': - if($k == 'force_suexec') { - // 'n' is less limited than y - if (!isset($limits[$k])){ - $limits[$k] = 'y'; - } - if($limits[$k] == 'n' || $v == 'n') $limits[$k] = 'n'; - } else { - // 'y' is less limited than n - if (!isset($limits[$k])){ - $limits[$k] = 'n'; - } - if($limits[$k] == 'y' || $v == 'y') $limits[$k] = 'y'; - } - break; - case 'SELECT': - $limit_values = array_keys($form["tabs"]["limits"]["fields"][$k]["value"]); - /* choose the lower index of the two SELECT items */ - $limits[$k] = $limit_values[min(array_search($limits[$k], $limit_values), array_search($v, $limit_values))]; - break; - } - } - } - } - } - } - - /* + $addTpl = explode('/', $additionalTemplateStr); + $addTpls = $app->db->queryAllRecords('SELECT `client_template_id` FROM `client_template_assigned` WHERE `client_id` = ' . $app->functions->intval($clientId)); + foreach ($addTpls as $addTpl){ + $item = $addTpl['client_template_id']; + $sql = "SELECT * FROM client_template WHERE template_id = " . $app->functions->intval($item); + $addLimits = $app->db->queryOneRecord($sql); + $app->log('Template processing subtemplate ' . $item . ' for client ' . $clientId, LOGLEVEL_DEBUG); + /* maybe the template is deleted in the meantime */ + if (is_array($addLimits)){ + foreach($addLimits as $k => $v){ + /* we can remove this condition, but it is easier to debug with it (don't add ids and other non-limit values) */ + if (strpos($k, 'limit') !== false or $k == 'ssh_chroot' or $k == 'web_php_options' or $k == 'force_suexec'){ + $app->log('Template processing key ' . $k . ' for client ' . $clientId, LOGLEVEL_DEBUG); + + /* process the numerical limits */ + if (is_numeric($v)){ + /* switch for special cases */ + switch ($k){ + case 'limit_cron_frequency': + if ($v < $limits[$k]) $limits[$k] = $v; + /* silent adjustment of the minimum cron frequency to 1 minute */ + /* maybe this control test should be done via validator definition in tform.php file, but I don't know how */ + if ($limits[$k] < 1) $limits[$k] = 1; + break; + + default: + if ($limits[$k] > -1){ + if ($v == -1){ + $limits[$k] = -1; + } + else { + $limits[$k] += $v; + } + } + } + } + /* process the string limits (CHECKBOXARRAY, SELECT etc.) */ + elseif (is_string($v)){ + switch ($form["tabs"]["limits"]["fields"][$k]['formtype']){ + case 'CHECKBOXARRAY': + if (!isset($limits[$k])){ + $limits[$k] = array(); + } + + $limits_values = $limits[$k]; + if (is_string($limits[$k])){ + $limits_values = explode($form["tabs"]["limits"]["fields"][$k]["separator"], $limits[$k]); + } + $additional_values = explode($form["tabs"]["limits"]["fields"][$k]["separator"], $v); + $app->log('Template processing key ' . $k . ' type CHECKBOXARRAY, lim / add: ' . implode(',', $limits_values) . ' / ' . implode(',', $additional_values) . ' for client ' . $clientId, LOGLEVEL_DEBUG); + /* unification of limits_values (master template) and additional_values (additional template) */ + $limits_unified = array(); + foreach($form["tabs"]["limits"]["fields"][$k]["value"] as $key => $val){ + if (in_array($key, $limits_values) || in_array($key, $additional_values)) $limits_unified[] = $key; + } + $limits[$k] = implode($form["tabs"]["limits"]["fields"][$k]["separator"], $limits_unified); + break; + case 'CHECKBOX': + if($k == 'force_suexec') { + // 'n' is less limited than y + if (!isset($limits[$k])){ + $limits[$k] = 'y'; + } + if($limits[$k] == 'n' || $v == 'n') $limits[$k] = 'n'; + } else { + // 'y' is less limited than n + if (!isset($limits[$k])){ + $limits[$k] = 'n'; + } + if($limits[$k] == 'y' || $v == 'y') $limits[$k] = 'y'; + } + break; + case 'SELECT': + $limit_values = array_keys($form["tabs"]["limits"]["fields"][$k]["value"]); + /* choose the lower index of the two SELECT items */ + $limits[$k] = $limit_values[min(array_search($limits[$k], $limit_values), array_search($v, $limit_values))]; + break; + } + } + } + } + } + } + + /* * Write all back to the database */ - $update = ''; - foreach($limits as $k => $v){ - if ((strpos($k, 'limit') !== false or $k == 'ssh_chroot' or $k == 'web_php_options' or $k == 'force_suexec') && !is_array($v)){ - if ($update != '') $update .= ', '; - $update .= '`' . $k . "`='" . $v . "'"; - } - } - $app->log('Template processed for client ' . $clientId . ', update string: ' . $update, LOGLEVEL_DEBUG); - if($update != '') { - $sql = 'UPDATE client SET ' . $update . " WHERE client_id = " . $app->functions->intval($clientId); - $app->db->query($sql); - } - unset($form); - } -} \ No newline at end of file + $update = ''; + foreach($limits as $k => $v){ + if ((strpos($k, 'limit') !== false or $k == 'ssh_chroot' or $k == 'web_php_options' or $k == 'force_suexec') && !is_array($v)){ + if ($update != '') $update .= ', '; + $update .= '`' . $k . "`='" . $v . "'"; + } + } + $app->log('Template processed for client ' . $clientId . ', update string: ' . $update, LOGLEVEL_DEBUG); + if($update != '') { + $sql = 'UPDATE client SET ' . $update . " WHERE client_id = " . $app->functions->intval($clientId); + $app->db->query($sql); + } + unset($form); + } + +} diff --git a/interface/lib/classes/cmstree.inc.php b/interface/lib/classes/cmstree.inc.php index d83fb297e50c81dbfce1826aa3a52b35881fc5b9..ead780ebf26c65fd01d97a10a5f0f640ca54e9be 100644 --- a/interface/lib/classes/cmstree.inc.php +++ b/interface/lib/classes/cmstree.inc.php @@ -48,13 +48,13 @@ class cmstree // - icon :icon im node-tree, optional // - modul :modul des Eintrages, noch nicht verwendet // - doc_id :id des zugeh�rigen Dokumentes - + public function node_list() { global $app; - + $nodes = $app->db->queryAllRecords('SELECT * FROM media_cat order by sort, name'); - + $optionlist = array(); $my0 = new nodetree(); @@ -74,11 +74,11 @@ class cmstree $$ordner->childs[] = &$$id; } } - - $this->ptree($my0, 0, $optionlist); + + $this->ptree($my0, 0, $optionlist); return is_array($nodes) ? $optionlist : false; } - + private function ptree($myobj, $tiefe, &$optionlist){ global $_SESSION; $tiefe += 1; @@ -87,7 +87,7 @@ class cmstree if(is_array($myobj->childs) and ($_SESSION['s']['cat_open'][$id] == 1 or $tiefe <= 1)) { foreach($myobj->childs as $val) { // kategorie => str_repeat('-  ',$tiefe) . $val->btext, - + // Ergebnisse Formatieren /* if($tiefe == 0) { @@ -104,7 +104,7 @@ class cmstree } else { $kategorie = "
"; } - + $optionlist[] = array( media_cat => $kategorie, media_cat_id => $val->id, depth => $tiefe); @@ -114,4 +114,4 @@ class cmstree } } -?> \ No newline at end of file +?> diff --git a/interface/lib/classes/custom_datasource.inc.php b/interface/lib/classes/custom_datasource.inc.php index 44fee19d9171cd26b846ccbcf36c852f962d91a6..fda355cfcd8076b3af89b38eccc43febcee39b20 100644 --- a/interface/lib/classes/custom_datasource.inc.php +++ b/interface/lib/classes/custom_datasource.inc.php @@ -29,7 +29,7 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class custom_datasource { - + function master_templates($field, $record) { global $app, $conf; $records = $app->db->queryAllRecords("SELECT template_id,template_name FROM client_template WHERE template_type ='m'"); @@ -40,10 +40,10 @@ class custom_datasource { } return $records_new; } - + function dns_servers($field, $record) { global $app, $conf; - + if($_SESSION["s"]["user"]["typ"] == 'user') { // Get the limits of the client $client_group_id = $_SESSION["s"]["user"]["default_group"]; @@ -62,10 +62,10 @@ class custom_datasource { } return $records_new; } - + function slave_dns_servers($field, $record) { global $app, $conf; - + if($_SESSION["s"]["user"]["typ"] == 'user') { // Get the limits of the client $client_group_id = $_SESSION["s"]["user"]["default_group"]; @@ -84,10 +84,10 @@ class custom_datasource { } return $records_new; } - + function webdav_domains($field, $record) { global $app, $conf; - + $servers = $app->db->queryAllRecords("SELECT * FROM server WHERE active = 1 AND mirror_server_id = 0"); $server_ids = array(); $app->uses('getconf'); @@ -100,7 +100,7 @@ class custom_datasource { if(count($server_ids) == 0) return array(); $server_ids = implode(',', $server_ids); $records = $app->db->queryAllRecords("SELECT web_domain.domain_id, CONCAT(web_domain.domain, ' :: ', server.server_name) AS parent_domain FROM web_domain, server WHERE web_domain.type = 'vhost' AND web_domain.server_id IN (".$server_ids.") AND web_domain.server_id = server.server_id AND ".$app->tform->getAuthSQL('r', 'web_domain')." ORDER BY web_domain.domain"); - + $records_new = array(); if(is_array($records)) { foreach($records as $rec) { @@ -110,40 +110,40 @@ class custom_datasource { } return $records_new; } - - + + function client_servers($field, $record) { global $app, $conf; - + $server_type = $field['name']; - + switch($server_type) { - case 'default_mailserver': - $field = 'mail_server'; + case 'default_mailserver': + $field = 'mail_server'; break; - case 'default_webserver': - $field = 'web_server'; + case 'default_webserver': + $field = 'web_server'; break; - case 'default_dnsserver': - $field = 'dns_server'; + case 'default_dnsserver': + $field = 'dns_server'; break; - case 'default_slave_dnsserver': - $field = 'dns_server'; + case 'default_slave_dnsserver': + $field = 'dns_server'; break; - case 'default_fileserver': - $field = 'file_server'; + case 'default_fileserver': + $field = 'file_server'; break; - case 'default_dbserver': - $field = 'db_server'; + case 'default_dbserver': + $field = 'db_server'; break; - case 'default_vserverserver': - $field = 'vserver_server'; + case 'default_vserverserver': + $field = 'vserver_server'; break; - default: - $field = 'web_server'; + default: + $field = 'web_server'; break; } - + if($_SESSION["s"]["user"]["typ"] == 'user') { // Get the limits of the client $client_group_id = $_SESSION["s"]["user"]["default_group"]; @@ -154,14 +154,14 @@ class custom_datasource { $sql = "SELECT server_id,server_name FROM server WHERE server_id = ".$client['server_id']; } else { //* Not able to find the clients defaults, use this as fallback and add a warning message to the log - $app->log('Unable to find default server for client in custom_datasource.inc.php',1); + $app->log('Unable to find default server for client in custom_datasource.inc.php', 1); $sql = "SELECT server_id,server_name FROM server WHERE $field = 1 ORDER BY server_name"; } } else { //* The logged in user is admin, so we show him all available servers of a specific type. $sql = "SELECT server_id,server_name FROM server WHERE $field = 1 ORDER BY server_name"; } - + $records = $app->db->queryAllRecords($sql); $records_new = array(); if(is_array($records)) { @@ -172,9 +172,9 @@ class custom_datasource { } return $records_new; } - - + + } -?> \ No newline at end of file +?> diff --git a/interface/lib/classes/db_firebird.inc.php b/interface/lib/classes/db_firebird.inc.php index 883e7ba0e87b9429f7842b69fa06d620a731f944..fda4ef8e64081c954c12a0fa5cb000e2c0242270 100644 --- a/interface/lib/classes/db_firebird.inc.php +++ b/interface/lib/classes/db_firebird.inc.php @@ -29,17 +29,17 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class db { - var $dbHost = ""; // hostname of the MySQL server - var $dbName = ""; // logical database name on that server - var $dbUser = ""; // database authorized user - var $dbPass = ""; // user's password - var $linkId = 0; // last result of mysql_connect() - var $queryId = 0; // last result of mysql_query() - var $record = array(); // last record fetched - var $autoCommit = 1; // Autocommit Transactions - var $currentRow; // current row number - var $errorNumber = 0; // last error number - var $errorMessage = ""; // last error message + var $dbHost = ""; // hostname of the MySQL server + var $dbName = ""; // logical database name on that server + var $dbUser = ""; // database authorized user + var $dbPass = ""; // user's password + var $linkId = 0; // last result of mysql_connect() + var $queryId = 0; // last result of mysql_query() + var $record = array(); // last record fetched + var $autoCommit = 1; // Autocommit Transactions + var $currentRow; // current row number + var $errorNumber = 0; // last error number + var $errorMessage = ""; // last error message var $errorLocation = "";// last error location var $show_error_messages = false; var $transID; @@ -47,7 +47,7 @@ class db { // constructor function __construct() { - + global $conf; $this->dbHost = $conf["db_host"]; $this->dbName = $conf["db_database"]; @@ -55,9 +55,10 @@ class db { $this->dbPass = $conf["db_password"]; $this->connect(); } + function __destruct() { $this->closeConn(); - } + } // error handler function updateError($location) @@ -67,7 +68,7 @@ class db { $this->errorLocation = $location; if($this->errorNumber && $this->show_error_messages) { - echo('
'.$this->errorLocation.'
'.$this->errorMessage); + echo '
'.$this->errorLocation.'
'.$this->errorMessage; flush(); } } @@ -76,7 +77,7 @@ class db { { if($this->linkId == 0) { - $this->linkId = ibase_connect( $this->dbHost.":".$this->dbName , $this->dbUser, $this->dbPass,'ISO8859_1',0,3 ); + $this->linkId = ibase_connect( $this->dbHost.":".$this->dbName , $this->dbUser, $this->dbPass, 'ISO8859_1', 0, 3 ); if(!$this->linkId) { $this->updateError('DB::connect()
ibase_pconnect'); @@ -91,16 +92,16 @@ class db { if(!$this->connect()) { return false; } - + if($this->autoCommit == 1) { //$transID = ibase_trans(); - $this->queryId = @ibase_query($this->linkId,$queryString); + $this->queryId = @ibase_query($this->linkId, $queryString); //ibase_commit(); } else { - $this->queryId = @ibase_query($this->linkId,$queryString); + $this->queryId = @ibase_query($this->linkId, $queryString); } - - + + $this->updateError('DB::query('.$queryString.')
ibase_query'); if(!$this->queryId) { return false; @@ -141,7 +142,7 @@ class db { // returns the next record in an array function nextRecord() { - $this->record = ibase_fetch_assoc($this->queryId); + $this->record = ibase_fetch_assoc($this->queryId); $this->updateError('DB::nextRecord()
ibase_fetch_assoc'); if(!$this->record || !is_array($this->record)) { @@ -156,32 +157,32 @@ class db { { return false; } - + // returns mySQL insert id function insertID() { return false; } - - // Check der variablen + + // Check der variablen // deprecated, now use quote - function check($formfield) - { - return $this->quote($formfield); - } - + function check($formfield) + { + return $this->quote($formfield); + } + // Check der variablen - function quote($formfield) - { - return str_replace("'","''",$formfield); - } - + function quote($formfield) + { + return str_replace("'", "''", $formfield); + } + // Check der variablen - function unquote($formfield) - { - return str_replace("''","'",$formfield); - } - + function unquote($formfield) + { + return str_replace("''", "'", $formfield); + } + function toLower($record) { if(is_array($record)) { foreach($record as $key => $val) { @@ -189,76 +190,76 @@ class db { $out[$key] = $val; } } - return $out; + return $out; + } + + + function insert($tablename, $form, $debug = 0) + { + if(is_array($form)){ + foreach($form as $key => $value) + { + $sql_key .= "$key, "; + $sql_value .= "'".$this->quote($value)."', "; + } + $sql_key = substr($sql_key, 0, strlen($sql_key) - 2); + $sql_value = substr($sql_value, 0, strlen($sql_value) - 2); + + $sql = "INSERT INTO $tablename (" . $sql_key . ") VALUES (" . $sql_value .")"; + + if($debug == 1) echo "SQL-Statement: ".$sql."

"; + $this->query($sql); + if($debug == 1) echo "mySQL Error Message: ".$this->errorMessage; + } + } + + function update($tablename, $form, $bedingung, $debug = 0) + { + + if(is_array($form)){ + foreach($form as $key => $value) + { + $insql .= "$key = '".$this->quote($value)."', "; + } + $insql = substr($insql, 0, strlen($insql) - 2); + $sql = "UPDATE $tablename SET " . $insql . " WHERE $bedingung"; + if($debug == 1) echo "SQL-Statement: ".$sql."

"; + $this->query($sql); + if($debug == 1) echo "mySQL Error Message: ".$this->errorMessage; + } + } + + function closeConn() { + ibase_close($this->linkId); + } + + function freeResult() { + //ibase_free_result(); + } + + function delete() { + } - - - function insert($tablename,$form,$debug = 0) - { - if(is_array($form)){ - foreach($form as $key => $value) - { - $sql_key .= "$key, "; - $sql_value .= "'".$this->quote($value)."', "; - } - $sql_key = substr($sql_key,0,strlen($sql_key) - 2); - $sql_value = substr($sql_value,0,strlen($sql_value) - 2); - - $sql = "INSERT INTO $tablename (" . $sql_key . ") VALUES (" . $sql_value .")"; - - if($debug == 1) echo "SQL-Statement: ".$sql."

"; - $this->query($sql); - if($debug == 1) echo "mySQL Error Message: ".$this->errorMessage; - } - } - - function update($tablename,$form,$bedingung,$debug = 0) - { - - if(is_array($form)){ - foreach($form as $key => $value) - { - $insql .= "$key = '".$this->quote($value)."', "; - } - $insql = substr($insql,0,strlen($insql) - 2); - $sql = "UPDATE $tablename SET " . $insql . " WHERE $bedingung"; - if($debug == 1) echo "SQL-Statement: ".$sql."

"; - $this->query($sql); - if($debug == 1) echo "mySQL Error Message: ".$this->errorMessage; - } - } - - function closeConn() { - ibase_close($this->linkId); - } - - function freeResult() { - //ibase_free_result(); - } - - function delete() { - - } - - function trans($action,$transID = null) { - //action = begin, commit oder rollback - - if($action == 'begin') { - $this->transID = ibase_trans($this->linkId); + + function trans($action, $transID = null) { + //action = begin, commit oder rollback + + if($action == 'begin') { + $this->transID = ibase_trans($this->linkId); return $this->transID; - } - + } + if($action == 'commit' and !empty($this->transID)) { - ibase_commit($this->linkId,$this->transID); + ibase_commit($this->linkId, $this->transID); } - + if($action == 'rollback') { - ibase_rollback($this->linkId,$this->transID); + ibase_rollback($this->linkId, $this->transID); } - - } - - /* + + } + + /* $columns = array(action => add | alter | drop name => Spaltenname name_new => neuer Spaltenname, nur bei 'alter' belegt @@ -268,38 +269,38 @@ class db { notNull => true | false autoInc => true | false option => unique | primary | index) - - + + */ - - function createTable($table_name,$columns) { - $index = ""; - $sql = "CREATE TABLE $table_name ("; - foreach($columns as $col){ - $sql .= $col["name"]." ".$this->mapType($col["type"],$col["typeValue"])." "; - - if($col["defaultValue"] != "") $sql .= "DEFAULT '".$col["defaultValue"]."' "; - if($col["notNull"] == true) { - $sql .= "NOT NULL "; - } else { - $sql .= "NULL "; - } - if($col["autoInc"] == true) $sql .= "auto_increment "; - $sql.= ","; - // key Definitionen - if($col["option"] == "primary") $index .= "PRIMARY KEY (".$col["name"]."),"; - if($col["option"] == "index") $index .= "INDEX (".$col["name"]."),"; - if($col["option"] == "unique") $index .= "UNIQUE (".$col["name"]."),"; - } - $sql .= $index; - $sql = substr($sql,0,-1); - $sql .= ")"; - - $this->query($sql); - return true; - } - - /* + + function createTable($table_name, $columns) { + $index = ""; + $sql = "CREATE TABLE $table_name ("; + foreach($columns as $col){ + $sql .= $col["name"]." ".$this->mapType($col["type"], $col["typeValue"])." "; + + if($col["defaultValue"] != "") $sql .= "DEFAULT '".$col["defaultValue"]."' "; + if($col["notNull"] == true) { + $sql .= "NOT NULL "; + } else { + $sql .= "NULL "; + } + if($col["autoInc"] == true) $sql .= "auto_increment "; + $sql.= ","; + // key Definitionen + if($col["option"] == "primary") $index .= "PRIMARY KEY (".$col["name"]."),"; + if($col["option"] == "index") $index .= "INDEX (".$col["name"]."),"; + if($col["option"] == "unique") $index .= "UNIQUE (".$col["name"]."),"; + } + $sql .= $index; + $sql = substr($sql, 0, -1); + $sql .= ")"; + + $this->query($sql); + return true; + } + + /* $columns = array(action => add | alter | drop name => Spaltenname name_new => neuer Spaltenname, nur bei 'alter' belegt @@ -309,26 +310,26 @@ class db { notNull => true | false autoInc => true | false option => unique | primary | index) - - + + */ - function alterTable($table_name,$columns) { - return false; - } - - function dropTable($table_name) { - $this->check($table_name); - $sql = "DROP TABLE '". $table_name."'"; - return $this->query($sql); - } - - // gibt Array mit Tabellennamen zurück - function getTables($database_name) { - return false; - } - - // gibt Feldinformationen zur Tabelle zurück - /* + function alterTable($table_name, $columns) { + return false; + } + + function dropTable($table_name) { + $this->check($table_name); + $sql = "DROP TABLE '". $table_name."'"; + return $this->query($sql); + } + + // gibt Array mit Tabellennamen zurück + function getTables($database_name) { + return false; + } + + // gibt Feldinformationen zur Tabelle zurück + /* $columns = array(action => add | alter | drop name => Spaltenname name_new => neuer Spaltenname, nur bei 'alter' belegt @@ -338,46 +339,46 @@ class db { notNull => true | false autoInc => true | false option => unique | primary | index) - - + + */ - - function tableInfo($table_name) { - return false; - } - - function mapType($metaType,$typeValue) { - global $go_api; - $metaType = strtolower($metaType); - switch ($metaType) { - case 'int16': - return 'smallint'; - break; - case 'int32': - return 'int'; - break; - case 'int64': - return 'bigint'; - break; - case 'double': - return 'double'; - break; - case 'char': - return 'char'; - break; - case 'varchar': - if($typeValue < 1) $go_api->errorMessage("Datenbank Fehler: Für diesen Datentyp ist eine Längenangabe notwendig."); - return 'varchar('.$typeValue.')'; - break; - case 'text': - return 'text'; - break; - case 'blob': - return 'blob'; - break; - } - } - + + function tableInfo($table_name) { + return false; + } + + function mapType($metaType, $typeValue) { + global $go_api; + $metaType = strtolower($metaType); + switch ($metaType) { + case 'int16': + return 'smallint'; + break; + case 'int32': + return 'int'; + break; + case 'int64': + return 'bigint'; + break; + case 'double': + return 'double'; + break; + case 'char': + return 'char'; + break; + case 'varchar': + if($typeValue < 1) $go_api->errorMessage("Datenbank Fehler: Für diesen Datentyp ist eine Längenangabe notwendig."); + return 'varchar('.$typeValue.')'; + break; + case 'text': + return 'text'; + break; + case 'blob': + return 'blob'; + break; + } + } + } ?> diff --git a/interface/lib/classes/db_mysql.inc.php b/interface/lib/classes/db_mysql.inc.php index 46729988e6a30223d66fd60e5fac1234e9c3fddd..1636cab5d38700c4370fca09f083e713d0cec0e2 100644 --- a/interface/lib/classes/db_mysql.inc.php +++ b/interface/lib/classes/db_mysql.inc.php @@ -29,64 +29,64 @@ class db extends mysqli { - private $dbHost = ''; // hostname of the MySQL server - private $dbName = ''; // logical database name on that server - private $dbUser = ''; // database authorized user - private $dbPass = ''; // user's password - private $dbCharset = 'utf8';// Database charset - private $dbNewLink = false; // Return a new linkID when connect is called again - private $dbClientFlags = 0; // MySQL Client falgs - private $linkId = 0; // last result of mysqli_connect() - private $queryId = 0; // last result of mysqli_query() - private $record = array(); // last record fetched - private $autoCommit = 1; // Autocommit Transactions - private $currentRow; // current row number - private $errorNumber = 0; // last error number - public $errorMessage = ''; // last error message - private $errorLocation = '';// last error location - public $show_error_messages = false; // false in server, true in interface - private $isConnected = false; // needed to know if we have a valid mysqli object from the constructor - - // constructor - public function __construct($prefix = '') { - global $conf; - if($prefix != '') $prefix .= '_'; - $this->dbHost = $conf[$prefix.'db_host']; - $this->dbName = $conf[$prefix.'db_database']; - $this->dbUser = $conf[$prefix.'db_user']; - $this->dbPass = $conf[$prefix.'db_password']; - $this->dbCharset = $conf[$prefix.'db_charset']; - $this->dbNewLink = $conf[$prefix.'db_new_link']; - $this->dbClientFlags = $conf[$prefix.'db_client_flags']; - parent::__construct($conf[$prefix.'db_host'], $conf[$prefix.'db_user'],$conf[$prefix.'db_password'],$conf[$prefix.'db_database']); - $try = 0; - //while(!is_null($this->connect_error) && $try < 5) { - while(mysqli_connect_error() && $try < 5) { - if($try > 0) sleep(1); - - $try++; - $this->updateError('DB::__construct'); - - parent::__construct($conf[$prefix.'db_host'], $conf[$prefix.'db_user'],$conf[$prefix.'db_password'],$conf[$prefix.'db_database']); - } - - //if(is_null($this->connect_error)) $this->isConnected = true; - //else return false; - if(!mysqli_connect_error()) $this->isConnected = true; - else return false; - - $this->setCharacterEncoding(); - } - - public function __destruct() { - $this->close(); // helps avoid memory leaks, and persitent connections that don't go away. - } - - // error handler - public function updateError($location) { - global $app, $conf; + private $dbHost = ''; // hostname of the MySQL server + private $dbName = ''; // logical database name on that server + private $dbUser = ''; // database authorized user + private $dbPass = ''; // user's password + private $dbCharset = 'utf8';// Database charset + private $dbNewLink = false; // Return a new linkID when connect is called again + private $dbClientFlags = 0; // MySQL Client falgs + private $linkId = 0; // last result of mysqli_connect() + private $queryId = 0; // last result of mysqli_query() + private $record = array(); // last record fetched + private $autoCommit = 1; // Autocommit Transactions + private $currentRow; // current row number + private $errorNumber = 0; // last error number + public $errorMessage = ''; // last error message + private $errorLocation = '';// last error location + public $show_error_messages = false; // false in server, true in interface + private $isConnected = false; // needed to know if we have a valid mysqli object from the constructor + + // constructor + public function __construct($prefix = '') { + global $conf; + if($prefix != '') $prefix .= '_'; + $this->dbHost = $conf[$prefix.'db_host']; + $this->dbName = $conf[$prefix.'db_database']; + $this->dbUser = $conf[$prefix.'db_user']; + $this->dbPass = $conf[$prefix.'db_password']; + $this->dbCharset = $conf[$prefix.'db_charset']; + $this->dbNewLink = $conf[$prefix.'db_new_link']; + $this->dbClientFlags = $conf[$prefix.'db_client_flags']; + parent::__construct($conf[$prefix.'db_host'], $conf[$prefix.'db_user'], $conf[$prefix.'db_password'], $conf[$prefix.'db_database']); + $try = 0; + //while(!is_null($this->connect_error) && $try < 5) { + while(mysqli_connect_error() && $try < 5) { + if($try > 0) sleep(1); + + $try++; + $this->updateError('DB::__construct'); + + parent::__construct($conf[$prefix.'db_host'], $conf[$prefix.'db_user'], $conf[$prefix.'db_password'], $conf[$prefix.'db_database']); + } - /* + //if(is_null($this->connect_error)) $this->isConnected = true; + //else return false; + if(!mysqli_connect_error()) $this->isConnected = true; + else return false; + + $this->setCharacterEncoding(); + } + + public function __destruct() { + $this->close(); // helps avoid memory leaks, and persitent connections that don't go away. + } + + // error handler + public function updateError($location) { + global $app, $conf; + + /* if(!is_null($this->connect_error)) { $this->errorNumber = $this->connect_errno; $this->errorMessage = $this->connect_error; @@ -95,183 +95,183 @@ class db extends mysqli $this->errorMessage = $this->error; } */ - if(mysqli_connect_error()) { - $this->errorNumber = mysqli_connect_errno(); - $this->errorMessage = mysqli_connect_error(); - } else { - $this->errorNumber = mysqli_errno($this); - $this->errorMessage = mysqli_error($this); - } + if(mysqli_connect_error()) { + $this->errorNumber = mysqli_connect_errno(); + $this->errorMessage = mysqli_connect_error(); + } else { + $this->errorNumber = mysqli_errno($this); + $this->errorMessage = mysqli_error($this); + } - $this->errorLocation = $location; - if($this->errorNumber) { - $error_msg = $this->errorLocation .' '. $this->errorMessage; - // This right here will allow us to use the same file for server & interface - if($this->show_error_messages && $conf['demo_mode'] === false) { - echo $error_msg; - } else if(is_object($app) && method_exists($app, 'log')) { - $app->log($error_msg, LOGLEVEL_WARN); - } - } - } - - private function setCharacterEncoding() { - if($this->isConnected == false) return false; - parent::query( 'SET NAMES '.$this->dbCharset); - parent::query( "SET character_set_results = '".$this->dbCharset."', character_set_client = '".$this->dbCharset."', character_set_connection = '".$this->dbCharset."', character_set_database = '".$this->dbCharset."', character_set_server = '".$this->dbCharset."'"); - } - - public function query($queryString) { - global $conf; - if($this->isConnected == false) return false; - $try = 0; - do { - $try++; - $ok = $this->ping(); - if(!$ok) { - if(!$this->real_connect($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName)) { - if($try > 4) { - $this->updateError('DB::query -> reconnect'); - return false; - } else { - sleep(1); - } - } else { - $this->setCharacterEncoding(); - $ok = true; - } - } - } while($ok == false); - $this->queryId = parent::query($queryString); - $this->updateError('DB::query('.$queryString.') -> mysqli_query'); - if($this->errorNumber && $conf['demo_mode'] === false) debug_print_backtrace(); - if(!$this->queryId) { - return false; - } - $this->currentRow = 0; - return $this->queryId; - } - - // returns all records in an array - public function queryAllRecords($queryString) { - if(!$this->query($queryString)) - { - return false; - } - $ret = array(); - while($line = $this->nextRecord()) - { - $ret[] = $line; - } - return $ret; - } - - // returns one record in an array - public function queryOneRecord($queryString) { - if(!$this->query($queryString) || $this->numRows() == 0) - { - return false; - } - return $this->nextRecord(); - } - - // returns the next record in an array - public function nextRecord() { - $this->record = $this->queryId->fetch_assoc(); - $this->updateError('DB::nextRecord()-> mysql_fetch_array'); - if(!$this->record || !is_array($this->record)) - { - return false; - } - $this->currentRow++; - return $this->record; - } - - // returns number of rows returned by the last select query - public function numRows() { - return intval($this->queryId->num_rows); - } - - public function affectedRows() { - return intval($this->queryId->affected_rows); - } - - // returns mySQL insert id - public function insertID() { - return $this->insert_id; - } - - - //* Function to quote strings - public function quote($formfield) { - return $this->escape_string($formfield); - } - - //* Function to unquotae strings - public function unquote($formfield) { - return stripslashes($formfield); - } - -public function toLower($record) { - if(is_array($record)) { - foreach($record as $key => $val) { - $key = strtolower($key); - $out[$key] = $val; - } - } - return $out; - } - - public function diffrec($record_old, $record_new) { - $diffrec_full = array(); - $diff_num = 0; - - if(is_array($record_old) && count($record_old) > 0) { - foreach($record_old as $key => $val) { - // if(!isset($record_new[$key]) || $record_new[$key] != $val) { - if(@$record_new[$key] != $val) { - // Record has changed - $diffrec_full['old'][$key] = $val; - $diffrec_full['new'][$key] = @$record_new[$key]; - $diff_num++; - } else { - $diffrec_full['old'][$key] = $val; - $diffrec_full['new'][$key] = $val; + $this->errorLocation = $location; + if($this->errorNumber) { + $error_msg = $this->errorLocation .' '. $this->errorMessage; + // This right here will allow us to use the same file for server & interface + if($this->show_error_messages && $conf['demo_mode'] === false) { + echo $error_msg; + } else if(is_object($app) && method_exists($app, 'log')) { + $app->log($error_msg, LOGLEVEL_WARN); + } + } } - } - } elseif(is_array($record_new)) { - foreach($record_new as $key => $val) { - if(isset($record_new[$key]) && @$record_old[$key] != $val) { - // Record has changed - $diffrec_full['new'][$key] = $val; - $diffrec_full['old'][$key] = @$record_old[$key]; - $diff_num++; - } else { - $diffrec_full['new'][$key] = $val; - $diffrec_full['old'][$key] = $val; - } + + private function setCharacterEncoding() { + if($this->isConnected == false) return false; + parent::query( 'SET NAMES '.$this->dbCharset); + parent::query( "SET character_set_results = '".$this->dbCharset."', character_set_client = '".$this->dbCharset."', character_set_connection = '".$this->dbCharset."', character_set_database = '".$this->dbCharset."', character_set_server = '".$this->dbCharset."'"); } - } - return array('diff_num' => $diff_num, 'diff_rec' => $diffrec_full); + public function query($queryString) { + global $conf; + if($this->isConnected == false) return false; + $try = 0; + do { + $try++; + $ok = $this->ping(); + if(!$ok) { + if(!$this->real_connect($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName)) { + if($try > 4) { + $this->updateError('DB::query -> reconnect'); + return false; + } else { + sleep(1); + } + } else { + $this->setCharacterEncoding(); + $ok = true; + } + } + } while($ok == false); + $this->queryId = parent::query($queryString); + $this->updateError('DB::query('.$queryString.') -> mysqli_query'); + if($this->errorNumber && $conf['demo_mode'] === false) debug_print_backtrace(); + if(!$this->queryId) { + return false; + } + $this->currentRow = 0; + return $this->queryId; + } - } + // returns all records in an array + public function queryAllRecords($queryString) { + if(!$this->query($queryString)) + { + return false; + } + $ret = array(); + while($line = $this->nextRecord()) + { + $ret[] = $line; + } + return $ret; + } + + // returns one record in an array + public function queryOneRecord($queryString) { + if(!$this->query($queryString) || $this->numRows() == 0) + { + return false; + } + return $this->nextRecord(); + } + + // returns the next record in an array + public function nextRecord() { + $this->record = $this->queryId->fetch_assoc(); + $this->updateError('DB::nextRecord()-> mysql_fetch_array'); + if(!$this->record || !is_array($this->record)) + { + return false; + } + $this->currentRow++; + return $this->record; + } + + // returns number of rows returned by the last select query + public function numRows() { + return intval($this->queryId->num_rows); + } + + public function affectedRows() { + return intval($this->queryId->affected_rows); + } - //** Function to fill the datalog with a full differential record. - public function datalogSave($db_table, $action, $primary_field, $primary_id, $record_old, $record_new, $force_update = false) { - global $app,$conf; + // returns mySQL insert id + public function insertID() { + return $this->insert_id; + } + + + //* Function to quote strings + public function quote($formfield) { + return $this->escape_string($formfield); + } - // Insert backticks only for incomplete table names. - if(stristr($db_table,'.')) { - $escape = ''; - } else { - $escape = '`'; - } + //* Function to unquotae strings + public function unquote($formfield) { + return stripslashes($formfield); + } + + public function toLower($record) { + if(is_array($record)) { + foreach($record as $key => $val) { + $key = strtolower($key); + $out[$key] = $val; + } + } + return $out; + } + + public function diffrec($record_old, $record_new) { + $diffrec_full = array(); + $diff_num = 0; + + if(is_array($record_old) && count($record_old) > 0) { + foreach($record_old as $key => $val) { + // if(!isset($record_new[$key]) || $record_new[$key] != $val) { + if(@$record_new[$key] != $val) { + // Record has changed + $diffrec_full['old'][$key] = $val; + $diffrec_full['new'][$key] = @$record_new[$key]; + $diff_num++; + } else { + $diffrec_full['old'][$key] = $val; + $diffrec_full['new'][$key] = $val; + } + } + } elseif(is_array($record_new)) { + foreach($record_new as $key => $val) { + if(isset($record_new[$key]) && @$record_old[$key] != $val) { + // Record has changed + $diffrec_full['new'][$key] = $val; + $diffrec_full['old'][$key] = @$record_old[$key]; + $diff_num++; + } else { + $diffrec_full['new'][$key] = $val; + $diffrec_full['old'][$key] = $val; + } + } + } + + return array('diff_num' => $diff_num, 'diff_rec' => $diffrec_full); + + } + + //** Function to fill the datalog with a full differential record. + public function datalogSave($db_table, $action, $primary_field, $primary_id, $record_old, $record_new, $force_update = false) { + global $app, $conf; + + // Insert backticks only for incomplete table names. + if(stristr($db_table, '.')) { + $escape = ''; + } else { + $escape = '`'; + } if($force_update == true) { //* We force a update even if no record has changed - $diffrec_full = array('new' => $record_new,'old' => $record_old); + $diffrec_full = array('new' => $record_new, 'old' => $record_old); $diff_num = count($record_new); } else { //* get the difference record between old and new record @@ -281,135 +281,135 @@ public function toLower($record) { unset($tmp); } - // Insert the server_id, if the record has a server_id - $server_id = (isset($record_old['server_id']) && $record_old['server_id'] > 0)?$record_old['server_id']:0; - if(isset($record_new['server_id'])) $server_id = $record_new['server_id']; + // Insert the server_id, if the record has a server_id + $server_id = (isset($record_old['server_id']) && $record_old['server_id'] > 0)?$record_old['server_id']:0; + if(isset($record_new['server_id'])) $server_id = $record_new['server_id']; - if($diff_num > 0) { - //print_r($diff_num); - //print_r($diffrec_full); - $diffstr = $app->db->quote(serialize($diffrec_full)); - $username = $app->db->quote($_SESSION['s']['user']['username']); - $dbidx = $primary_field.':'.$primary_id; + if($diff_num > 0) { + //print_r($diff_num); + //print_r($diffrec_full); + $diffstr = $app->db->quote(serialize($diffrec_full)); + $username = $app->db->quote($_SESSION['s']['user']['username']); + $dbidx = $primary_field.':'.$primary_id; - if($action == 'INSERT') $action = 'i'; - if($action == 'UPDATE') $action = 'u'; - if($action == 'DELETE') $action = 'd'; - $sql = "INSERT INTO sys_datalog (dbtable,dbidx,server_id,action,tstamp,user,data) VALUES ('".$db_table."','$dbidx','$server_id','$action','".time()."','$username','$diffstr')"; - $app->db->query($sql); - } + if($action == 'INSERT') $action = 'i'; + if($action == 'UPDATE') $action = 'u'; + if($action == 'DELETE') $action = 'd'; + $sql = "INSERT INTO sys_datalog (dbtable,dbidx,server_id,action,tstamp,user,data) VALUES ('".$db_table."','$dbidx','$server_id','$action','".time()."','$username','$diffstr')"; + $app->db->query($sql); + } - return true; - } + return true; + } - //** Inserts a record and saves the changes into the datalog - public function datalogInsert($tablename, $insert_data, $index_field) { - global $app; - - if(is_array($insert_data)) { + //** Inserts a record and saves the changes into the datalog + public function datalogInsert($tablename, $insert_data, $index_field) { + global $app; + + if(is_array($insert_data)) { $key_str = ''; $val_str = ''; foreach($insert_data as $key => $val) { $key_str .= "`".$key ."`,"; $val_str .= "'".$this->quote($val)."',"; } - $key_str = substr($key_str,0,-1); - $val_str = substr($val_str,0,-1); + $key_str = substr($key_str, 0, -1); + $val_str = substr($val_str, 0, -1); $insert_data_str = '('.$key_str.') VALUES ('.$val_str.')'; } else { $insert_data_str = $insert_data; } - $old_rec = array(); - $this->query("INSERT INTO $tablename $insert_data_str"); - $index_value = $this->insertID(); - $new_rec = $this->queryOneRecord("SELECT * FROM $tablename WHERE $index_field = '$index_value'"); - $this->datalogSave($tablename, 'INSERT', $index_field, $index_value, $old_rec, $new_rec); + $old_rec = array(); + $this->query("INSERT INTO $tablename $insert_data_str"); + $index_value = $this->insertID(); + $new_rec = $this->queryOneRecord("SELECT * FROM $tablename WHERE $index_field = '$index_value'"); + $this->datalogSave($tablename, 'INSERT', $index_field, $index_value, $old_rec, $new_rec); - return $index_value; - } + return $index_value; + } - //** Updates a record and saves the changes into the datalog - public function datalogUpdate($tablename, $update_data, $index_field, $index_value, $force_update = false) { + //** Updates a record and saves the changes into the datalog + public function datalogUpdate($tablename, $update_data, $index_field, $index_value, $force_update = false) { global $app; - - $old_rec = $this->queryOneRecord("SELECT * FROM $tablename WHERE $index_field = '$index_value'"); - - if(is_array($update_data)) { + + $old_rec = $this->queryOneRecord("SELECT * FROM $tablename WHERE $index_field = '$index_value'"); + + if(is_array($update_data)) { $update_data_str = ''; foreach($update_data as $key => $val) { $update_data_str .= "`".$key ."` = '".$this->quote($val)."',"; } - $update_data_str = substr($update_data_str,0,-1); + $update_data_str = substr($update_data_str, 0, -1); } else { $update_data_str = $update_data; } - - $this->query("UPDATE $tablename SET $update_data_str WHERE $index_field = '$index_value'"); - $new_rec = $this->queryOneRecord("SELECT * FROM $tablename WHERE $index_field = '$index_value'"); - $this->datalogSave($tablename, 'UPDATE', $index_field, $index_value, $old_rec, $new_rec, $force_update); - return true; - } + $this->query("UPDATE $tablename SET $update_data_str WHERE $index_field = '$index_value'"); + $new_rec = $this->queryOneRecord("SELECT * FROM $tablename WHERE $index_field = '$index_value'"); + $this->datalogSave($tablename, 'UPDATE', $index_field, $index_value, $old_rec, $new_rec, $force_update); - //** Deletes a record and saves the changes into the datalog - public function datalogDelete($tablename, $index_field, $index_value) { - global $app; + return true; + } - $old_rec = $this->queryOneRecord("SELECT * FROM $tablename WHERE $index_field = '$index_value'"); - $this->query("DELETE FROM $tablename WHERE $index_field = '$index_value'"); - $new_rec = array(); - $this->datalogSave($tablename, 'DELETE', $index_field, $index_value, $old_rec, $new_rec); + //** Deletes a record and saves the changes into the datalog + public function datalogDelete($tablename, $index_field, $index_value) { + global $app; - return true; - } - - //* get the current datalog status for the specified login (or currently logged in user) - public function datalogStatus($login = '') { - global $app; - - $return = array('count' => 0, 'entries' => array()); - if($_SESSION['s']['user']['typ'] == 'admin') return $return; // these information should not be displayed to admin users - - if($login == '' && isset($_SESSION['s']['user'])) { - $login = $_SESSION['s']['user']['username']; - } - - $result = $this->queryAllRecords("SELECT COUNT( * ) AS cnt, sys_datalog.action, sys_datalog.dbtable FROM sys_datalog, server WHERE server.server_id = sys_datalog.server_id AND sys_datalog.user = '" . $this->quote($login) . "' AND sys_datalog.datalog_id > server.updated GROUP BY sys_datalog.dbtable, sys_datalog.action"); - foreach($result as $row) { - if(!$row['dbtable'] || in_array($row['dbtable'], array('aps_instances', 'aps_instances_settings', 'mail_access', 'mail_content_filter'))) continue; // ignore some entries, maybe more to come - $return['entries'][] = array('table' => $row['dbtable'], 'action' => $row['action'], 'count' => $row['cnt'], 'text' => $app->lng('datalog_status_' . $row['action'] . '_' . $row['dbtable'])); - $return['count'] += $row['cnt']; - } - unset($result); - - return $return; - } + $old_rec = $this->queryOneRecord("SELECT * FROM $tablename WHERE $index_field = '$index_value'"); + $this->query("DELETE FROM $tablename WHERE $index_field = '$index_value'"); + $new_rec = array(); + $this->datalogSave($tablename, 'DELETE', $index_field, $index_value, $old_rec, $new_rec); + return true; + } - public function freeResult($query) - { - if(is_object($query) && (get_class($query) == "mysqli_result")) { - $query->free(); - return true; - } else { - return false; - } - } + //* get the current datalog status for the specified login (or currently logged in user) + public function datalogStatus($login = '') { + global $app; - /* TODO: Does anything use this? */ - public function delete() { + $return = array('count' => 0, 'entries' => array()); + if($_SESSION['s']['user']['typ'] == 'admin') return $return; // these information should not be displayed to admin users - } + if($login == '' && isset($_SESSION['s']['user'])) { + $login = $_SESSION['s']['user']['username']; + } - /* TODO: Does anything use this? */ - public function Transaction($action) { - //action = begin, commit oder rollback + $result = $this->queryAllRecords("SELECT COUNT( * ) AS cnt, sys_datalog.action, sys_datalog.dbtable FROM sys_datalog, server WHERE server.server_id = sys_datalog.server_id AND sys_datalog.user = '" . $this->quote($login) . "' AND sys_datalog.datalog_id > server.updated GROUP BY sys_datalog.dbtable, sys_datalog.action"); + foreach($result as $row) { + if(!$row['dbtable'] || in_array($row['dbtable'], array('aps_instances', 'aps_instances_settings', 'mail_access', 'mail_content_filter'))) continue; // ignore some entries, maybe more to come + $return['entries'][] = array('table' => $row['dbtable'], 'action' => $row['action'], 'count' => $row['cnt'], 'text' => $app->lng('datalog_status_' . $row['action'] . '_' . $row['dbtable'])); + $return['count'] += $row['cnt']; + } + unset($result); - } + return $return; + } + + + public function freeResult($query) + { + if(is_object($query) && (get_class($query) == "mysqli_result")) { + $query->free(); + return true; + } else { + return false; + } + } - /* + /* TODO: Does anything use this? */ + public function delete() { + + } + + /* TODO: Does anything use this? */ + public function Transaction($action) { + //action = begin, commit oder rollback + + } + + /* $columns = array(action => add | alter | drop name => Spaltenname name_new => neuer Spaltenname, nur bei 'alter' belegt @@ -423,33 +423,33 @@ public function toLower($record) { */ - public function createTable($table_name,$columns) { - $index = ''; - $sql = "CREATE TABLE $table_name ("; - foreach($columns as $col){ - $sql .= $col['name'].' '.$this->mapType($col['type'],$col['typeValue']).' '; - - if($col['defaultValue'] != '') $sql .= "DEFAULT '".$col['defaultValue']."' "; - if($col['notNull'] == true) { - $sql .= 'NOT NULL '; - } else { - $sql .= 'NULL '; + public function createTable($table_name, $columns) { + $index = ''; + $sql = "CREATE TABLE $table_name ("; + foreach($columns as $col){ + $sql .= $col['name'].' '.$this->mapType($col['type'], $col['typeValue']).' '; + + if($col['defaultValue'] != '') $sql .= "DEFAULT '".$col['defaultValue']."' "; + if($col['notNull'] == true) { + $sql .= 'NOT NULL '; + } else { + $sql .= 'NULL '; + } + if($col['autoInc'] == true) $sql .= 'auto_increment '; + $sql.= ','; + // key Definitionen + if($col['option'] == 'primary') $index .= 'PRIMARY KEY ('.$col['name'].'),'; + if($col['option'] == 'index') $index .= 'INDEX ('.$col['name'].'),'; + if($col['option'] == 'unique') $index .= 'UNIQUE ('.$col['name'].'),'; + } + $sql .= $index; + $sql = substr($sql, 0, -1); + $sql .= ')'; + $this->query($sql); + return true; } - if($col['autoInc'] == true) $sql .= 'auto_increment '; - $sql.= ','; - // key Definitionen - if($col['option'] == 'primary') $index .= 'PRIMARY KEY ('.$col['name'].'),'; - if($col['option'] == 'index') $index .= 'INDEX ('.$col['name'].'),'; - if($col['option'] == 'unique') $index .= 'UNIQUE ('.$col['name'].'),'; - } - $sql .= $index; - $sql = substr($sql,0,-1); - $sql .= ')'; - $this->query($sql); - return true; - } - /* + /* $columns = array(action => add | alter | drop name => Spaltenname name_new => neuer Spaltenname, nur bei 'alter' belegt @@ -462,59 +462,59 @@ public function toLower($record) { */ - public function alterTable($table_name,$columns) { - $index = ''; - $sql = "ALTER TABLE $table_name "; - foreach($columns as $col){ - if($col['action'] == 'add') { - $sql .= 'ADD '.$col['name'].' '.$this->mapType($col['type'],$col['typeValue']).' '; - } elseif ($col['action'] == 'alter') { - $sql .= 'CHANGE '.$col['name'].' '.$col['name_new'].' '.$this->mapType($col['type'],$col['typeValue']).' '; - } elseif ($col['action'] == 'drop') { - $sql .= 'DROP '.$col['name'].' '; - } - if($col['action'] != 'drop') { - if($col['defaultValue'] != '') $sql .= "DEFAULT '".$col['defaultValue']."' "; - if($col['notNull'] == true) { - $sql .= 'NOT NULL '; - } else { - $sql .= 'NULL '; - } - if($col['autoInc'] == true) $sql .= 'auto_increment '; - $sql.= ','; - // Index definitions - if($col['option'] == 'primary') $index .= 'PRIMARY KEY ('.$col['name'].'),'; - if($col['option'] == 'index') $index .= 'INDEX ('.$col['name'].'),'; - if($col['option'] == 'unique') $index .= 'UNIQUE ('.$col['name'].'),'; - } - } - $sql .= $index; - $sql = substr($sql,0,-1); + public function alterTable($table_name, $columns) { + $index = ''; + $sql = "ALTER TABLE $table_name "; + foreach($columns as $col){ + if($col['action'] == 'add') { + $sql .= 'ADD '.$col['name'].' '.$this->mapType($col['type'], $col['typeValue']).' '; + } elseif ($col['action'] == 'alter') { + $sql .= 'CHANGE '.$col['name'].' '.$col['name_new'].' '.$this->mapType($col['type'], $col['typeValue']).' '; + } elseif ($col['action'] == 'drop') { + $sql .= 'DROP '.$col['name'].' '; + } + if($col['action'] != 'drop') { + if($col['defaultValue'] != '') $sql .= "DEFAULT '".$col['defaultValue']."' "; + if($col['notNull'] == true) { + $sql .= 'NOT NULL '; + } else { + $sql .= 'NULL '; + } + if($col['autoInc'] == true) $sql .= 'auto_increment '; + $sql.= ','; + // Index definitions + if($col['option'] == 'primary') $index .= 'PRIMARY KEY ('.$col['name'].'),'; + if($col['option'] == 'index') $index .= 'INDEX ('.$col['name'].'),'; + if($col['option'] == 'unique') $index .= 'UNIQUE ('.$col['name'].'),'; + } + } + $sql .= $index; + $sql = substr($sql, 0, -1); - //die($sql); - $this->query($sql); - return true; - } + //die($sql); + $this->query($sql); + return true; + } - public function dropTable($table_name) { - $this->check($table_name); - $sql = "DROP TABLE '". $table_name."'"; - return $this->query($sql); - } + public function dropTable($table_name) { + $this->check($table_name); + $sql = "DROP TABLE '". $table_name."'"; + return $this->query($sql); + } - // gibt Array mit Tabellennamen zur�ck - public function getTables($database_name = '') { - if($this->isConnected == false) return false; - if($database_name == '') $database_name = $this->dbName; - $result = parent::query("SHOW TABLES FROM $database_name"); - for ($i = 0; $i < $result->num_rows; $i++) { - $tb_names[$i] = (($result->data_seek( $i) && (($___mysqli_tmp = $result->fetch_row()) !== NULL)) ? array_shift($___mysqli_tmp) : false); - } - return $tb_names; - } + // gibt Array mit Tabellennamen zur�ck + public function getTables($database_name = '') { + if($this->isConnected == false) return false; + if($database_name == '') $database_name = $this->dbName; + $result = parent::query("SHOW TABLES FROM $database_name"); + for ($i = 0; $i < $result->num_rows; $i++) { + $tb_names[$i] = (($result->data_seek( $i) && (($___mysqli_tmp = $result->fetch_row()) !== NULL)) ? array_shift($___mysqli_tmp) : false); + } + return $tb_names; + } - // gibt Feldinformationen zur Tabelle zur�ck - /* + // gibt Feldinformationen zur Tabelle zur�ck + /* $columns = array(action => add | alter | drop name => Spaltenname name_new => neuer Spaltenname, nur bei 'alter' belegt @@ -528,14 +528,14 @@ public function toLower($record) { */ - function tableInfo($table_name) { + function tableInfo($table_name) { - global $go_api,$go_info,$app; - // Tabellenfelder einlesen + global $go_api, $go_info, $app; + // Tabellenfelder einlesen - if($rows = $app->db->queryAllRecords('SHOW FIELDS FROM '.$table_name)){ - foreach($rows as $row) { - /* + if($rows = $app->db->queryAllRecords('SHOW FIELDS FROM '.$table_name)){ + foreach($rows as $row) { + /* $name = $row[0]; $default = $row[4]; $key = $row[3]; @@ -543,61 +543,61 @@ public function toLower($record) { $isnull = $row[2]; $type = $row[1]; */ - - $name = $row['Field']; - $default = $row['Default']; - $key = $row['Key']; - $extra = $row['Extra']; - $isnull = $row['Null']; - $type = $row['Type']; - - - $column = array(); - - $column['name'] = $name; - //$column['type'] = $type; - $column['defaultValue'] = $default; - if(stristr($key,'PRI')) $column['option'] = 'primary'; - if(stristr($isnull,'YES')) { - $column['notNull'] = false; - } else { - $column['notNull'] = true; - } - if($extra == 'auto_increment') $column['autoInc'] = true; - - - // Type in Metatype umsetzen - - if(stristr($type,'int(')) $metaType = 'int32'; - if(stristr($type,'bigint')) $metaType = 'int64'; - if(stristr($type,'char')) { - $metaType = 'char'; - $tmp_typeValue = explode('(',$type); - $column['typeValue'] = substr($tmp_typeValue[1],0,-1); - } - if(stristr($type,'varchar')) { - $metaType = 'varchar'; - $tmp_typeValue = explode('(',$type); - $column['typeValue'] = substr($tmp_typeValue[1],0,-1); - } - if(stristr($type,'text')) $metaType = 'text'; - if(stristr($type,'double')) $metaType = 'double'; - if(stristr($type,'blob')) $metaType = 'blob'; - - - $column['type'] = $metaType; - - $columns[] = $column; - } - return $columns; - } else { - return false; - } - - - //$this->createTable('tester',$columns); - - /* + + $name = $row['Field']; + $default = $row['Default']; + $key = $row['Key']; + $extra = $row['Extra']; + $isnull = $row['Null']; + $type = $row['Type']; + + + $column = array(); + + $column['name'] = $name; + //$column['type'] = $type; + $column['defaultValue'] = $default; + if(stristr($key, 'PRI')) $column['option'] = 'primary'; + if(stristr($isnull, 'YES')) { + $column['notNull'] = false; + } else { + $column['notNull'] = true; + } + if($extra == 'auto_increment') $column['autoInc'] = true; + + + // Type in Metatype umsetzen + + if(stristr($type, 'int(')) $metaType = 'int32'; + if(stristr($type, 'bigint')) $metaType = 'int64'; + if(stristr($type, 'char')) { + $metaType = 'char'; + $tmp_typeValue = explode('(', $type); + $column['typeValue'] = substr($tmp_typeValue[1], 0, -1); + } + if(stristr($type, 'varchar')) { + $metaType = 'varchar'; + $tmp_typeValue = explode('(', $type); + $column['typeValue'] = substr($tmp_typeValue[1], 0, -1); + } + if(stristr($type, 'text')) $metaType = 'text'; + if(stristr($type, 'double')) $metaType = 'double'; + if(stristr($type, 'blob')) $metaType = 'blob'; + + + $column['type'] = $metaType; + + $columns[] = $column; + } + return $columns; + } else { + return false; + } + + + //$this->createTable('tester',$columns); + + /* $result = mysql_list_fields($go_info["server"]["db_name"],$table_name); $fields = mysql_num_fields ($result); $i = 0; @@ -622,40 +622,40 @@ public function toLower($record) { - } + } + + public function mapType($metaType, $typeValue) { + global $go_api; + $metaType = strtolower($metaType); + switch ($metaType) { + case 'int16': + return 'smallint'; + break; + case 'int32': + return 'int'; + break; + case 'int64': + return 'bigint'; + break; + case 'double': + return 'double'; + break; + case 'char': + return 'char'; + break; + case 'varchar': + if($typeValue < 1) die('Database failure: Lenght required for these data types.'); + return 'varchar('.$typeValue.')'; + break; + case 'text': + return 'text'; + break; + case 'blob': + return 'blob'; + break; + } + } + +} - public function mapType($metaType,$typeValue) { - global $go_api; - $metaType = strtolower($metaType); - switch ($metaType) { - case 'int16': - return 'smallint'; - break; - case 'int32': - return 'int'; - break; - case 'int64': - return 'bigint'; - break; - case 'double': - return 'double'; - break; - case 'char': - return 'char'; - break; - case 'varchar': - if($typeValue < 1) die('Database failure: Lenght required for these data types.'); - return 'varchar('.$typeValue.')'; - break; - case 'text': - return 'text'; - break; - case 'blob': - return 'blob'; - break; - } - } - - } - - ?> \ No newline at end of file +?> diff --git a/interface/lib/classes/form.inc.php b/interface/lib/classes/form.inc.php index 898cbe6c05570771383033a58b6c36ccb20c9c6d..34c0b626c3c0b379f0b91ea8443ee07d8472fce0 100644 --- a/interface/lib/classes/form.inc.php +++ b/interface/lib/classes/form.inc.php @@ -29,165 +29,192 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** -* Formularbehandlung -* -* Funktionen zur Umwandlung von Formulardaten -* sowie zum vorbereiten von HTML und SQL -* Ausgaben -* -* Tabellendefinition -* -* Datentypen: -* - INTEGER (Wandelt Ausdrücke in Int um) -* - DOUBLE -* - CURRENCY (Formatiert Zahlen nach Währungsnotation) -* - VARCHAR (kein weiterer Format Check) -* - DATE (Datumsformat, Timestamp Umwandlung) -* -* Formtype: -* - TEXT (normales Textfeld) -* - PASSWORD (Feldinhalt wird nicht angezeigt) -* - SELECT (Gibt Werte als option Feld aus) -* - MULTIPLE (Select-Feld mit nehreren Werten) -* -* VALUE: -* - Wert oder Array -* -* SEPARATOR -* - Trennzeichen für multiple Felder -* -* Hinweis: -* Das ID-Feld ist nicht bei den Table Values einzufügen. -* -* @package form -* @author Till Brehm -* @version 1.1 -*/ + * Formularbehandlung + * + * Funktionen zur Umwandlung von Formulardaten + * sowie zum vorbereiten von HTML und SQL + * Ausgaben + * + * Tabellendefinition + * + * Datentypen: + * - INTEGER (Wandelt Ausdrücke in Int um) + * - DOUBLE + * - CURRENCY (Formatiert Zahlen nach Währungsnotation) + * - VARCHAR (kein weiterer Format Check) + * - DATE (Datumsformat, Timestamp Umwandlung) + * + * Formtype: + * - TEXT (normales Textfeld) + * - PASSWORD (Feldinhalt wird nicht angezeigt) + * - SELECT (Gibt Werte als option Feld aus) + * - MULTIPLE (Select-Feld mit nehreren Werten) + * + * VALUE: + * - Wert oder Array + * + * SEPARATOR + * - Trennzeichen für multiple Felder + * + * Hinweis: + * Das ID-Feld ist nicht bei den Table Values einzufügen. + * + * @package form + * @author Till Brehm + * @version 1.1 + */ + class form { - + + + /** - * Definition der Tabelle (array) - * @var tableDef - */ + * Definition der Tabelle (array) + * @var tableDef + */ var $tableDef; - + + + /** - * Private - * @var action - */ + * Private + * @var action + */ var $action; - + + + /** - * Tabellenname (String) - * @var table_name - */ + * Tabellenname (String) + * @var table_name + */ var $table_name; - + + + /** - * Debug Variable - * @var debug - */ + * Debug Variable + * @var debug + */ var $debug = 0; - + + + /** - * name des primary Field der Tabelle (string) - * @var table_index - */ + * name des primary Field der Tabelle (string) + * @var table_index + */ var $table_index; - + + + /** - * enthält die Fehlermeldung bei Überprüfung - * der Variablen mit Regex - * @var errorMessage - */ + * enthält die Fehlermeldung bei Überprüfung + * der Variablen mit Regex + * @var errorMessage + */ var $errorMessage; - + var $dateformat = "d.m.Y"; - var $formDef; - + var $formDef; + + + + + /** - * Laden der Tabellendefinition - * - * @param file: Pfad zur Tabellendefinition - * @return true - */ + * Laden der Tabellendefinition + * + * @param file: Pfad zur Tabellendefinition + * @return true + */ function loadTableDef($file) { - global $app,$conf; - - include_once($file); + global $app, $conf; + + include_once $file; $this->tableDef = $table; $this->table_name = $table_name; $this->table_index = $table_index; return true; } - - function loadFormDef($file) { - global $app,$conf; - - include_once($file); + + function loadFormDef($file) { + global $app, $conf; + + include_once $file; $this->formDef = $form; return true; } - - + + + + + + + + /** - * Konvertiert die Daten des übergebenen assoziativen - * Arrays in "menschenlesbare" Form. - * Datentyp Konvertierung, z.B. für Ausgabe in Listen. - * - * @param record - * @return record - */ + * Konvertiert die Daten des übergebenen assoziativen + * Arrays in "menschenlesbare" Form. + * Datentyp Konvertierung, z.B. für Ausgabe in Listen. + * + * @param record + * @return record + */ function decode($record) { - global $app; + global $app; if(is_array($record)) { foreach($record as $key => $val) { switch ($this->tableDef[$key]['datatype']) { case 'VARCHAR': $new_record[$key] = stripslashes($val); - break; - + break; + case 'DATE': if($val > 0) { - $new_record[$key] = date($this->dateformat,$val); + $new_record[$key] = date($this->dateformat, $val); } - break; - + break; + case 'INTEGER': $new_record[$key] = $app->functions->intval($val); - break; - + break; + case 'DOUBLE': $new_record[$key] = $val; - break; - + break; + case 'CURRENCY': $new_record[$key] = number_format($val, 2, ',', ''); - break; - + break; + default: $new_record[$key] = stripslashes($val); } } - + } - return $new_record; + return $new_record; } - + + + + + /** - * Record für Ausgabe in Formularen vorbereiten. - * - * @param record = Datensatz als Array - * @param action = NEW oder EDIT - * @return record - */ - function getHTML($record,$action = 'NEW') { - + * Record für Ausgabe in Formularen vorbereiten. + * + * @param record = Datensatz als Array + * @param action = NEW oder EDIT + * @return record + */ + function getHTML($record, $action = 'NEW') { + global $app; - + if(!is_array($this->tableDef)) $app->error("Keine Tabellendefinition vorhanden."); - + $new_record = array(); if($action == 'EDIT') { $record = $this->decode($record); @@ -203,32 +230,32 @@ class form { } } $new_record[$key] = $out; - break; + break; case 'MULTIPLE': if(is_array($this->tableDef[$key]['value'])) { - + // aufsplitten ergebnisse - $vals = explode($this->tableDef[$key]['separator'],$val); - + $vals = explode($this->tableDef[$key]['separator'], $val); + // HTML schreiben $out = ''; foreach($this->tableDef[$key]['value'] as $k => $v) { - + $selected = ''; foreach($vals as $tvl) { if(trim($tvl) == trim($k)) $selected = ' SELECTED'; } - + $out .= "\r\n"; } } $new_record[$key] = $out; - break; - + break; + case 'PASSWORD': $new_record[$key] = ''; - break; - + break; + default: $new_record[$key] = htmlspecialchars($val); } @@ -246,50 +273,54 @@ class form { } } $new_record[$key] = $out; - break; + break; case 'MULTIPLE': - if(is_array($this->tableDef[$key]['value'])) { - - // aufsplitten ergebnisse - $vals = explode($this->tableDef[$key]['separator'],$val); - - // HTML schreiben - $out = ''; - foreach($this->tableDef[$key]['value'] as $k => $v) { - - $out .= "\r\n"; - } + if(is_array($this->tableDef[$key]['value'])) { + + // aufsplitten ergebnisse + $vals = explode($this->tableDef[$key]['separator'], $val); + + // HTML schreiben + $out = ''; + foreach($this->tableDef[$key]['value'] as $k => $v) { + + $out .= "\r\n"; } - $new_record[$key] = $out; + } + $new_record[$key] = $out; break; - + case 'PASSWORD': $new_record[$key] = ''; - break; - + break; + default: $new_record[$key] = htmlspecialchars($this->tableDef[$key]['value']); } } - + } - + if($this->debug == 1) $this->dbg($new_record); - + return $new_record; } - + + + + + /** - * Record in "maschinen lesbares" Format überführen - * und Werte gegen reguläre Ausdrücke prüfen. - * - * @param record = Datensatz als Array - * @return record - */ + * Record in "maschinen lesbares" Format überführen + * und Werte gegen reguläre Ausdrücke prüfen. + * + * @param record = Datensatz als Array + * @return record + */ function encode($record) { global $app; $this->errorMessage = ''; - + if(is_array($record)) { foreach($record as $key => $val) { switch ($this->tableDef[$key]['datatype']) { @@ -297,26 +328,26 @@ class form { if(!is_array($val)) { $new_record[$key] = $app->db->quote($val); } else { - $new_record[$key] = implode($this->tableDef[$key]['separator'],$val); + $new_record[$key] = implode($this->tableDef[$key]['separator'], $val); } - break; + break; case 'DATE': if($val > 0) { - list($tag,$monat,$jahr) = explode('.',$val); - $new_record[$key] = mktime(0,0,0,$monat,$tag,$jahr); + list($tag, $monat, $jahr) = explode('.', $val); + $new_record[$key] = mktime(0, 0, 0, $monat, $tag, $jahr); } - break; + break; case 'INTEGER': $new_record[$key] = $app->functions->intval($val); - break; + break; case 'DOUBLE': $new_record[$key] = $app->db->quote($val); - break; + break; case 'CURRENCY': - $new_record[$key] = str_replace(",",".",$val); - break; + $new_record[$key] = str_replace(",", ".", $val); + break; } - + if($this->tableDef[$key]['regex'] != '') { // Enable that "." matches also newlines $this->tableDef[$key]['regex'] .= 's'; @@ -325,152 +356,160 @@ class form { } } } - + } return $new_record; } - + + + + + /** - * SQL Statement für Record erzeugen. - * - * @param record = Datensatz als Array - * @param action = INSERT oder UPDATE - * @param primary_id - * @return record - */ + * SQL Statement für Record erzeugen. + * + * @param record = Datensatz als Array + * @param action = INSERT oder UPDATE + * @param primary_id + * @return record + */ function getSQL($record, $action = 'INSERT', $primary_id = 0, $sql_ext_where = '') { - + global $app; - + $record = $this->encode($record); $sql_insert_key = ''; $sql_insert_val = ''; $sql_update = ''; - + if(!is_array($this->tableDef)) $app->error("Keine Tabellendefinition vorhanden."); - + // gehe durch alle Felder des Records if(is_array($record)) { - foreach($record as $key => $val) { - // Wenn es kein leeres Passwortfeld ist - if (!($this->tableDef[$key]['formtype'] == 'PASSWORD' and $val == '')) { - // gehe durch alle Felder der TableDef - foreach($this->tableDef as $tk => $tv) { - // Wenn Feld in TableDef enthalten ist - if($tk == $key) { - // Erzeuge Insert oder Update Quelltext - if($action == "INSERT") { - - if($this->tableDef[$key]['formtype'] == 'PASSWORD') { - $sql_insert_key .= "`$key`, "; - $sql_insert_val .= "md5('$val'), "; - //} elseif($this->tableDef[$key]['formtype'] == 'MULTIPLE') { - // $val = implode($this->tableDef[$key]['separator'],$val); - // $sql_insert_key .= "`$key`, "; - // $sql_insert_val .= "'$val', "; - } else { - $sql_insert_key .= "`$key`, "; - $sql_insert_val .= "'$val', "; - } - - } else { - - if($this->tableDef[$key]['formtype'] == 'PASSWORD') { - $sql_update .= "`$key` = md5('$val'), "; - //} elseif($this->tableDef[$key]['formtype'] == 'MULTIPLE') { - // $val = implode($this->tableDef[$key]['separator'],$val); - // $sql_update .= "`$key` = '$val', "; + foreach($record as $key => $val) { + // Wenn es kein leeres Passwortfeld ist + if (!($this->tableDef[$key]['formtype'] == 'PASSWORD' and $val == '')) { + // gehe durch alle Felder der TableDef + foreach($this->tableDef as $tk => $tv) { + // Wenn Feld in TableDef enthalten ist + if($tk == $key) { + // Erzeuge Insert oder Update Quelltext + if($action == "INSERT") { + + if($this->tableDef[$key]['formtype'] == 'PASSWORD') { + $sql_insert_key .= "`$key`, "; + $sql_insert_val .= "md5('$val'), "; + //} elseif($this->tableDef[$key]['formtype'] == 'MULTIPLE') { + // $val = implode($this->tableDef[$key]['separator'],$val); + // $sql_insert_key .= "`$key`, "; + // $sql_insert_val .= "'$val', "; + } else { + $sql_insert_key .= "`$key`, "; + $sql_insert_val .= "'$val', "; + } + } else { - $sql_update .= "`$key` = '$val', "; + + if($this->tableDef[$key]['formtype'] == 'PASSWORD') { + $sql_update .= "`$key` = md5('$val'), "; + //} elseif($this->tableDef[$key]['formtype'] == 'MULTIPLE') { + // $val = implode($this->tableDef[$key]['separator'],$val); + // $sql_update .= "`$key` = '$val', "; + } else { + $sql_update .= "`$key` = '$val', "; + } + } - } } } } } - } - + // Füge Backticks nur bei unvollständigen Tabellennamen ein - if(stristr($this->table_name,'.')) { + if(stristr($this->table_name, '.')) { $escape = ''; } else { $escape = '`'; } - - + + if($action == "INSERT") { - $sql_insert_key = substr($sql_insert_key,0,-2); - $sql_insert_val = substr($sql_insert_val,0,-2); + $sql_insert_key = substr($sql_insert_key, 0, -2); + $sql_insert_val = substr($sql_insert_val, 0, -2); $sql = "INSERT INTO ".$escape.$this->table_name.$escape." ($sql_insert_key) VALUES ($sql_insert_val)"; } else { if($primary_id != 0) { - $sql_update = substr($sql_update,0,-2); + $sql_update = substr($sql_update, 0, -2); $sql = "UPDATE ".$escape.$this->table_name.$escape." SET ".$sql_update." WHERE ".$this->table_index ." = ".$primary_id; if($sql_ext_where != '') $sql .= " and ".$sql_ext_where; } else { $app->error("Primary ID fehlt!"); } } - + return $sql; } - + + + + + /** - * Debugging arrays. - * - * @param array_data - */ + * Debugging arrays. + * + * @param array_data + */ function dbg($array_data) { - + echo "
";
 		print_r($array_data);
 		echo "
"; - + } - - - function showForm() { - global $app,$conf; - - if(!is_array($this->formDef)) die("Form Definition wurde nicht geladen."); - - if($this->errorMessage == '') { - // wenn kein Fehler vorliegt + + + function showForm() { + global $app, $conf; + + if(!is_array($this->formDef)) die("Form Definition wurde nicht geladen."); + + if($this->errorMessage == '') { + // wenn kein Fehler vorliegt if($_REQUEST["next_tab"] != '') { - // wenn nächster Tab bekannt - $active_tab = $_REQUEST["next_tab"]; - } else { - // ansonsten ersten tab nehmen - $active_tab = $this->formDef["tabs"][0]["name"]; - } + // wenn nächster Tab bekannt + $active_tab = $_REQUEST["next_tab"]; + } else { + // ansonsten ersten tab nehmen + $active_tab = $this->formDef["tabs"][0]["name"]; + } } else { - // bei Fehlern den gleichen Tab nochmal anzeigen - $active_tab = $_SESSION["s"]["form"]["tab"]; + // bei Fehlern den gleichen Tab nochmal anzeigen + $active_tab = $_SESSION["s"]["form"]["tab"]; + } + + // definiere Tabs + foreach( $this->formDef["tabs"] as $tab) { + + if($tab["name"] == $active_tab) { + $app->tpl->setInclude('content_tpl', $tab["template"]); + $tab["active"] = 1; + $_SESSION["s"]["form"]["tab"] = $tab["name"]; + } else { + $tab["active"] = 0; + } + + $frmTab[] = $tab; } - - // definiere Tabs - foreach( $this->formDef["tabs"] as $tab) { - - if($tab["name"] == $active_tab) { - $app->tpl->setInclude('content_tpl',$tab["template"]); - $tab["active"] = 1; - $_SESSION["s"]["form"]["tab"] = $tab["name"]; - } else { - $tab["active"] = 0; - } - - $frmTab[] = $tab; - } - - // setze Loop - $app->tpl->setLoop("formTab", $frmTab); + + // setze Loop + $app->tpl->setLoop("formTab", $frmTab); // Formular action setzen - $app->tpl->setVar('form_action',$this->formDef["action"]); - } - - + $app->tpl->setVar('form_action', $this->formDef["action"]); + } + + } ?> diff --git a/interface/lib/classes/functions.inc.php b/interface/lib/classes/functions.inc.php index 64074d4b466223422a84491173f2beacb68c9b2b..d2ac5830a850eeb9679ace811f733fc1c3a315c7 100644 --- a/interface/lib/classes/functions.inc.php +++ b/interface/lib/classes/functions.inc.php @@ -33,14 +33,14 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class functions { var $idn_converter = null; - var $idn_converter_name = ''; + var $idn_converter_name = ''; public function mail($to, $subject, $text, $from, $filepath = '', $filetype = 'application/pdf', $filename = '', $cc = '', $bcc = '', $from_name = '') { - global $app,$conf; - + global $app, $conf; + if($conf['demo_mode'] == true) $app->error("Mail sending disabled in demo mode."); - - $app->uses('getconf,ispcmail'); + + $app->uses('getconf,ispcmail'); $mail_config = $app->getconf->get_global_config('mail'); if($mail_config['smtp_enabled'] == 'y') { $mail_config['use_smtp'] = true; @@ -49,27 +49,27 @@ class functions { $app->ispcmail->setSender($from, $from_name); $app->ispcmail->setSubject($subject); $app->ispcmail->setMailText($text); - + if($filepath != '') { if(!file_exists($filepath)) $app->error("Mail attachement does not exist ".$filepath); $app->ispcmail->readAttachFile($filepath); } - + if($cc != '') $app->ispcmail->setHeader('Cc', $cc); if($bcc != '') $app->ispcmail->setHeader('Bcc', $bcc); - + $app->ispcmail->send($to); $app->ispcmail->finish(); - + /* left in here just for the case... if($filepath != '') { if(!file_exists($filepath)) $app->error("Mail attachement does not exist ".$filepath); - + $content = file_get_contents($filepath); $content = chunk_split(base64_encode($content)); $uid = strtoupper(md5(uniqid(time()))); $subject = "=?utf-8?B?".base64_encode($subject)."?="; - + if($filename == '') { $path_parts = pathinfo($filepath); $filename = $path_parts["basename"]; @@ -109,44 +109,44 @@ class functions { */ return true; } - - public function array_merge($array1,$array2) { + + public function array_merge($array1, $array2) { $out = $array1; foreach($array2 as $key => $val) { $out[$key] = $val; } return $out; } - + public function currency_format($number, $view = '') { global $app; if($view != '') $number_format_decimals = (int)$app->lng('number_format_decimals_'.$view); - if(!$number_format_decimals) $number_format_decimals = (int)$app->lng('number_format_decimals'); - + if(!$number_format_decimals) $number_format_decimals = (int)$app->lng('number_format_decimals'); + $number_format_dec_point = $app->lng('number_format_dec_point'); $number_format_thousands_sep = $app->lng('number_format_thousands_sep'); if($number_format_thousands_sep == 'number_format_thousands_sep') $number_format_thousands_sep = ''; return number_format((double)$number, $number_format_decimals, $number_format_dec_point, $number_format_thousands_sep); } - + //* convert currency formatted number back to floating number public function currency_unformat($number) { global $app; - + $number_format_dec_point = $app->lng('number_format_dec_point'); $number_format_thousands_sep = $app->lng('number_format_thousands_sep'); if($number_format_thousands_sep == 'number_format_thousands_sep') $number_format_thousands_sep = ''; - + if($number_format_thousands_sep != '') $number = str_replace($number_format_thousands_sep, '', $number); if($number_format_dec_point != '.' && $number_format_dec_point != '') $number = str_replace($number_format_dec_point, '.', $number); - + return (double)$number; } - + public function get_ispconfig_url() { global $app; - - $url = (stristr($_SERVER['SERVER_PROTOCOL'],'HTTPS') || stristr($_SERVER['HTTPS'],'on'))?'https':'http'; + + $url = (stristr($_SERVER['SERVER_PROTOCOL'], 'HTTPS') || stristr($_SERVER['HTTPS'], 'on'))?'https':'http'; if($_SERVER['SERVER_NAME'] != '_') { $url .= '://'.$_SERVER['SERVER_NAME']; if($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) { @@ -154,7 +154,7 @@ class functions { } } else { $app->uses("getconf"); - $server_config = $app->getconf->get_server_config(1,'server'); + $server_config = $app->getconf->get_server_config(1, 'server'); $url .= '://'.$server_config['hostname']; if($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) { $url .= ':'.$_SERVER['SERVER_PORT']; @@ -162,53 +162,53 @@ class functions { } return $url; } - - public function json_encode($data) { + + public function json_encode($data) { if(!function_exists('json_encode')){ if(is_array($data) || is_object($data)){ - $islist = is_array($data) && (empty($data) || array_keys($data) === range(0,count($data)-1)); + $islist = is_array($data) && (empty($data) || array_keys($data) === range(0, count($data)-1)); if($islist){ $json = '[' . implode(',', array_map(array($this, "json_encode"), $data) ) . ']'; } else { - $items = Array(); + $items = array(); foreach( $data as $key => $value ) { $items[] = $this->json_encode("$key") . ':' . $this->json_encode($value); } $json = '{' . implode(',', $items) . '}'; } } elseif(is_string($data)){ - # Escape non-printable or Non-ASCII characters. - # I also put the \\ character first, as suggested in comments on the 'addclashes' page. + // Escape non-printable or Non-ASCII characters. + // I also put the \\ character first, as suggested in comments on the 'addclashes' page. $string = '"'.addcslashes($data, "\\\"\n\r\t/".chr(8).chr(12)).'"'; $json = ''; $len = strlen($string); - # Convert UTF-8 to Hexadecimal Codepoints. + // Convert UTF-8 to Hexadecimal Codepoints. for($i = 0; $i < $len; $i++){ $char = $string[$i]; $c1 = ord($char); - # Single byte; + // Single byte; if($c1 <128){ $json .= ($c1 > 31) ? $char : sprintf("\\u%04x", $c1); continue; } - # Double byte + // Double byte $c2 = ord($string[++$i]); if(($c1 & 32) === 0){ $json .= sprintf("\\u%04x", ($c1 - 192) * 64 + $c2 - 128); continue; } - # Triple + // Triple $c3 = ord($string[++$i]); if(($c1 & 16) === 0){ $json .= sprintf("\\u%04x", (($c1 - 224) <<12) + (($c2 - 128) << 6) + ($c3 - 128)); continue; } - # Quadruple + // Quadruple $c4 = ord($string[++$i]); if(($c1 & 8) === 0){ $u = (($c1 & 15) << 2) + (($c2>>4) & 3) - 1; @@ -219,25 +219,25 @@ class functions { } } } else { - # int, floats, bools, null + // int, floats, bools, null $json = strtolower(var_export($data, true)); } return $json; } else { return json_encode($data); } - } - + } + public function suggest_ips($type = 'IPv4'){ global $app; - + if($type == 'IPv4'){ $regex = "/^[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}$/"; } else { // IPv6 $regex = "/^(\:\:([a-f0-9]{1,4}\:){0,6}?[a-f0-9]{0,4}|[a-f0-9]{1,4}(\:[a-f0-9]{1,4}){0,6}?\:\:|[a-f0-9]{1,4}(\:[a-f0-9]{1,4}){1,6}?\:\:([a-f0-9]{1,4}\:){1,6}?[a-f0-9]{1,4})(\/\d{1,3})?$/i"; } - + $server_by_id = array(); $server_by_ip = array(); $servers = $app->db->queryAllRecords("SELECT * FROM server"); @@ -246,7 +246,7 @@ class functions { $server_by_id[$server['server_id']] = $server['server_name']; } } - + $ips = array(); $results = $app->db->queryAllRecords("SELECT ip_address AS ip, server_id FROM server_ip WHERE ip_type = '".$type."'"); if(!empty($results) && is_array($results)){ @@ -275,7 +275,7 @@ class functions { if(preg_match($regex, $result['ip'])) $ips[] = $result['ip']; } } - + $results = $app->db->queryAllRecords("SELECT xfer FROM dns_slave WHERE xfer != ''"); if(!empty($results) && is_array($results)){ foreach($results as $result){ @@ -320,105 +320,107 @@ class functions { sort($ips, SORT_NUMERIC); $result_array = array('cheader' => array(), 'cdata' => array()); - + if(!empty($ips)){ $result_array['cheader'] = array('title' => 'IPs', - 'total' => count($ips), - 'limit' => count($ips) - ); - + 'total' => count($ips), + 'limit' => count($ips) + ); + foreach($ips as $ip){ - $result_array['cdata'][] = array( 'title' => $ip, - 'description' => $type.($server_by_ip[$ip] != ''? ' > '.$server_by_ip[$ip] : ''), - 'onclick' => '', - 'fill_text' => $ip - ); + $result_array['cdata'][] = array( 'title' => $ip, + 'description' => $type.($server_by_ip[$ip] != ''? ' > '.$server_by_ip[$ip] : ''), + 'onclick' => '', + 'fill_text' => $ip + ); } } - + return $result_array; } - public function intval($string, $force_numeric = false) { - if(intval($string) == 2147483647 || ($string > 0 && intval($string) < 0)) { - if($force_numeric == true) return floatval($string); - elseif(preg_match('/^([-]?)[0]*([1-9][0-9]*)([^0-9].*)*$/', $string, $match)) return $match[1].$match[2]; - else return 0; - } else { - return intval($string); - } - } - - /** IDN converter wrapper. - * all converter classes should be placed in ISPC_CLASS_PATH.'/idn/' - */ - private function _idn_encode_decode($domain, $encode = true) { - if($domain == '') return ''; - if(preg_match('/^[0-9\.]+$/', $domain)) return $domain; // may be an ip address - anyway does not need to bee encoded - - // get domain and user part if it is an email - $user_part = false; - if(strpos($domain, '@') !== false) { - $user_part = substr($domain, 0, strrpos($domain, '@')); - $domain = substr($domain, strrpos($domain, '@') + 1); - } - - if($encode == true) { - if(function_exists('idn_to_ascii')) { - $domain = idn_to_ascii($domain); - } elseif(file_exists(ISPC_CLASS_PATH.'/idn/idna_convert.class.php')) { - /* use idna class: + public function intval($string, $force_numeric = false) { + if(intval($string) == 2147483647 || ($string > 0 && intval($string) < 0)) { + if($force_numeric == true) return floatval($string); + elseif(preg_match('/^([-]?)[0]*([1-9][0-9]*)([^0-9].*)*$/', $string, $match)) return $match[1].$match[2]; + else return 0; + } else { + return intval($string); + } + } + + /** IDN converter wrapper. + * all converter classes should be placed in ISPC_CLASS_PATH.'/idn/' + */ + + + private function _idn_encode_decode($domain, $encode = true) { + if($domain == '') return ''; + if(preg_match('/^[0-9\.]+$/', $domain)) return $domain; // may be an ip address - anyway does not need to bee encoded + + // get domain and user part if it is an email + $user_part = false; + if(strpos($domain, '@') !== false) { + $user_part = substr($domain, 0, strrpos($domain, '@')); + $domain = substr($domain, strrpos($domain, '@') + 1); + } + + if($encode == true) { + if(function_exists('idn_to_ascii')) { + $domain = idn_to_ascii($domain); + } elseif(file_exists(ISPC_CLASS_PATH.'/idn/idna_convert.class.php')) { + /* use idna class: * @author Matthias Sommerfeld * @copyright 2004-2011 phlyLabs Berlin, http://phlylabs.de * @version 0.8.0 2011-03-11 */ - - if(!is_object($this->idn_converter) || $this->idn_converter_name != 'idna_convert.class') { - include_once(ISPC_CLASS_PATH.'/idn/idna_convert.class.php'); - $this->idn_converter = new idna_convert(array('idn_version' => 2008)); - $this->idn_converter_name = 'idna_convert.class'; - } - $domain = $this->idn_converter->encode($domain); - } - } else { - if(function_exists('idn_to_utf8')) { - $domain = idn_to_utf8($domain); - } elseif(file_exists(ISPC_CLASS_PATH.'/idn/idna_convert.class.php')) { - /* use idna class: + + if(!is_object($this->idn_converter) || $this->idn_converter_name != 'idna_convert.class') { + include_once ISPC_CLASS_PATH.'/idn/idna_convert.class.php'; + $this->idn_converter = new idna_convert(array('idn_version' => 2008)); + $this->idn_converter_name = 'idna_convert.class'; + } + $domain = $this->idn_converter->encode($domain); + } + } else { + if(function_exists('idn_to_utf8')) { + $domain = idn_to_utf8($domain); + } elseif(file_exists(ISPC_CLASS_PATH.'/idn/idna_convert.class.php')) { + /* use idna class: * @author Matthias Sommerfeld * @copyright 2004-2011 phlyLabs Berlin, http://phlylabs.de * @version 0.8.0 2011-03-11 */ - - if(!is_object($this->idn_converter) || $this->idn_converter_name != 'idna_convert.class') { - include_once(ISPC_CLASS_PATH.'/idn/idna_convert.class.php'); - $this->idn_converter = new idna_convert(array('idn_version' => 2008)); - $this->idn_converter_name = 'idna_convert.class'; - } - $domain = $this->idn_converter->decode($domain); - } - } - - if($user_part !== false) return $user_part . '@' . $domain; - else return $domain; - } - - public function idn_encode($domain) { - $domains = explode("\n", $domain); - for($d = 0; $d < count($domains); $d++) { - $domains[$d] = $this->_idn_encode_decode($domains[$d], true); - } - return implode("\n", $domains); - } - - public function idn_decode($domain) { - $domains = explode("\n", $domain); - for($d = 0; $d < count($domains); $d++) { - $domains[$d] = $this->_idn_encode_decode($domains[$d], false); - } - return implode("\n", $domains); - } - + + if(!is_object($this->idn_converter) || $this->idn_converter_name != 'idna_convert.class') { + include_once ISPC_CLASS_PATH.'/idn/idna_convert.class.php'; + $this->idn_converter = new idna_convert(array('idn_version' => 2008)); + $this->idn_converter_name = 'idna_convert.class'; + } + $domain = $this->idn_converter->decode($domain); + } + } + + if($user_part !== false) return $user_part . '@' . $domain; + else return $domain; + } + + public function idn_encode($domain) { + $domains = explode("\n", $domain); + for($d = 0; $d < count($domains); $d++) { + $domains[$d] = $this->_idn_encode_decode($domains[$d], true); + } + return implode("\n", $domains); + } + + public function idn_decode($domain) { + $domains = explode("\n", $domain); + for($d = 0; $d < count($domains); $d++) { + $domains[$d] = $this->_idn_encode_decode($domains[$d], false); + } + return implode("\n", $domains); + } + } -?> \ No newline at end of file +?> diff --git a/interface/lib/classes/getconf.inc.php b/interface/lib/classes/getconf.inc.php index ad2a30231b1b4e7c31896a9cb4efc80f367f07f9..45fefa601b503a46b57898046183cafd5f96d556 100644 --- a/interface/lib/classes/getconf.inc.php +++ b/interface/lib/classes/getconf.inc.php @@ -31,7 +31,7 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class getconf { private $config; - + public function get_server_config($server_id, $section = '') { global $app; @@ -43,10 +43,10 @@ class getconf { } return ($section == '') ? $this->config[$server_id] : $this->config[$server_id][$section]; } - + public function get_global_config($section = '') { global $app; - + if(!isset($this->config['global'])) { $app->uses('ini_parser'); $tmp = $app->db->queryOneRecord('SELECT config FROM sys_ini WHERE sysini_id = 1'); @@ -54,6 +54,7 @@ class getconf { } return ($section == '') ? $this->config['global'] : $this->config['global'][$section]; } + } ?> diff --git a/interface/lib/classes/importer.inc.php b/interface/lib/classes/importer.inc.php index e74c0993ab4a3b3b003b760d9e929ce9747ee983..f6cbab570cd1ef1b072b8f3bf09876ca3dab31f1 100644 --- a/interface/lib/classes/importer.inc.php +++ b/interface/lib/classes/importer.inc.php @@ -30,56 +30,59 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -require_once(realpath(dirname(__FILE__)) . '/remoting.inc.php'); +require_once realpath(dirname(__FILE__)) . '/remoting.inc.php'; class fakeserver { - private $faultMessage; - private $faultText; - public function fault($message = '', $text = '') { - $this->faultMessage = $message; - $this->faultText = $text; - } - - public function getFault() { - $ret = $this->faultMessage . ' (' . $this->faultText . ')'; - $this->faultMessage = null; - $this->faultText = null; - return $ret; - } + private $faultMessage; + private $faultText; + public function fault($message = '', $text = '') { + $this->faultMessage = $message; + $this->faultText = $text; + } + + public function getFault() { + $ret = $this->faultMessage . ' (' . $this->faultText . ')'; + $this->faultMessage = null; + $this->faultText = null; + return $ret; + } + } class importer extends remoting { public function __construct() - { - $this->server = new fakeserver(); - } + { + $this->server = new fakeserver(); + } //* remote login function - overridden just to make sure it cannot be called from importer scripts public function login($username, $password) - { - + { + } - + //* remote logout function - overridden just to make sure it cannot be called from importer scripts public function logout($session_id) - { - + { + } - + public function getFault() { - return $this->server->getFault(); - } - + return $this->server->getFault(); + } + protected function checkPerm($session_id, $function_name) - { - // always return true as this is used from inside the application not through remote calls - return true; + { + // always return true as this is used from inside the application not through remote calls + return true; } - - + + protected function getSession($session_id) - { + { return array(); // we have no sessions here } + } + ?> diff --git a/interface/lib/classes/ini_parser.inc.php b/interface/lib/classes/ini_parser.inc.php index 6303115753d2f628b4210b84f73a4bfc896eaa3d..b8dffbafa5cd57b316c3d16241ae867abc798fa3 100644 --- a/interface/lib/classes/ini_parser.inc.php +++ b/interface/lib/classes/ini_parser.inc.php @@ -59,8 +59,8 @@ class ini_parser{ $content .= "[$section]\n"; foreach($data as $item => $value) { if($item != ''){ - $value = trim($value); - $item = trim($item); + $value = trim($value); + $item = trim($item); $content .= "$item=$value\n"; } } diff --git a/interface/lib/classes/ispcmail.inc.php b/interface/lib/classes/ispcmail.inc.php index d49af96fc6100135f24ce0078325247382ea2b88..dff71f3b89a70473e7e5f788d8fab4ffede0acb7 100644 --- a/interface/lib/classes/ispcmail.inc.php +++ b/interface/lib/classes/ispcmail.inc.php @@ -30,498 +30,544 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** * email class - * + * * @package pxFramework * */ + + class ispcmail { - - /**#@+ + + /**#@+ * @access private */ - private $html_part; - private $text_part; - - private $headers; - - private $_logged_in = false; - private $_smtp_conn = null; - - private $_crlf = "\n"; - - private $attach_type = 'application/octet-stream'; - private $attachments; - private $mime_boundary; - private $body = ''; - private $_mail_sender = ''; - private $_sent_mails = 0; - private $user_agent = 'ISPConfig/3 (Mailer Class)'; - /**#@-*/ - - /** - * set the mail charset - */ - private $mail_charset = 'UTF-8';//'ISO-8859-1'; - - /**#@+ + private $html_part; + private $text_part; + + private $headers; + + private $_logged_in = false; + private $_smtp_conn = null; + + private $_crlf = "\n"; + + private $attach_type = 'application/octet-stream'; + private $attachments; + private $mime_boundary; + private $body = ''; + private $_mail_sender = ''; + private $_sent_mails = 0; + private $user_agent = 'ISPConfig/3 (Mailer Class)'; + /**#@-*/ + + + + /** + * set the mail charset + */ + private $mail_charset = 'UTF-8';//'ISO-8859-1'; + + /**#@+ * Provide smtp credentials for smtp mail sending * * @access public */ - /** - * if set to true smtp is used instead of mail() to send emails - * @see mail - */ - private $use_smtp = false; - /** - * the smtp helo string - use the mail server name here! - */ - private $smtp_helo = ''; - /** - * the smtp server to send mails - */ - private $smtp_host = ''; - /** - * the smtp port - */ - private $smtp_port = 25; - /** - * if the smtp server needs authentication you can set the smtp user here - */ - private $smtp_user = ''; - /** - * if the smtp server needs authentication you can set the smtp password here - */ - private $smtp_pass = ''; - /** - * If you want to use tls/ssl specify it here - */ - private $smtp_crypt = ''; // tls or ssl - /** - * How many mails should be sent via one single smtp connection - */ - private $smtp_max_mails = 20; - /** - * Should the mail be signed - */ - private $sign_email = false; - /** - * The cert and key to use for email signing - */ - private $sign_key = ''; - private $sign_key_pass = ''; - private $sign_cert = ''; - private $sign_bundle = ''; - private $_is_signed = false; - /** - * get disposition notification - */ - private $notification = false; - /**#@-*/ - - public function __construct($options = array()) { - $rand = md5(microtime()); - $this->mime_boundary = '==Multipart_Boundary_x' . $rand . 'x'; - - $this->headers = array(); - $this->attachments = array(); - - $this->headers['MIME-Version'] = '1.0'; - $this->headers['User-Agent'] = $this->user_agent; - if(is_array($options) && count($options) > 0) $this->setOptions($options); - } - - public function __destruct() { - $this->finish(); - } - - /** - * Set option - * - * @param string $key the option to set - * @param string $value the option value to set - */ - public function setOption($key, $value) { - switch($key) { - case 'smtp_helo': - $this->smtp_helo = $value; - break; - case 'smtp_host': - $this->smtp_host = $value; - break; - case 'smtp_server': - $this->smtp_host = $value; - break; - case 'smtp_port': - $this->smtp_port = $value; - break; - case 'smtp_user': - $this->smtp_user = $value; - break; - case 'smtp_pass': - $this->smtp_pass = $value; - break; - case 'smtp_max_mails': - $this->smtp_max_mails = intval($value); - if($this->smtp_max_mails < 1) $this->smtp_max_mails = 1; - break; - case 'use_smtp': - $this->use_smtp = ($value == true ? true : false); - if($value == true) $this->_crlf = "\r\n"; - break; - case 'smtp_crypt': - if($value != 'ssl' && $value != 'tls') $value = ''; - $this->smtp_crypt = $value; - break; - case 'sign_email': - $this->sign_email = ($value == true ? true : false); - break; - case 'sign_key': - $this->sign_key = $value; - break; - case 'sign_key_pass': - $this->sign_key_pass = $value; - break; - case 'sign_cert': - $this->sign_cert = $value; - break; - case 'sign_bundle': - $this->sign_bundle = $value; - break; - case 'mail_charset': - $this->mail_charset = $value; - break; - case 'notify': - $this->notification = ($value == true ? true : false); - break; - } - } - - /** Detect the helo string if none given - * - */ - private function detectHelo() { - if(isset($_SERVER['HTTP_HOST'])) $this->smtp_helo = $_SERVER['HTTP_HOST']; - elseif(isset($_SERVER['SERVER_NAME'])) $this->smtp_helo = $_SERVER['SERVER_NAME']; - else $this->smtp_helo = php_uname('n'); - if($this->smtp_helo == '') $this->smtp_helo = 'localhost'; - } - - /** - * Set options - * - * @param array $options the options to set as an associative array key => value - */ - public function setOptions($options) { - foreach($options as $key => $value) $this->setOption($key, $value); - } - - /** - * Read a file's contents - * - * Simply gets the file's content - * - * @access public - * @param string $filename name and path of file to read - * @return string file content (can be binary) - */ - public function read_File($filename) { - $content = ''; - - $fp = fopen($filename, 'r'); - if(!$fp) return false; - - while(!feof($fp)) { - $content .= fread($fp, 1024); - } - fclose($fp); - - return $content; - } - - /** - * set smtp connection encryption - * - * @access public - * @param string $mode encryption mode (tls, ssl or empty string) - */ - public function setSMTPEncryption($mode = '') { - if($mode != 'ssl' && $mode != 'tls') $mode = ''; - $this->smtp_crypt = $mode; - } - /** - * set a mail header - * - * Sets a single mail header to a given value - * - * @access public - * @param string $header header name to set - * @param string $value value to set in header field - */ - public function setHeader($header, $value) { - if(strtolower($header) == 'bcc') $header = 'Bcc'; - elseif(strtolower($header) == 'cc') $header = 'Cc'; - elseif(strtolower($header) == 'from') $header = 'From'; - $this->headers["$header"] = $value; - } - - /** - * get a mail header value - * - * Returns a value of a single mail header - * - * @access public - * @param string $header header name to get - * @return string header value - */ - public function getHeader($header) { - if(strtolower($header) == 'bcc') $header = 'Bcc'; - elseif(strtolower($header) == 'cc') $header = 'Cc'; - elseif(strtolower($header) == 'from') $header = 'From'; - return (isset($this->headers["$header"]) ? $this->headers["$header"] : ''); - } - - /** - * Set email sender - * - * Sets the email sender and optionally the sender's name - * - * @access public - * @param string $email sender email address - * @param string $name sender name - */ - public function setSender($email, $name = '') { - if($name) $header = '"' . $name . '" <' . $email . '>'; - else $header = '<' . $email . '>'; - - $this->_mail_sender = $email; - - $this->setHeader('From', $header); - } - - /** - * Set mail subject - * - * @access public - * @param string $subject the mail subject - * @return string where-string for db query - */ - public function setSubject($subject) { - $this->setHeader('Subject', $subject); - } - - /** - * Get current mail subject - * - * @access public - * @return string mail subject - */ - public function getSubject() { - return $this->headers['Subject']; - } - - /** - * Set mail content - * - * Sets the mail html and plain text content - * - * @access public - * @param string $text plain text mail content (can be empty) - * @param string $html html mail content - */ - public function setMailText($text, $html = '') { - $this->text_part = $text; - $this->html_part = $html; - } - - /** - * Read and attach a file - * - * Reads a file and attaches it to the current email - * - * @access public - * @param string $filename the file to read and attach - * @param string $display_name the name that will be displayed in the mail - * @see read_File - */ - public function readAttachFile($filename, $display_name = '') { - if($display_name == '') { - $path_parts = pathinfo($filename); - $display_name = $path_parts["basename"]; - unset($path_parts); - } - $this->attachFile($this->read_File($filename), $display_name); - } - - /** - * Attach a file - * - * Attaches a string (can be binary) as a file to the mail - * - * @access public - * @param string $content attachment data string - * @param string $filename name for file attachment - */ - public function attachFile($content, $filename) { - $attachment = array('content' => $content, - 'filename' => $filename, - 'type' => 'application/octet-stream', - 'encoding' => 'base64' - ); - $this->attachments[] = $attachment; - } - - /** - * @access private - */ - private function create() { - $attach = false; - $html = false; - $text = false; - - if($this->html_part) $html = true; - if($this->text_part) $text = true; - if(count($this->attachments) > 0) $attach = true; - - $textonly = false; - $htmlonly = false; - if($text == true && $html == false && $attach == false) { - // only text - $content_type = 'text/plain; charset="' . strtolower($this->mail_charset) . '"'; - $textonly = true; - } elseif($text == true && $html == false && $attach == true) { - // text and attachment - $content_type = 'multipart/mixed;'; - $content_type .= "\n" . ' boundary="' . $this->mime_boundary . '"'; - } elseif($html == true && $text == true && $attach == false) { - // html only (or text too) - $content_type = 'multipart/alternative;'; - $content_type .= "\n" . ' boundary="' . $this->mime_boundary . '"'; - } elseif($html == true && $text == false && $attach == false) { - // html only (or text too) - $content_type = 'text/html; charset="' . strtolower($this->mail_charset) . '"'; - $htmlonly = true; - } elseif($html == true && $attach == true) { - // html and attachments - $content_type = 'multipart/mixed;'; - $content_type .= "\n" . ' boundary="' . $this->mime_boundary . '"'; - } - - $this->headers['Content-Type'] = $content_type; - - if($textonly == false && $htmlonly == false) { - $this->body = "This is a multi-part message in MIME format.\n\n"; - - if($text) { - /*$this->body .= "--{$this->mime_boundary}\n" . + /** + * if set to true smtp is used instead of mail() to send emails + * @see mail + */ + private $use_smtp = false; + + /** + * the smtp helo string - use the mail server name here! + */ + private $smtp_helo = ''; + + /** + * the smtp server to send mails + */ + private $smtp_host = ''; + + /** + * the smtp port + */ + private $smtp_port = 25; + + /** + * if the smtp server needs authentication you can set the smtp user here + */ + private $smtp_user = ''; + + /** + * if the smtp server needs authentication you can set the smtp password here + */ + private $smtp_pass = ''; + + /** + * If you want to use tls/ssl specify it here + */ + private $smtp_crypt = ''; // tls or ssl + /** + * How many mails should be sent via one single smtp connection + */ + private $smtp_max_mails = 20; + + /** + * Should the mail be signed + */ + private $sign_email = false; + + /** + * The cert and key to use for email signing + */ + private $sign_key = ''; + private $sign_key_pass = ''; + private $sign_cert = ''; + private $sign_bundle = ''; + private $_is_signed = false; + + /** + * get disposition notification + */ + private $notification = false; + /**#@-*/ + + public function __construct($options = array()) { + $rand = md5(microtime()); + $this->mime_boundary = '==Multipart_Boundary_x' . $rand . 'x'; + + $this->headers = array(); + $this->attachments = array(); + + $this->headers['MIME-Version'] = '1.0'; + $this->headers['User-Agent'] = $this->user_agent; + if(is_array($options) && count($options) > 0) $this->setOptions($options); + } + + public function __destruct() { + $this->finish(); + } + + + + /** + * Set option + * + * @param string $key the option to set + * @param string $value the option value to set + */ + public function setOption($key, $value) { + switch($key) { + case 'smtp_helo': + $this->smtp_helo = $value; + break; + case 'smtp_host': + $this->smtp_host = $value; + break; + case 'smtp_server': + $this->smtp_host = $value; + break; + case 'smtp_port': + $this->smtp_port = $value; + break; + case 'smtp_user': + $this->smtp_user = $value; + break; + case 'smtp_pass': + $this->smtp_pass = $value; + break; + case 'smtp_max_mails': + $this->smtp_max_mails = intval($value); + if($this->smtp_max_mails < 1) $this->smtp_max_mails = 1; + break; + case 'use_smtp': + $this->use_smtp = ($value == true ? true : false); + if($value == true) $this->_crlf = "\r\n"; + break; + case 'smtp_crypt': + if($value != 'ssl' && $value != 'tls') $value = ''; + $this->smtp_crypt = $value; + break; + case 'sign_email': + $this->sign_email = ($value == true ? true : false); + break; + case 'sign_key': + $this->sign_key = $value; + break; + case 'sign_key_pass': + $this->sign_key_pass = $value; + break; + case 'sign_cert': + $this->sign_cert = $value; + break; + case 'sign_bundle': + $this->sign_bundle = $value; + break; + case 'mail_charset': + $this->mail_charset = $value; + break; + case 'notify': + $this->notification = ($value == true ? true : false); + break; + } + } + + + + /** Detect the helo string if none given + * + */ + private function detectHelo() { + if(isset($_SERVER['HTTP_HOST'])) $this->smtp_helo = $_SERVER['HTTP_HOST']; + elseif(isset($_SERVER['SERVER_NAME'])) $this->smtp_helo = $_SERVER['SERVER_NAME']; + else $this->smtp_helo = php_uname('n'); + if($this->smtp_helo == '') $this->smtp_helo = 'localhost'; + } + + + + /** + * Set options + * + * @param array $options the options to set as an associative array key => value + */ + public function setOptions($options) { + foreach($options as $key => $value) $this->setOption($key, $value); + } + + + + /** + * Read a file's contents + * + * Simply gets the file's content + * + * @access public + * @param string $filename name and path of file to read + * @return string file content (can be binary) + */ + public function read_File($filename) { + $content = ''; + + $fp = fopen($filename, 'r'); + if(!$fp) return false; + + while(!feof($fp)) { + $content .= fread($fp, 1024); + } + fclose($fp); + + return $content; + } + + + + /** + * set smtp connection encryption + * + * @access public + * @param string $mode encryption mode (tls, ssl or empty string) + */ + public function setSMTPEncryption($mode = '') { + if($mode != 'ssl' && $mode != 'tls') $mode = ''; + $this->smtp_crypt = $mode; + } + + /** + * set a mail header + * + * Sets a single mail header to a given value + * + * @access public + * @param string $header header name to set + * @param string $value value to set in header field + */ + public function setHeader($header, $value) { + if(strtolower($header) == 'bcc') $header = 'Bcc'; + elseif(strtolower($header) == 'cc') $header = 'Cc'; + elseif(strtolower($header) == 'from') $header = 'From'; + $this->headers["$header"] = $value; + } + + + + /** + * get a mail header value + * + * Returns a value of a single mail header + * + * @access public + * @param string $header header name to get + * @return string header value + */ + public function getHeader($header) { + if(strtolower($header) == 'bcc') $header = 'Bcc'; + elseif(strtolower($header) == 'cc') $header = 'Cc'; + elseif(strtolower($header) == 'from') $header = 'From'; + return isset($this->headers["$header"]) ? $this->headers["$header"] : ''; + } + + + + /** + * Set email sender + * + * Sets the email sender and optionally the sender's name + * + * @access public + * @param string $email sender email address + * @param string $name sender name + */ + public function setSender($email, $name = '') { + if($name) $header = '"' . $name . '" <' . $email . '>'; + else $header = '<' . $email . '>'; + + $this->_mail_sender = $email; + + $this->setHeader('From', $header); + } + + + + /** + * Set mail subject + * + * @access public + * @param string $subject the mail subject + * @return string where-string for db query + */ + public function setSubject($subject) { + $this->setHeader('Subject', $subject); + } + + + + /** + * Get current mail subject + * + * @access public + * @return string mail subject + */ + public function getSubject() { + return $this->headers['Subject']; + } + + + + /** + * Set mail content + * + * Sets the mail html and plain text content + * + * @access public + * @param string $text plain text mail content (can be empty) + * @param string $html html mail content + */ + public function setMailText($text, $html = '') { + $this->text_part = $text; + $this->html_part = $html; + } + + + + /** + * Read and attach a file + * + * Reads a file and attaches it to the current email + * + * @access public + * @param string $filename the file to read and attach + * @param string $display_name the name that will be displayed in the mail + * @see read_File + */ + public function readAttachFile($filename, $display_name = '') { + if($display_name == '') { + $path_parts = pathinfo($filename); + $display_name = $path_parts["basename"]; + unset($path_parts); + } + $this->attachFile($this->read_File($filename), $display_name); + } + + + + /** + * Attach a file + * + * Attaches a string (can be binary) as a file to the mail + * + * @access public + * @param string $content attachment data string + * @param string $filename name for file attachment + */ + public function attachFile($content, $filename) { + $attachment = array('content' => $content, + 'filename' => $filename, + 'type' => 'application/octet-stream', + 'encoding' => 'base64' + ); + $this->attachments[] = $attachment; + } + + + + /** + * @access private + */ + private function create() { + $attach = false; + $html = false; + $text = false; + + if($this->html_part) $html = true; + if($this->text_part) $text = true; + if(count($this->attachments) > 0) $attach = true; + + $textonly = false; + $htmlonly = false; + if($text == true && $html == false && $attach == false) { + // only text + $content_type = 'text/plain; charset="' . strtolower($this->mail_charset) . '"'; + $textonly = true; + } elseif($text == true && $html == false && $attach == true) { + // text and attachment + $content_type = 'multipart/mixed;'; + $content_type .= "\n" . ' boundary="' . $this->mime_boundary . '"'; + } elseif($html == true && $text == true && $attach == false) { + // html only (or text too) + $content_type = 'multipart/alternative;'; + $content_type .= "\n" . ' boundary="' . $this->mime_boundary . '"'; + } elseif($html == true && $text == false && $attach == false) { + // html only (or text too) + $content_type = 'text/html; charset="' . strtolower($this->mail_charset) . '"'; + $htmlonly = true; + } elseif($html == true && $attach == true) { + // html and attachments + $content_type = 'multipart/mixed;'; + $content_type .= "\n" . ' boundary="' . $this->mime_boundary . '"'; + } + + $this->headers['Content-Type'] = $content_type; + + if($textonly == false && $htmlonly == false) { + $this->body = "This is a multi-part message in MIME format.\n\n"; + + if($text) { + /*$this->body .= "--{$this->mime_boundary}\n" . "Content-Type:text/plain; charset=\"" . strtolower($this->mail_charset) . "\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $this->text_part . "\n\n";*/ $this->body .= "--{$this->mime_boundary}\n" . - "Content-Type:text/plain; charset=\"UTF-8\"\n" . - "Content-Transfer-Encoding: 8bit\n\n" . $this->text_part . "\n\n"; + "Content-Type:text/plain; charset=\"UTF-8\"\n" . + "Content-Transfer-Encoding: 8bit\n\n" . $this->text_part . "\n\n"; } - - if($html) { - /*$this->body .= "--{$this->mime_boundary}\n" . - "Content-Type:text/html; charset=\"" . strtolower($this->mail_charset) . "\"\n" . + + if($html) { + /*$this->body .= "--{$this->mime_boundary}\n" . + "Content-Type:text/html; charset=\"" . strtolower($this->mail_charset) . "\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $this->html_part . "\n\n";*/ $this->body .= "--{$this->mime_boundary}\n" . - "Content-Type:text/html; charset=\"UTF-8\"\n" . - "Content-Transfer-Encoding: 8bit\n\n" . $this->html_part . "\n\n"; + "Content-Type:text/html; charset=\"UTF-8\"\n" . + "Content-Transfer-Encoding: 8bit\n\n" . $this->html_part . "\n\n"; } - - if($attach) { - foreach($this->attachments as $att) { - $this->body .= "--{$this->mime_boundary}\n" . - "Content-Type: " . $att['type'] . ";\n" . - " name=\"" . $att['filename'] . "\"\n" . - "Content-Transfer-Encoding: base64\n" . - "Content-Disposition: attachment;\n\n" . - chunk_split(base64_encode($att['content'])) . "\n\n"; - } - } - $this->body .= "--{$this->mime_boundary}--\n"; - } elseif($htmlonly == true) { - $this->body = $this->html_part; - } else { - $this->body = $this->text_part; - } - - if (isset($this->body)) { - // Add message ID header - $message_id = sprintf('<%s.%s@%s>', base_convert(time(), 10, 36), base_convert(rand(), 10, 36), $this->smtp_helo != '' ? $this->smtp_helo : $this->detectHelo()); - $this->headers['Message-ID'] = $message_id; - return true; - } else { - return false; - } - } - - /** - * Function to sign an email body - */ - private function sign() { - if($this->sign_email == false || $this->sign_key == '' || $this->sign_cert == '') return false; - if(function_exists('openssl_pkcs7_sign') == false) return false; - - $tmpin = tempnam(sys_get_temp_dir(), 'sign'); - $tmpout = tempnam(sys_get_temp_dir(), 'sign'); - if(!file_exists($tmpin) || !is_writable($tmpin)) return false; - - file_put_contents($tmpin, 'Content-Type: ' . $this->getHeader('Content-Type') . "\n\n" . $this->body); - $tmpf_key = tempnam(sys_get_temp_dir(), 'sign'); - file_put_contents($tmpf_key, $this->sign_key); - $tmpf_cert = tempnam(sys_get_temp_dir(), 'sign'); - file_put_contents($tmpf_cert, $this->sign_cert); - if($this->sign_bundle != '') { - $tmpf_bundle = tempnam(sys_get_temp_dir(), 'sign'); - file_put_contents($tmpf_bundle, $this->sign_bundle); - openssl_pkcs7_sign($tmpin, $tmpout, 'file://' . realpath($tmpf_cert), array('file://' . realpath($tmpf_key), $this->sign_key_pass), array(), PKCS7_DETACHED, realpath($tmpf_bundle)); - } else { - openssl_pkcs7_sign($tmpin, $tmpout, 'file://' . realpath($tmpf_cert), array('file://' . realpath($tmpf_key), $this->sign_key_pass), array()); - } - unlink($tmpin); - unlink($tmpf_cert); - unlink($tmpf_key); - if(file_exists($tmpf_bundle)) unlink($tmpf_bundle); - - if(!file_exists($tmpout) || !is_readable($tmpout)) return false; - $this->body = file_get_contents($tmpout); - unlink($tmpout); - - unset($this->headers['Content-Type']); - unset($this->headers['MIME-Version']); - - $this->_is_signed = true; - } - - private function _char_to_hex($matches) { - return '=' . strtoupper(dechex(ord($matches[1]))); - } - - /** - * Function to encode a header if necessary - * according to RFC2047 - * @access private - */ - private function _encodeHeader($input, $charset = 'ISO-8859-1') { + + if($attach) { + foreach($this->attachments as $att) { + $this->body .= "--{$this->mime_boundary}\n" . + "Content-Type: " . $att['type'] . ";\n" . + " name=\"" . $att['filename'] . "\"\n" . + "Content-Transfer-Encoding: base64\n" . + "Content-Disposition: attachment;\n\n" . + chunk_split(base64_encode($att['content'])) . "\n\n"; + } + } + $this->body .= "--{$this->mime_boundary}--\n"; + } elseif($htmlonly == true) { + $this->body = $this->html_part; + } else { + $this->body = $this->text_part; + } + + if (isset($this->body)) { + // Add message ID header + $message_id = sprintf('<%s.%s@%s>', base_convert(time(), 10, 36), base_convert(rand(), 10, 36), $this->smtp_helo != '' ? $this->smtp_helo : $this->detectHelo()); + $this->headers['Message-ID'] = $message_id; + return true; + } else { + return false; + } + } + + + + /** + * Function to sign an email body + */ + private function sign() { + if($this->sign_email == false || $this->sign_key == '' || $this->sign_cert == '') return false; + if(function_exists('openssl_pkcs7_sign') == false) return false; + + $tmpin = tempnam(sys_get_temp_dir(), 'sign'); + $tmpout = tempnam(sys_get_temp_dir(), 'sign'); + if(!file_exists($tmpin) || !is_writable($tmpin)) return false; + + file_put_contents($tmpin, 'Content-Type: ' . $this->getHeader('Content-Type') . "\n\n" . $this->body); + $tmpf_key = tempnam(sys_get_temp_dir(), 'sign'); + file_put_contents($tmpf_key, $this->sign_key); + $tmpf_cert = tempnam(sys_get_temp_dir(), 'sign'); + file_put_contents($tmpf_cert, $this->sign_cert); + if($this->sign_bundle != '') { + $tmpf_bundle = tempnam(sys_get_temp_dir(), 'sign'); + file_put_contents($tmpf_bundle, $this->sign_bundle); + openssl_pkcs7_sign($tmpin, $tmpout, 'file://' . realpath($tmpf_cert), array('file://' . realpath($tmpf_key), $this->sign_key_pass), array(), PKCS7_DETACHED, realpath($tmpf_bundle)); + } else { + openssl_pkcs7_sign($tmpin, $tmpout, 'file://' . realpath($tmpf_cert), array('file://' . realpath($tmpf_key), $this->sign_key_pass), array()); + } + unlink($tmpin); + unlink($tmpf_cert); + unlink($tmpf_key); + if(file_exists($tmpf_bundle)) unlink($tmpf_bundle); + + if(!file_exists($tmpout) || !is_readable($tmpout)) return false; + $this->body = file_get_contents($tmpout); + unlink($tmpout); + + unset($this->headers['Content-Type']); + unset($this->headers['MIME-Version']); + + $this->_is_signed = true; + } + + private function _char_to_hex($matches) { + return '=' . strtoupper(dechex(ord($matches[1]))); + } + + + + /** + * Function to encode a header if necessary + * according to RFC2047 + * @access private + */ + private function _encodeHeader($input, $charset = 'ISO-8859-1') { preg_match_all('/(\s?\w*[\x80-\xFF]+\w*\s?)/', $input, $matches); foreach ($matches[1] as $value) { $replacement = preg_replace_callback('/([\x20\x80-\xFF])/', array($this, '_char_to_hex'), $value); $input = str_replace($value, '=?' . $charset . '?Q?' . $replacement . '?=', $input); } - - return $input; - } - - /** - * Function to encode the subject if necessary - * according to RFC2047 - * @access private - */ - private function _encodeSubject($input, $charset = 'ISO-8859-1') { - /* + + return $input; + } + + + + /** + * Function to encode the subject if necessary + * according to RFC2047 + * @access private + */ + private function _encodeSubject($input, $charset = 'ISO-8859-1') { + /* if($charset == 'UTF-8' && function_exists('imap_8bit')) { $input = "=?utf-8?Q?" . imap_8bit($input) . "?="; } else { @@ -532,204 +578,213 @@ class ispcmail { } }*/ $input='=?UTF-8?B?'.base64_encode($input).'?='; - - return $input; - } - - /** - * @access private - */ - private function _smtp_login() { - $this->_smtp_conn = fsockopen(($this->smtp_crypt == 'ssl' ? 'ssl://' : '') . $this->smtp_host, $this->smtp_port, $errno, $errstr, 30); - $response = fgets($this->_smtp_conn, 515); - if(empty($this->_smtp_conn)) return false; - - // ENCRYPTED? - if($this->smtp_crypt == 'tls') { - fputs($this->_smtp_conn, 'STARTTLS' . $this->_crlf); - fgets($this->_smtp_conn, 515); - stream_socket_enable_crypto($this->_smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); - } - - //Say Hello to SMTP - if($this->smtp_helo == '') $this->detectHelo(); - fputs($this->_smtp_conn, 'HELO ' . $this->smtp_helo . $this->_crlf); - $response = fgets($this->_smtp_conn, 515); - - //AUTH LOGIN - fputs($this->_smtp_conn, 'AUTH LOGIN' . $this->_crlf); - $response = fgets($this->_smtp_conn, 515); - - //Send username - fputs($this->_smtp_conn, base64_encode($this->smtp_user) . $this->_crlf); - $response = fgets($this->_smtp_conn, 515); - - //Send password - fputs($this->_smtp_conn, base64_encode($this->smtp_pass) . $this->_crlf); - $response = fgets($this->_smtp_conn, 515); - - $this->_logged_in = true; - return true; - } - - /** - * @access private - */ - private function _smtp_close() { - $this->_logged_in = false; - - if(empty($this->_smtp_conn)) { - return false; - } - - fputs($this->_smtp_conn, 'QUIT' . $this->_crlf); - $response = @fgets($this->_smtp_conn, 515); - return true; - } - - /** - * Send the mail to one or more recipients - * - * The recipients can be either a string (1 recipient email without name) or an associative array of recipients with names as keys and email addresses as values. - * - * @access public - * @param mixed $recipients one email address or array of recipients with names as keys and email addresses as values - */ - public function send($recipients) { - if(!is_array($recipients)) $recipients = array($recipients); - - if($this->use_smtp == true) $this->_crlf = "\r\n"; - else $this->_crlf = "\n"; - - $this->create(); - if($this->sign_email == true) $this->sign(); - - $subject = ''; - if (!empty($this->headers['Subject'])) { - //$subject = $this->_encodeHeader($this->headers['Subject'], $this->mail_charset); - $subject = $this->headers['Subject']; - - //$enc_subject = $this->_encodeHeader($subject, $this->mail_charset); + + return $input; + } + + + + /** + * @access private + */ + private function _smtp_login() { + $this->_smtp_conn = fsockopen(($this->smtp_crypt == 'ssl' ? 'ssl://' : '') . $this->smtp_host, $this->smtp_port, $errno, $errstr, 30); + $response = fgets($this->_smtp_conn, 515); + if(empty($this->_smtp_conn)) return false; + + // ENCRYPTED? + if($this->smtp_crypt == 'tls') { + fputs($this->_smtp_conn, 'STARTTLS' . $this->_crlf); + fgets($this->_smtp_conn, 515); + stream_socket_enable_crypto($this->_smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT); + } + + //Say Hello to SMTP + if($this->smtp_helo == '') $this->detectHelo(); + fputs($this->_smtp_conn, 'HELO ' . $this->smtp_helo . $this->_crlf); + $response = fgets($this->_smtp_conn, 515); + + //AUTH LOGIN + fputs($this->_smtp_conn, 'AUTH LOGIN' . $this->_crlf); + $response = fgets($this->_smtp_conn, 515); + + //Send username + fputs($this->_smtp_conn, base64_encode($this->smtp_user) . $this->_crlf); + $response = fgets($this->_smtp_conn, 515); + + //Send password + fputs($this->_smtp_conn, base64_encode($this->smtp_pass) . $this->_crlf); + $response = fgets($this->_smtp_conn, 515); + + $this->_logged_in = true; + return true; + } + + + + /** + * @access private + */ + private function _smtp_close() { + $this->_logged_in = false; + + if(empty($this->_smtp_conn)) { + return false; + } + + fputs($this->_smtp_conn, 'QUIT' . $this->_crlf); + $response = @fgets($this->_smtp_conn, 515); + return true; + } + + + + /** + * Send the mail to one or more recipients + * + * The recipients can be either a string (1 recipient email without name) or an associative array of recipients with names as keys and email addresses as values. + * + * @access public + * @param mixed $recipients one email address or array of recipients with names as keys and email addresses as values + */ + public function send($recipients) { + if(!is_array($recipients)) $recipients = array($recipients); + + if($this->use_smtp == true) $this->_crlf = "\r\n"; + else $this->_crlf = "\n"; + + $this->create(); + if($this->sign_email == true) $this->sign(); + + $subject = ''; + if (!empty($this->headers['Subject'])) { + //$subject = $this->_encodeHeader($this->headers['Subject'], $this->mail_charset); + $subject = $this->headers['Subject']; + + //$enc_subject = $this->_encodeHeader($subject, $this->mail_charset); $enc_subject = $this->_encodeSubject($subject, $this->mail_charset); - unset($this->headers['Subject']); - } - - if($this->notification == true) $this->setHeader('Disposition-Notification-To', $this->getHeader('From')); - - unset($this->headers['To']); // always reset the To header to prevent from sending to multiple users at once - $this->headers['Date'] = date('r'); //date('D, d M Y H:i:s O'); - - // Get flat representation of headers - foreach ($this->headers as $name => $value) { - if(strtolower($name) == 'to' || strtolower($name) == 'cc' || strtolower($name) == 'bcc') continue; // never add the To header - $headers[] = $name . ': ' . $this->_encodeHeader($value, $this->mail_charset); - } - - if($this->use_smtp == true) { - if(!$this->_logged_in || !$this->_smtp_conn) { - $result = $this->_smtp_login(); - if(!$result) return false; - } - foreach($recipients as $recipname => $recip) { - if($this->_sent_mails >= $this->smtp_max_mails) { - // close connection to smtp and reconnect - $this->_sent_mails = 0; - $this->_smtp_close(); - $result = $this->_smtp_login(); - if(!$result) return false; - } - $this->_sent_mails += 1; - - $recipname = trim(str_replace('"', '', $recipname)); - $recip = $this->_encodeHeader($recip, $this->mail_charset); - $recipname = $this->_encodeHeader($recipname, $this->mail_charset); - - //Email From - fputs($this->_smtp_conn, 'MAIL FROM: ' . $this->_mail_sender . $this->_crlf); - $response = fgets($this->_smtp_conn, 515); - - //Email To - fputs($this->_smtp_conn, 'RCPT TO: ' . $recip . $this->_crlf); - $response = fgets($this->_smtp_conn, 515); - - //The Email - fputs($this->_smtp_conn, 'DATA' . $this->_crlf); - $response = fgets($this->_smtp_conn, 515); - - //Construct Headers - if($recipname && !is_numeric($recipname)) $this->setHeader('To', $recipname . ' <' . $recip . '>'); - else $this->setHeader('To', $recip); - - $mail_content = 'Subject: ' . $enc_subject . $this->_crlf; - $mail_content .= 'To: ' . $this->getHeader('To') . $this->_crlf; - if($this->getHeader('Bcc') != '') $mail_content .= 'Bcc: ' . $this->_encodeHeader($this->getHeader('Bcc'), $this->mail_charset) . $this->_crlf; - if($this->getHeader('Cc') != '') $mail_content .= 'Cc: ' . $this->_encodeHeader($this->getHeader('Cc'), $this->mail_charset) . $this->_crlf; - $mail_content .= implode($this->_crlf, $headers) . $this->_crlf . ($this->_is_signed == false ? $this->_crlf : '') . $this->body; - - fputs($this->_smtp_conn, $mail_content . $this->_crlf . '.' . $this->_crlf); - $response = fgets($this->_smtp_conn, 515); - - // hopefully message was correctly sent now - $result = true; - } - } else { - if($this->getHeader('Bcc') != '') $headers[] = 'Bcc: ' . $this->_encodeHeader($this->getHeader('Bcc'), $this->mail_charset); - if($this->getHeader('Cc') != '') $headers[] = 'Cc: ' . $this->_encodeHeader($this->getHeader('Cc'), $this->mail_charset); - $rec_string = ''; - foreach($recipients as $recipname => $recip) { - $recipname = trim(str_replace('"', '', $recipname)); - - if($rec_string != '') $rec_string .= ', '; - if($recipname && !is_numeric($recipname)) $rec_string .= $recipname . '<' . $recip . '>'; - else $rec_string .= $recip; - } - $to = $this->_encodeHeader($rec_string, $this->mail_charset); - //$result = mail($to, $subject, $this->body, implode($this->_crlf, $headers)); + unset($this->headers['Subject']); + } + + if($this->notification == true) $this->setHeader('Disposition-Notification-To', $this->getHeader('From')); + + unset($this->headers['To']); // always reset the To header to prevent from sending to multiple users at once + $this->headers['Date'] = date('r'); //date('D, d M Y H:i:s O'); + + // Get flat representation of headers + foreach ($this->headers as $name => $value) { + if(strtolower($name) == 'to' || strtolower($name) == 'cc' || strtolower($name) == 'bcc') continue; // never add the To header + $headers[] = $name . ': ' . $this->_encodeHeader($value, $this->mail_charset); + } + + if($this->use_smtp == true) { + if(!$this->_logged_in || !$this->_smtp_conn) { + $result = $this->_smtp_login(); + if(!$result) return false; + } + foreach($recipients as $recipname => $recip) { + if($this->_sent_mails >= $this->smtp_max_mails) { + // close connection to smtp and reconnect + $this->_sent_mails = 0; + $this->_smtp_close(); + $result = $this->_smtp_login(); + if(!$result) return false; + } + $this->_sent_mails += 1; + + $recipname = trim(str_replace('"', '', $recipname)); + $recip = $this->_encodeHeader($recip, $this->mail_charset); + $recipname = $this->_encodeHeader($recipname, $this->mail_charset); + + //Email From + fputs($this->_smtp_conn, 'MAIL FROM: ' . $this->_mail_sender . $this->_crlf); + $response = fgets($this->_smtp_conn, 515); + + //Email To + fputs($this->_smtp_conn, 'RCPT TO: ' . $recip . $this->_crlf); + $response = fgets($this->_smtp_conn, 515); + + //The Email + fputs($this->_smtp_conn, 'DATA' . $this->_crlf); + $response = fgets($this->_smtp_conn, 515); + + //Construct Headers + if($recipname && !is_numeric($recipname)) $this->setHeader('To', $recipname . ' <' . $recip . '>'); + else $this->setHeader('To', $recip); + + $mail_content = 'Subject: ' . $enc_subject . $this->_crlf; + $mail_content .= 'To: ' . $this->getHeader('To') . $this->_crlf; + if($this->getHeader('Bcc') != '') $mail_content .= 'Bcc: ' . $this->_encodeHeader($this->getHeader('Bcc'), $this->mail_charset) . $this->_crlf; + if($this->getHeader('Cc') != '') $mail_content .= 'Cc: ' . $this->_encodeHeader($this->getHeader('Cc'), $this->mail_charset) . $this->_crlf; + $mail_content .= implode($this->_crlf, $headers) . $this->_crlf . ($this->_is_signed == false ? $this->_crlf : '') . $this->body; + + fputs($this->_smtp_conn, $mail_content . $this->_crlf . '.' . $this->_crlf); + $response = fgets($this->_smtp_conn, 515); + + // hopefully message was correctly sent now + $result = true; + } + } else { + if($this->getHeader('Bcc') != '') $headers[] = 'Bcc: ' . $this->_encodeHeader($this->getHeader('Bcc'), $this->mail_charset); + if($this->getHeader('Cc') != '') $headers[] = 'Cc: ' . $this->_encodeHeader($this->getHeader('Cc'), $this->mail_charset); + $rec_string = ''; + foreach($recipients as $recipname => $recip) { + $recipname = trim(str_replace('"', '', $recipname)); + + if($rec_string != '') $rec_string .= ', '; + if($recipname && !is_numeric($recipname)) $rec_string .= $recipname . '<' . $recip . '>'; + else $rec_string .= $recip; + } + $to = $this->_encodeHeader($rec_string, $this->mail_charset); + //$result = mail($to, $subject, $this->body, implode($this->_crlf, $headers)); $result = mail($to, $enc_subject, $this->body, implode($this->_crlf, $headers)); - } - - // Reset the subject in case mail is resent - if ($subject !== '') { - $this->headers['Subject'] = $subject; - } - - // Return - return $result; - } - - /** - * Close mail connections - * - * This closes an open smtp connection so you should always call this function in your script if you have finished sending all emails - * - * @access public - */ - public function finish() { - if($this->use_smtp == true) $this->_smtp_close(); - - $rand = md5(microtime()); - $this->mime_boundary = '==Multipart_Boundary_x' . $rand . 'x'; - - $this->headers = array(); - $this->attachments = array(); - $this->text_part = ''; - $this->html_part = ''; - - $this->headers['MIME-Version'] = '1.0'; - $this->headers['User-Agent'] = $this->user_agent; - - $this->smtp_helo = ''; - $this->smtp_host = ''; - $this->smtp_port = ''; - $this->smtp_user = ''; - $this->smtp_pass = ''; - $this->use_smtp = false; - $this->smtp_crypt = false; - $this->mail_charset = 'UTF-8'; - $this->_sent_mails = 0; - - return; - } + } + + // Reset the subject in case mail is resent + if ($subject !== '') { + $this->headers['Subject'] = $subject; + } + + // Return + return $result; + } + + + + /** + * Close mail connections + * + * This closes an open smtp connection so you should always call this function in your script if you have finished sending all emails + * + * @access public + */ + public function finish() { + if($this->use_smtp == true) $this->_smtp_close(); + + $rand = md5(microtime()); + $this->mime_boundary = '==Multipart_Boundary_x' . $rand . 'x'; + + $this->headers = array(); + $this->attachments = array(); + $this->text_part = ''; + $this->html_part = ''; + + $this->headers['MIME-Version'] = '1.0'; + $this->headers['User-Agent'] = $this->user_agent; + + $this->smtp_helo = ''; + $this->smtp_host = ''; + $this->smtp_port = ''; + $this->smtp_user = ''; + $this->smtp_pass = ''; + $this->use_smtp = false; + $this->smtp_crypt = false; + $this->mail_charset = 'UTF-8'; + $this->_sent_mails = 0; + + return; + } + } ?> diff --git a/interface/lib/classes/listform.inc.php b/interface/lib/classes/listform.inc.php index cf8f6410f415b18acc94e713735c9719db4086f7..14c1a13f75fa2e5a2d59bd4e3a7dcc6eb4438eef 100644 --- a/interface/lib/classes/listform.inc.php +++ b/interface/lib/classes/listform.inc.php @@ -30,158 +30,160 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class listform { - private $debug = 0; - private $errorMessage; - public $listDef; - public $searchValues; - public $pagingHTML; - private $pagingValues; - private $searchChanged = 0; - private $module; + private $debug = 0; + private $errorMessage; + public $listDef; + public $searchValues; + public $pagingHTML; + private $pagingValues; + private $searchChanged = 0; + private $module; public $wordbook; - public function loadListDef($file, $module = '') - { - global $app,$conf; - if(!is_file($file)){ - die("List-Definition: $file not found."); - } - require_once($file); - $this->listDef = $liste; - $this->module = $module; - + public function loadListDef($file, $module = '') + { + global $app, $conf; + if(!is_file($file)){ + die("List-Definition: $file not found."); + } + require_once $file; + $this->listDef = $liste; + $this->module = $module; + //* Fill datasources - if(@is_array($this->listDef['item'])) { - foreach($this->listDef['item'] as $key => $field) { - if(@is_array($field['datasource'])) { - $this->listDef['item'][$key]['value'] = $this->getDatasourceData($field); - } - } + if(@is_array($this->listDef['item'])) { + foreach($this->listDef['item'] as $key => $field) { + if(@is_array($field['datasource'])) { + $this->listDef['item'][$key]['value'] = $this->getDatasourceData($field); + } + } } - + //* Set local Language File $lng_file = 'lib/lang/'.$_SESSION['s']['language'].'_'.$this->listDef['name'].'_list.lng'; if(!file_exists($lng_file)) $lng_file = 'lib/lang/en_'.$this->listDef['name'].'_list.lng'; - include($lng_file); - + include $lng_file; + $this->wordbook = $wb; - - return true; - } - + + return true; + } + /** - * Get the key => value array of a form filed from a datasource definitiom - * - * @param field = array with field definition - * @param record = Dataset as array - * @return array key => value array for the value field of a form - */ - private function getDatasourceData($field) - { - global $app; - $values = array(); - - if($field['datasource']['type'] == 'SQL') { - - //** Preparing SQL string. We will replace some common placeholders - $querystring = $field['datasource']['querystring']; - $querystring = str_replace('{USERID}', $_SESSION['s']['user']['userid'], $querystring); - $querystring = str_replace('{GROUPID}', $_SESSION['s']['user']['default_group'], $querystring); - $querystring = str_replace('{GROUPS}', $_SESSION['s']['user']['groups'], $querystring); - //TODO: - //$table_idx = $this->formDef['db_table_idx']; - //$querystring = str_replace("{RECORDID}",$record[$table_idx],$querystring); + * Get the key => value array of a form filed from a datasource definitiom + * + * @param field = array with field definition + * @param record = Dataset as array + * @return array key => value array for the value field of a form + */ + + + private function getDatasourceData($field) + { + global $app; + $values = array(); + + if($field['datasource']['type'] == 'SQL') { + + //** Preparing SQL string. We will replace some common placeholders + $querystring = $field['datasource']['querystring']; + $querystring = str_replace('{USERID}', $_SESSION['s']['user']['userid'], $querystring); + $querystring = str_replace('{GROUPID}', $_SESSION['s']['user']['default_group'], $querystring); + $querystring = str_replace('{GROUPS}', $_SESSION['s']['user']['groups'], $querystring); + //TODO: + //$table_idx = $this->formDef['db_table_idx']; + //$querystring = str_replace("{RECORDID}",$record[$table_idx],$querystring); $app->uses('tform'); - $querystring = str_replace("{AUTHSQL}",$app->tform->getAuthSQL('r'),$querystring); - $querystring = str_replace("{AUTHSQL-A}",$app->tform->getAuthSQL('r','a'),$querystring); - $querystring = str_replace("{AUTHSQL-B}",$app->tform->getAuthSQL('r','b'),$querystring); - - //* Getting the records - $tmp_records = $app->db->queryAllRecords($querystring); - if($app->db->errorMessage != '') die($app->db->errorMessage); - if(is_array($tmp_records)) { - $key_field = $field['datasource']['keyfield']; - $value_field = $field['datasource']['valuefield']; - foreach($tmp_records as $tmp_rec) { - $tmp_id = $tmp_rec[$key_field]; - $values[$tmp_id] = $tmp_rec[$value_field]; - } - } - } - - if($field['datasource']['type'] == 'CUSTOM') { - //* Calls a custom class to validate this record - if($field['datasource']['class'] != '' and $field['datasource']['function'] != '') { - $datasource_class = $field['datasource']['class']; - $datasource_function = $field['datasource']['function']; - $app->uses($datasource_class); + $querystring = str_replace("{AUTHSQL}", $app->tform->getAuthSQL('r'), $querystring); + $querystring = str_replace("{AUTHSQL-A}", $app->tform->getAuthSQL('r', 'a'), $querystring); + $querystring = str_replace("{AUTHSQL-B}", $app->tform->getAuthSQL('r', 'b'), $querystring); + + //* Getting the records + $tmp_records = $app->db->queryAllRecords($querystring); + if($app->db->errorMessage != '') die($app->db->errorMessage); + if(is_array($tmp_records)) { + $key_field = $field['datasource']['keyfield']; + $value_field = $field['datasource']['valuefield']; + foreach($tmp_records as $tmp_rec) { + $tmp_id = $tmp_rec[$key_field]; + $values[$tmp_id] = $tmp_rec[$value_field]; + } + } + } + + if($field['datasource']['type'] == 'CUSTOM') { + //* Calls a custom class to validate this record + if($field['datasource']['class'] != '' and $field['datasource']['function'] != '') { + $datasource_class = $field['datasource']['class']; + $datasource_function = $field['datasource']['function']; + $app->uses($datasource_class); $record = array(); - $values = $app->$datasource_class->$datasource_function($field, $record); - } else { - $this->errorMessage .= "Custom datasource class or function is empty
\r\n"; - } - } - return $values; - } - - public function getSearchSQL($sql_where = '') - { - global $app, $db; - - //* Get config variable - $list_name = $this->listDef['name']; - $search_prefix = $this->listDef['search_prefix']; - + $values = $app->$datasource_class->$datasource_function($field, $record); + } else { + $this->errorMessage .= "Custom datasource class or function is empty
\r\n"; + } + } + return $values; + } + + public function getSearchSQL($sql_where = '') + { + global $app, $db; + + //* Get config variable + $list_name = $this->listDef['name']; + $search_prefix = $this->listDef['search_prefix']; + if(isset($_REQUEST['Filter']) && !isset($_SESSION['search'][$list_name])) { //* Jump back to page 1 of the list when a new search gets started. $_SESSION['search'][$list_name]['page'] = 0; } - //* store retrieval query - if(@is_array($this->listDef['item'])) { - foreach($this->listDef['item'] as $i) { - $field = $i['field']; - - //* The search string has been changed - if(isset($_REQUEST[$search_prefix.$field]) && isset($_SESSION['search'][$list_name][$search_prefix.$field]) && $_REQUEST[$search_prefix.$field] != $_SESSION['search'][$list_name][$search_prefix.$field]){ - $this->searchChanged = 1; - - //* Jump back to page 1 of the list when search has changed. - $_SESSION['search'][$list_name]['page'] = 0; - } - - //* Store field in session - if(isset($_REQUEST[$search_prefix.$field]) && !stristr($_REQUEST[$search_prefix.$field],"'")){ - $_SESSION['search'][$list_name][$search_prefix.$field] = $_REQUEST[$search_prefix.$field]; + //* store retrieval query + if(@is_array($this->listDef['item'])) { + foreach($this->listDef['item'] as $i) { + $field = $i['field']; + + //* The search string has been changed + if(isset($_REQUEST[$search_prefix.$field]) && isset($_SESSION['search'][$list_name][$search_prefix.$field]) && $_REQUEST[$search_prefix.$field] != $_SESSION['search'][$list_name][$search_prefix.$field]){ + $this->searchChanged = 1; + + //* Jump back to page 1 of the list when search has changed. + $_SESSION['search'][$list_name]['page'] = 0; + } + + //* Store field in session + if(isset($_REQUEST[$search_prefix.$field]) && !stristr($_REQUEST[$search_prefix.$field], "'")){ + $_SESSION['search'][$list_name][$search_prefix.$field] = $_REQUEST[$search_prefix.$field]; if(preg_match("/['\\\\]/", $_SESSION['search'][$list_name][$search_prefix.$field])) $_SESSION['search'][$list_name][$search_prefix.$field] = ''; } - if(isset($i['formtype']) && $i['formtype'] == 'SELECT'){ - if(is_array($i['value'])) { - $out = ''; - foreach($i['value'] as $k => $v) { - // TODO: this could be more elegant - $selected = (isset($_SESSION['search'][$list_name][$search_prefix.$field]) - && $k == $_SESSION['search'][$list_name][$search_prefix.$field] - && $_SESSION['search'][$list_name][$search_prefix.$field] != '') - ? ' SELECTED' : ''; - $out .= "\r\n"; - } - } - $this->searchValues[$search_prefix.$field] = $out; - } else { - if(isset($_SESSION['search'][$list_name][$search_prefix.$field])){ - $this->searchValues[$search_prefix.$field] = htmlspecialchars($_SESSION['search'][$list_name][$search_prefix.$field]); - } - } - } - } - //* Store variables in object | $this->searchValues = $_SESSION["search"][$list_name]; - if(@is_array($this->listDef['item'])) { - foreach($this->listDef['item'] as $i) { - $field = $i['field']; + if(isset($i['formtype']) && $i['formtype'] == 'SELECT'){ + if(is_array($i['value'])) { + $out = ''; + foreach($i['value'] as $k => $v) { + // TODO: this could be more elegant + $selected = (isset($_SESSION['search'][$list_name][$search_prefix.$field]) + && $k == $_SESSION['search'][$list_name][$search_prefix.$field] + && $_SESSION['search'][$list_name][$search_prefix.$field] != '') + ? ' SELECTED' : ''; + $out .= "\r\n"; + } + } + $this->searchValues[$search_prefix.$field] = $out; + } else { + if(isset($_SESSION['search'][$list_name][$search_prefix.$field])){ + $this->searchValues[$search_prefix.$field] = htmlspecialchars($_SESSION['search'][$list_name][$search_prefix.$field]); + } + } + } + } + //* Store variables in object | $this->searchValues = $_SESSION["search"][$list_name]; + if(@is_array($this->listDef['item'])) { + foreach($this->listDef['item'] as $i) { + $field = $i['field']; $table = $i['table']; - + $searchval = $_SESSION['search'][$list_name][$search_prefix.$field]; // format user date format to MySQL date format 0000-00-00 if($i['datatype'] == 'DATE' && $this->lng('conf_format_dateshort') != 'Y-m-d'){ @@ -189,15 +191,15 @@ class listform { $yearpos = strpos($dateformat, 'Y') + 1; $monthpos = strpos($dateformat, 'm') + 1; $daypos = strpos($dateformat, 'd') + 1; - - $full_date_trans = array ('Y' => '((?:19|20)\d\d)', - 'm' => '(0[1-9]|1[012])', - 'd' => '(0[1-9]|[12][0-9]|3[01])' - ); - // d.m.Y Y/m/d + + $full_date_trans = array ('Y' => '((?:19|20)\d\d)', + 'm' => '(0[1-9]|1[012])', + 'd' => '(0[1-9]|[12][0-9]|3[01])' + ); + // d.m.Y Y/m/d $full_date_regex = strtr(preg_replace("@[^Ymd]@", "[^0-9]", $this->lng('conf_format_dateshort')), $full_date_trans); //echo $full_date_regex; - + if (preg_match("@^\d+$@", $_SESSION['search'][$list_name][$search_prefix.$field])) { // we just have digits $searchval = $_SESSION['search'][$list_name][$search_prefix.$field]; } elseif(preg_match("@^[^0-9]?\d+[^0-9]?$@", $_SESSION['search'][$list_name][$search_prefix.$field])){ // 10. or .10. @@ -212,8 +214,8 @@ class listform { $searchval = $year.'-'.$month; } elseif(preg_match("@^[^0-9]?(\d{1,2})[^0-9](\d{1,2})[^0-9]?$@", $_SESSION['search'][$list_name][$search_prefix.$field], $matches)){ // 04.10. if($monthpos < $daypos){ - $month = $matches[1]; - $day = $matches[2]; + $month = $matches[1]; + $day = $matches[2]; } else { $month = $matches[2]; $day = $matches[1]; @@ -227,332 +229,332 @@ class listform { $searchval = $year.'-'.$month.'-'.$day; } } - - // if($_REQUEST[$search_prefix.$field] != '') $sql_where .= " $field ".$i["op"]." '".$i["prefix"].$_REQUEST[$search_prefix.$field].$i["suffix"]."' and"; - if(isset($searchval) && $searchval != ''){ - $sql_where .= " ".($table != ''? $table.'.' : $this->listDef['table'].'.')."$field ".$i['op']." '".$app->db->quote($i['prefix'].$searchval.$i['suffix'])."' and"; - } - } - } - return ( $sql_where != '' ) ? $sql_where = substr($sql_where,0,-3) : '1'; - } - + + // if($_REQUEST[$search_prefix.$field] != '') $sql_where .= " $field ".$i["op"]." '".$i["prefix"].$_REQUEST[$search_prefix.$field].$i["suffix"]."' and"; + if(isset($searchval) && $searchval != ''){ + $sql_where .= " ".($table != ''? $table.'.' : $this->listDef['table'].'.')."$field ".$i['op']." '".$app->db->quote($i['prefix'].$searchval.$i['suffix'])."' and"; + } + } + } + return ( $sql_where != '' ) ? $sql_where = substr($sql_where, 0, -3) : '1'; + } + public function getPagingValue($key) { if(!is_array($this->pagingValues)) return null; if(!array_key_exists($key, $this->pagingValues)) return null; return $this->pagingValues[$key]; } - - public function getPagingSQL($sql_where = '1') - { - global $app, $conf; - + + public function getPagingSQL($sql_where = '1') + { + global $app, $conf; + //* Add Global Limit from selectbox - if(!empty($_POST['search_limit']) AND $app->functions->intval($_POST['search_limit']) > 0){ + if(!empty($_POST['search_limit']) and $app->functions->intval($_POST['search_limit']) > 0){ $_SESSION['search']['limit'] = $app->functions->intval($_POST['search_limit']); } - + //if(preg_match('{^[0-9]$}',$_SESSION['search']['limit'])){ - // $_SESSION['search']['limit'] = 15; + // $_SESSION['search']['limit'] = 15; //} if(intval($_SESSION['search']['limit']) < 1) $_SESSION['search']['limit'] = 15; - //* Get Config variables - $list_name = $this->listDef['name']; - $search_prefix = $this->listDef['search_prefix']; - $records_per_page = (empty($_SESSION['search']['limit']) ? $app->functions->intval($this->listDef['records_per_page']) : $app->functions->intval($_SESSION['search']['limit'])) ; - $table = $this->listDef['table']; - - //* set PAGE to zero, if in session not set - if(!isset($_SESSION['search'][$list_name]['page']) || $_SESSION['search'][$list_name]['page'] == ''){ - $_SESSION['search'][$list_name]['page'] = 0; - } - - //* set PAGE to worth request variable "PAGE" - ? setze page auf wert der request variablen "page" - if(isset($_REQUEST["page"])) $_SESSION["search"][$list_name]["page"] = $app->functions->intval($_REQUEST["page"]); - - //* PAGE to 0 set, if look for themselves ? page auf 0 setzen, wenn suche sich ge�ndert hat. - if($this->searchChanged == 1) $_SESSION['search'][$list_name]['page'] = 0; - - $sql_von = $app->functions->intval($_SESSION['search'][$list_name]['page'] * $records_per_page); - $record_count = $app->db->queryOneRecord("SELECT count(*) AS anzahl FROM $table".($app->listform->listDef['additional_tables'] != ''? ','.$app->listform->listDef['additional_tables'] : '')." WHERE $sql_where"); - $pages = $app->functions->intval(($record_count['anzahl'] - 1) / $records_per_page); - - - $vars['list_file'] = $_SESSION['s']['module']['name'].'/'.$this->listDef['file']; - $vars['page'] = $_SESSION['search'][$list_name]['page']; - $vars['last_page'] = $_SESSION['search'][$list_name]['page'] - 1; - $vars['next_page'] = $_SESSION['search'][$list_name]['page'] + 1; - $vars['pages'] = $pages; - $vars['max_pages'] = $pages + 1; - $vars['records_gesamt'] = $record_count['anzahl']; - $vars['page_params'] = (isset($this->listDef['page_params'])) ? $this->listDef['page_params'] : ''; - $vars['offset'] = $sql_von; - $vars['records_per_page'] = $records_per_page; - //$vars['module'] = $_SESSION['s']['module']['name']; - - if($_SESSION['search'][$list_name]['page'] > 0) $vars['show_page_back'] = 1; - if($_SESSION['search'][$list_name]['page'] <= $vars['pages'] - 1) $vars['show_page_next'] = 1; - - $this->pagingValues = $vars; - $this->pagingHTML = $this->getPagingHTML($vars); - - //* Return limit sql - return "LIMIT $sql_von, $records_per_page"; - } - - public function getPagingHTML($vars) - { - global $app; - - // we want to show at max 17 page numbers (8 left, current, 8 right) - $show_pages_count = 17; - - $show_pages = array(0); // first page - if($vars['pages'] > 0) $show_pages[] = $vars['pages']; // last page - for($p = $vars['page'] - 2; $p <= $vars['page'] + 2; $p++) { // surrounding pages - if($p > 0 && $p < $vars['pages']) $show_pages[] = $p; - } - - $l_start = $vars['page'] - 13; - $l_start -= ($l_start % 10) + 1; - $h_end = $vars['page'] + 23; - $h_end -= ($h_end % 10) + 1; - for($p = $l_start; $p <= $h_end; $p += 10) { // surrounding pages - if($p > 0 && $p < $vars['pages'] && !in_array($p, $show_pages, true) && count($show_pages) < $show_pages_count) $show_pages[] = $p; - } - - $l_start = $vars['page'] - 503; - $l_start -= ($l_start % 100) + 1; - $h_end = $vars['page'] + 603; - $h_end -= ($h_end % 100) + 1; - for($p = $l_start; $p <= $h_end; $p += 100) { // surrounding pages - if($p > 0 && $p < $vars['pages'] && !in_array($p, $show_pages, true) && count($show_pages) < $show_pages_count) $show_pages[] = $p; - } - - $l_start = $vars['page'] - 203; - $l_start -= ($l_start % 25) + 1; - $h_end = $vars['page'] + 228; - $h_end -= ($h_end % 25) + 1; - for($p = $l_start; $p <= $h_end; $p += 25) { // surrounding pages - if($p > 0 && $p < $vars['pages'] && abs($p - $vars['page']) > 30 && !in_array($p, $show_pages, true) && count($show_pages) < $show_pages_count) $show_pages[] = $p; - } - - sort($show_pages); - $show_pages = array_unique($show_pages); - - //* Show Back - if(isset($vars['show_page_back']) && $vars['show_page_back'] == 1){ - $content = '' - .'   '; - $content .= '' - .'   '; - } - $content .= ' '.$this->lng('page_txt').' '; - $prev = -1; - foreach($show_pages as $p) { - if($prev != -1 && $p > $prev + 1) $content .= '...'; - $content .= ''. ($p+1) .''; - $prev = $p; - } - //.$vars['next_page'].' '.$this->lng('page_of_txt').' '.$vars['max_pages'].'   '; - //* Show Next - if(isset($vars['show_page_next']) && $vars['show_page_next'] == 1){ - $content .= '' - .'   '; - $content .= '' - .''; - } - return $content; - } - + //* Get Config variables + $list_name = $this->listDef['name']; + $search_prefix = $this->listDef['search_prefix']; + $records_per_page = (empty($_SESSION['search']['limit']) ? $app->functions->intval($this->listDef['records_per_page']) : $app->functions->intval($_SESSION['search']['limit'])) ; + $table = $this->listDef['table']; + + //* set PAGE to zero, if in session not set + if(!isset($_SESSION['search'][$list_name]['page']) || $_SESSION['search'][$list_name]['page'] == ''){ + $_SESSION['search'][$list_name]['page'] = 0; + } + + //* set PAGE to worth request variable "PAGE" - ? setze page auf wert der request variablen "page" + if(isset($_REQUEST["page"])) $_SESSION["search"][$list_name]["page"] = $app->functions->intval($_REQUEST["page"]); + + //* PAGE to 0 set, if look for themselves ? page auf 0 setzen, wenn suche sich ge�ndert hat. + if($this->searchChanged == 1) $_SESSION['search'][$list_name]['page'] = 0; + + $sql_von = $app->functions->intval($_SESSION['search'][$list_name]['page'] * $records_per_page); + $record_count = $app->db->queryOneRecord("SELECT count(*) AS anzahl FROM $table".($app->listform->listDef['additional_tables'] != ''? ','.$app->listform->listDef['additional_tables'] : '')." WHERE $sql_where"); + $pages = $app->functions->intval(($record_count['anzahl'] - 1) / $records_per_page); + + + $vars['list_file'] = $_SESSION['s']['module']['name'].'/'.$this->listDef['file']; + $vars['page'] = $_SESSION['search'][$list_name]['page']; + $vars['last_page'] = $_SESSION['search'][$list_name]['page'] - 1; + $vars['next_page'] = $_SESSION['search'][$list_name]['page'] + 1; + $vars['pages'] = $pages; + $vars['max_pages'] = $pages + 1; + $vars['records_gesamt'] = $record_count['anzahl']; + $vars['page_params'] = (isset($this->listDef['page_params'])) ? $this->listDef['page_params'] : ''; + $vars['offset'] = $sql_von; + $vars['records_per_page'] = $records_per_page; + //$vars['module'] = $_SESSION['s']['module']['name']; + + if($_SESSION['search'][$list_name]['page'] > 0) $vars['show_page_back'] = 1; + if($_SESSION['search'][$list_name]['page'] <= $vars['pages'] - 1) $vars['show_page_next'] = 1; + + $this->pagingValues = $vars; + $this->pagingHTML = $this->getPagingHTML($vars); + + //* Return limit sql + return "LIMIT $sql_von, $records_per_page"; + } + + public function getPagingHTML($vars) + { + global $app; + + // we want to show at max 17 page numbers (8 left, current, 8 right) + $show_pages_count = 17; + + $show_pages = array(0); // first page + if($vars['pages'] > 0) $show_pages[] = $vars['pages']; // last page + for($p = $vars['page'] - 2; $p <= $vars['page'] + 2; $p++) { // surrounding pages + if($p > 0 && $p < $vars['pages']) $show_pages[] = $p; + } + + $l_start = $vars['page'] - 13; + $l_start -= ($l_start % 10) + 1; + $h_end = $vars['page'] + 23; + $h_end -= ($h_end % 10) + 1; + for($p = $l_start; $p <= $h_end; $p += 10) { // surrounding pages + if($p > 0 && $p < $vars['pages'] && !in_array($p, $show_pages, true) && count($show_pages) < $show_pages_count) $show_pages[] = $p; + } + + $l_start = $vars['page'] - 503; + $l_start -= ($l_start % 100) + 1; + $h_end = $vars['page'] + 603; + $h_end -= ($h_end % 100) + 1; + for($p = $l_start; $p <= $h_end; $p += 100) { // surrounding pages + if($p > 0 && $p < $vars['pages'] && !in_array($p, $show_pages, true) && count($show_pages) < $show_pages_count) $show_pages[] = $p; + } + + $l_start = $vars['page'] - 203; + $l_start -= ($l_start % 25) + 1; + $h_end = $vars['page'] + 228; + $h_end -= ($h_end % 25) + 1; + for($p = $l_start; $p <= $h_end; $p += 25) { // surrounding pages + if($p > 0 && $p < $vars['pages'] && abs($p - $vars['page']) > 30 && !in_array($p, $show_pages, true) && count($show_pages) < $show_pages_count) $show_pages[] = $p; + } + + sort($show_pages); + $show_pages = array_unique($show_pages); + + //* Show Back + if(isset($vars['show_page_back']) && $vars['show_page_back'] == 1){ + $content = '' + .'   '; + $content .= '' + .'   '; + } + $content .= ' '.$this->lng('page_txt').' '; + $prev = -1; + foreach($show_pages as $p) { + if($prev != -1 && $p > $prev + 1) $content .= '...'; + $content .= ''. ($p+1) .''; + $prev = $p; + } + //.$vars['next_page'].' '.$this->lng('page_of_txt').' '.$vars['max_pages'].'   '; + //* Show Next + if(isset($vars['show_page_next']) && $vars['show_page_next'] == 1){ + $content .= '' + .'   '; + $content .= '' + .''; + } + return $content; + } + public function getPagingHTMLasTXT($vars) - { - global $app; - $content = '[|<< ]'; - if($vars['show_page_back'] == 1){ - $content .= '[<< '.$app->lng('page_back_txt').'] '; - } - $content .= ' '.$this->lng('page_txt').' '.$vars['next_page'].' '.$this->lng('page_of_txt').' '.$vars['max_pages'].' '; - if($vars['show_page_next'] == 1){ - $content .= '['.$app->lng('page_next_txt').' >>] '; - } - $content .= '[ >>|]'; - return $content; - } - - public function getSortSQL() - { - global $app, $conf; - //* Get config vars - $sort_field = $this->listDef['sort_field']; - $sort_direction = $this->listDef['sort_direction']; - return ($sort_field != '' && $sort_direction != '') ? "ORDER BY $sort_field $sort_direction" : ''; - } - - public function decode($record) - { - global $conf, $app; - if(is_array($record) && count($record) > 0 && is_array($this->listDef['item'])) { - foreach($this->listDef['item'] as $field){ - $key = $field['field']; - //* Apply filter to record value. - if(isset($field['filters']) && is_array($field['filters'])) { - $app->uses('tform'); - $record[$key] = $app->tform->filterField($key, (isset($record[$key]))?$record[$key]:'', $field['filters'], 'SHOW'); - } + { + global $app; + $content = '[|<< ]'; + if($vars['show_page_back'] == 1){ + $content .= '[<< '.$app->lng('page_back_txt').'] '; + } + $content .= ' '.$this->lng('page_txt').' '.$vars['next_page'].' '.$this->lng('page_of_txt').' '.$vars['max_pages'].' '; + if($vars['show_page_next'] == 1){ + $content .= '['.$app->lng('page_next_txt').' >>] '; + } + $content .= '[ >>|]'; + return $content; + } + + public function getSortSQL() + { + global $app, $conf; + //* Get config vars + $sort_field = $this->listDef['sort_field']; + $sort_direction = $this->listDef['sort_direction']; + return ($sort_field != '' && $sort_direction != '') ? "ORDER BY $sort_field $sort_direction" : ''; + } + + public function decode($record) + { + global $conf, $app; + if(is_array($record) && count($record) > 0 && is_array($this->listDef['item'])) { + foreach($this->listDef['item'] as $field){ + $key = $field['field']; + //* Apply filter to record value. + if(isset($field['filters']) && is_array($field['filters'])) { + $app->uses('tform'); + $record[$key] = $app->tform->filterField($key, (isset($record[$key]))?$record[$key]:'', $field['filters'], 'SHOW'); + } if(isset($record[$key])) { - switch ($field['datatype']){ - case 'VARCHAR': - case 'TEXT': - $record[$key] = htmlentities(stripslashes($record[$key]),ENT_QUOTES,$conf["html_content_encoding"]); - break; - - case 'DATETSTAMP': - if ($record[$key] > 0) { + switch ($field['datatype']){ + case 'VARCHAR': + case 'TEXT': + $record[$key] = htmlentities(stripslashes($record[$key]), ENT_QUOTES, $conf["html_content_encoding"]); + break; + + case 'DATETSTAMP': + if ($record[$key] > 0) { // is value int? if (preg_match("/^[0-9]+[\.]?[0-9]*$/", $record[$key], $p)) { - $record[$key] = date($this->lng('conf_format_dateshort'), $record[$key]); + $record[$key] = date($this->lng('conf_format_dateshort'), $record[$key]); } else { - $record[$key] = date($this->lng('conf_format_dateshort'), strtotime($record[$key])); + $record[$key] = date($this->lng('conf_format_dateshort'), strtotime($record[$key])); } } - break; + break; case 'DATETIMETSTAMP': - if ($record[$key] > 0) { + if ($record[$key] > 0) { // is value int? if (preg_match("/^[0-9]+[\.]?[0-9]*$/", $record[$key], $p)) { - $record[$key] = date($this->lng('conf_format_datetime'), $record[$key]); + $record[$key] = date($this->lng('conf_format_datetime'), $record[$key]); } else { - $record[$key] = date($this->lng('conf_format_datetime'), strtotime($record[$key])); + $record[$key] = date($this->lng('conf_format_datetime'), strtotime($record[$key])); } } - break; + break; case 'DATE': - if ($record[$key] > 0) { + if ($record[$key] > 0) { // is value int? if (preg_match("/^[0-9]+[\.]?[0-9]*$/", $record[$key], $p)) { - $record[$key] = date($this->lng('conf_format_dateshort'), $record[$key]); + $record[$key] = date($this->lng('conf_format_dateshort'), $record[$key]); } else { - $record[$key] = date($this->lng('conf_format_dateshort'), strtotime($record[$key])); + $record[$key] = date($this->lng('conf_format_dateshort'), strtotime($record[$key])); } } - break; - - case 'DATETIME': - if ($record[$key] > 0) { + break; + + case 'DATETIME': + if ($record[$key] > 0) { // is value int? if (preg_match("/^[0-9]+[\.]?[0-9]*$/", $record[$key], $p)) { - $record[$key] = date($this->lng('conf_format_datetime'), $record[$key]); + $record[$key] = date($this->lng('conf_format_datetime'), $record[$key]); } else { - $record[$key] = date($this->lng('conf_format_datetime'), strtotime($record[$key])); + $record[$key] = date($this->lng('conf_format_datetime'), strtotime($record[$key])); } } - break; + break; - case 'INTEGER': - $record[$key] = $app->functions->intval($record[$key]); - break; + case 'INTEGER': + $record[$key] = $app->functions->intval($record[$key]); + break; - case 'DOUBLE': - $record[$key] = htmlentities($record[$key],ENT_QUOTES,$conf["html_content_encoding"]); - break; + case 'DOUBLE': + $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf["html_content_encoding"]); + break; - case 'CURRENCY': - $record[$key] = $app->functions->currency_format($record[$key]); - break; + case 'CURRENCY': + $record[$key] = $app->functions->currency_format($record[$key]); + break; - default: - $record[$key] = htmlentities(stripslashes($record[$key]),ENT_QUOTES,$conf["html_content_encoding"]); - } + default: + $record[$key] = htmlentities(stripslashes($record[$key]), ENT_QUOTES, $conf["html_content_encoding"]); + } } - } - } - return $record; - } - - public function encode($record) - { - global $app; - if(is_array($record)) { - foreach($this->listDef['item'] as $field){ - $key = $field['field']; - switch($field['datatype']){ - - case 'VARCHAR': - case 'TEXT': - if(!is_array($record[$key])) { - $record[$key] = $app->db->quote($record[$key]); - } else { - $record[$key] = implode($this->tableDef[$key]['separator'],$record[$key]); - } - break; - - case 'DATETSTAMP': - if($record[$key] > 0) { - $record[$key] = date('Y-m-d',strtotime($record[$key])); - } - break; - - case 'DATETIMETSTAMP': - if($record[$key] > 0) { - $record[$key] = date('Y-m-d H:i:s',strtotime($record[$key])); - } - break; - - case 'DATE': - if($record[$key] != '' && $record[$key] != '0000-00-00') { - $record[$key] = $record[$key]; - } - break; - - case 'DATETIME': - if($record[$key] > 0) { - $record[$key] = date('Y-m-d H:i:s',strtotime($record[$key])); - } - break; - - case 'INTEGER': - $record[$key] = $app->functions->intval($record[$key]); - break; - - case 'DOUBLE': - $record[$key] = $app->db->quote($record[$key]); - break; - - case 'CURRENCY': - $record[$key] = str_replace(',', '.', $record[$key]); - break; - } - } - } - return $record; - } - + } + } + return $record; + } + + public function encode($record) + { + global $app; + if(is_array($record)) { + foreach($this->listDef['item'] as $field){ + $key = $field['field']; + switch($field['datatype']){ + + case 'VARCHAR': + case 'TEXT': + if(!is_array($record[$key])) { + $record[$key] = $app->db->quote($record[$key]); + } else { + $record[$key] = implode($this->tableDef[$key]['separator'], $record[$key]); + } + break; + + case 'DATETSTAMP': + if($record[$key] > 0) { + $record[$key] = date('Y-m-d', strtotime($record[$key])); + } + break; + + case 'DATETIMETSTAMP': + if($record[$key] > 0) { + $record[$key] = date('Y-m-d H:i:s', strtotime($record[$key])); + } + break; + + case 'DATE': + if($record[$key] != '' && $record[$key] != '0000-00-00') { + $record[$key] = $record[$key]; + } + break; + + case 'DATETIME': + if($record[$key] > 0) { + $record[$key] = date('Y-m-d H:i:s', strtotime($record[$key])); + } + break; + + case 'INTEGER': + $record[$key] = $app->functions->intval($record[$key]); + break; + + case 'DOUBLE': + $record[$key] = $app->db->quote($record[$key]); + break; + + case 'CURRENCY': + $record[$key] = str_replace(',', '.', $record[$key]); + break; + } + } + } + return $record; + } + function lng($msg) { global $app; - + if(isset($this->wordbook[$msg])) { return $this->wordbook[$msg]; } else { return $app->lng($msg); - } + } } - + function escapeArrayValues($search_values) { - global $conf; - + global $conf; + $out = array(); if(is_array($search_values)) { foreach($search_values as $key => $val) { - $out[$key] = htmlentities($val,ENT_QUOTES,$conf["html_content_encoding"]); + $out[$key] = htmlentities($val, ENT_QUOTES, $conf["html_content_encoding"]); } } - + return $out; - + } } -?> \ No newline at end of file +?> diff --git a/interface/lib/classes/listform_actions.inc.php b/interface/lib/classes/listform_actions.inc.php index fe167a90a59ca70641c8d68e836f921f98209444..0062d8e3ae6725eb8e3f3b912d6666f2f3dc2e85 100644 --- a/interface/lib/classes/listform_actions.inc.php +++ b/interface/lib/classes/listform_actions.inc.php @@ -29,7 +29,7 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class listform_actions { - + private $id; public $idx_key; public $DataRowColor; @@ -37,139 +37,139 @@ class listform_actions { public $SQLOrderBy = ''; public $SQLExtSelect = ''; private $sortKeys; - - private function _sort($aOne, $aTwo) { - if(!is_array($aOne) || !is_array($aTwo)) return 0; - - if(!is_array($this->sortKeys)) $this->sortKeys = array($this->sortKeys); - foreach($this->sortKeys as $sKey => $sDir) { - if(is_numeric($sKey)) { - $sKey = $sDir; - $sDir = 'ASC'; - } - $a = $aOne[$sKey]; - $b = $aTwo[$sKey]; - if(is_string($a)) $a = strtolower($a); - if(is_string($b)) $b = strtolower($b); - if($a < $b) return ($sDir == 'DESC' ? 1 : -1); - elseif($a > $b) return ($sDir == 'DESC' ? -1 : 1); - } - return 0; - } - + + private function _sort($aOne, $aTwo) { + if(!is_array($aOne) || !is_array($aTwo)) return 0; + + if(!is_array($this->sortKeys)) $this->sortKeys = array($this->sortKeys); + foreach($this->sortKeys as $sKey => $sDir) { + if(is_numeric($sKey)) { + $sKey = $sDir; + $sDir = 'ASC'; + } + $a = $aOne[$sKey]; + $b = $aTwo[$sKey]; + if(is_string($a)) $a = strtolower($a); + if(is_string($b)) $b = strtolower($b); + if($a < $b) return $sDir == 'DESC' ? 1 : -1; + elseif($a > $b) return $sDir == 'DESC' ? -1 : 1; + } + return 0; + } + public function onLoad() - { + { global $app, $conf, $list_def_file; - + $app->uses('tpl,listform,tform'); - + //* Clear session variable that is used when lists are embedded with the listview plugin $_SESSION['s']['form']['return_to'] = ''; - + // Load list definition $app->listform->loadListDef($list_def_file); - + if(!is_file('templates/'.$app->listform->listDef["name"].'_list.htm')) { $app->uses('listform_tpl_generator'); $app->listform_tpl_generator->buildHTML($app->listform->listDef); } - + $app->tpl->newTemplate("listpage.tpl.htm"); - $app->tpl->setInclude('content_tpl','templates/'.$app->listform->listDef["name"].'_list.htm'); - + $app->tpl->setInclude('content_tpl', 'templates/'.$app->listform->listDef["name"].'_list.htm'); + //* Manipulate order by for sorting / Every list has a stored value //* Against notice error if(!isset($_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order'])){ - $_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order'] = ''; + $_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order'] = ''; } - - $php_sort = false; - + + $php_sort = false; + if(!empty($_GET['orderby'])){ - $order = str_replace('tbl_col_','',$_GET['orderby']); - - //* Check the css class submited value - if (preg_match("/^[a-z\_]{1,}$/",$order)) { - - if(isset($app->listform->listDef['phpsort']) && is_array($app->listform->listDef['phpsort']) && in_array($order, $app->listform->listDef['phpsort'])) { - $php_sort = true; - } else { - // prepend correct table - $prepend_table = $app->listform->listDef['table']; - if(trim($app->listform->listDef['additional_tables']) != '' && is_array($app->listform->listDef['item']) && count($app->listform->listDef['item']) > 0) { - foreach($app->listform->listDef['item'] as $field) { - if($field['field'] == $order && $field['table'] != ''){ - $prepend_table = $field['table']; - break; - } - } - } - $order = $prepend_table.'.'.$order; - } - - if($_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order'] == $order){ - $_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order'] = $order.' DESC'; - } else { - $_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order'] = $order; - } - $_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order_in_php'] = $php_sort; - } + $order = str_replace('tbl_col_', '', $_GET['orderby']); + + //* Check the css class submited value + if (preg_match("/^[a-z\_]{1,}$/", $order)) { + + if(isset($app->listform->listDef['phpsort']) && is_array($app->listform->listDef['phpsort']) && in_array($order, $app->listform->listDef['phpsort'])) { + $php_sort = true; + } else { + // prepend correct table + $prepend_table = $app->listform->listDef['table']; + if(trim($app->listform->listDef['additional_tables']) != '' && is_array($app->listform->listDef['item']) && count($app->listform->listDef['item']) > 0) { + foreach($app->listform->listDef['item'] as $field) { + if($field['field'] == $order && $field['table'] != ''){ + $prepend_table = $field['table']; + break; + } + } + } + $order = $prepend_table.'.'.$order; + } + + if($_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order'] == $order){ + $_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order'] = $order.' DESC'; + } else { + $_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order'] = $order; + } + $_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order_in_php'] = $php_sort; + } } // If a manuel oder by like customers isset the sorting will be infront if(!empty($_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order']) && !$_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order_in_php']){ - if(empty($this->SQLOrderBy)){ - $this->SQLOrderBy = "ORDER BY ".$_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order']; - } else { - $this->SQLOrderBy = str_replace("ORDER BY ","ORDER BY ".$_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order'].', ',$this->SQLOrderBy); - } + if(empty($this->SQLOrderBy)){ + $this->SQLOrderBy = "ORDER BY ".$_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order']; + } else { + $this->SQLOrderBy = str_replace("ORDER BY ", "ORDER BY ".$_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order'].', ', $this->SQLOrderBy); + } } - + if($_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order_in_php']) $php_sort = true; - + // Getting Datasets from DB $records = $app->db->queryAllRecords($this->getQueryString($php_sort)); $this->DataRowColor = "#FFFFFF"; $records_new = ''; if(is_array($records)) { - $this->idx_key = $app->listform->listDef["table_idx"]; + $this->idx_key = $app->listform->listDef["table_idx"]; foreach($records as $rec) { $records_new[] = $this->prepareDataRow($rec); } } - - if(!empty($_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order']) && $_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order_in_php']) { - $order_by = $_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order']; - $order_dir = 'ASC'; - if(substr($order_by, -5) === ' DESC') { - $order_by = substr($order_by, 0, -5); - $order_dir = 'DESC'; - } - $this->sortKeys = array($order_by => $order_dir); - uasort($records_new, array($this, '_sort')); - } - if($php_sort) { + + if(!empty($_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order']) && $_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order_in_php']) { + $order_by = $_SESSION['search'][$_SESSION['s']['module']['name'].$app->listform->listDef["name"].$app->listform->listDef['table']]['order']; + $order_dir = 'ASC'; + if(substr($order_by, -5) === ' DESC') { + $order_by = substr($order_by, 0, -5); + $order_dir = 'DESC'; + } + $this->sortKeys = array($order_by => $order_dir); + uasort($records_new, array($this, '_sort')); + } + if($php_sort) { $records_new = array_slice($records_new, $app->listform->getPagingValue('offset'), $app->listform->getPagingValue('records_per_page')); } - - $app->tpl->setLoop('records',$records_new); + + $app->tpl->setLoop('records', $records_new); $this->onShow(); - - + + } - + public function prepareDataRow($rec) - { + { global $app; - + $rec = $app->listform->decode($rec); //* Alternating datarow colors $this->DataRowColor = ($this->DataRowColor == '#FFFFFF') ? '#EEEEEE' : '#FFFFFF'; $rec['bgcolor'] = $this->DataRowColor; - + //* substitute value for select fields if(is_array($app->listform->listDef['item']) && count($app->listform->listDef['item']) > 0) { foreach($app->listform->listDef['item'] as $field) { @@ -184,12 +184,12 @@ class listform_actions { } } } - + //* The variable "id" contains always the index variable $rec['id'] = $rec[$this->idx_key]; return $rec; } - + public function getQueryString($no_limit = false) { global $app; $sql_where = ''; @@ -199,32 +199,32 @@ class listform_actions { if($_SESSION['s']['user']['typ'] == "admin") { $sql_where = ''; } else { - $sql_where = $app->tform->getAuthSQL('r', $app->listform->listDef['table']).' and'; - //$sql_where = $app->tform->getAuthSQL('r').' and'; + $sql_where = $app->tform->getAuthSQL('r', $app->listform->listDef['table']).' and'; + //$sql_where = $app->tform->getAuthSQL('r').' and'; } - } + } if($this->SQLExtWhere != '') { $sql_where .= ' '.$this->SQLExtWhere.' and'; } - + $sql_where = $app->listform->getSearchSQL($sql_where); if($app->listform->listDef['join_sql']) $sql_where .= ' AND '.$app->listform->listDef['join_sql']; $app->tpl->setVar($app->listform->searchValues); - + $order_by_sql = $this->SQLOrderBy; //* Generate SQL for paging $limit_sql = $app->listform->getPagingSQL($sql_where); - $app->tpl->setVar('paging',$app->listform->pagingHTML); + $app->tpl->setVar('paging', $app->listform->pagingHTML); $extselect = ''; $join = ''; - + if($this->SQLExtSelect != '') { - if(substr($this->SQLExtSelect,0,1) != ',') $this->SQLExtSelect = ','.$this->SQLExtSelect; + if(substr($this->SQLExtSelect, 0, 1) != ',') $this->SQLExtSelect = ','.$this->SQLExtSelect; $extselect .= $this->SQLExtSelect; } - + $table_selects = array(); $table_selects[] = trim($app->listform->listDef['table']).'.*'; $app->listform->listDef['additional_tables'] = trim($app->listform->listDef['additional_tables']); @@ -241,53 +241,54 @@ class listform_actions { //echo $sql; return $sql; } - - + + public function onShow() - { + { global $app; - + //* Set global Language File $lng_file = ISPC_LIB_PATH.'/lang/'.$_SESSION['s']['language'].'.lng'; if(!file_exists($lng_file)) - $lng_file = ISPC_LIB_PATH.'/lang/en.lng'; - include($lng_file); + $lng_file = ISPC_LIB_PATH.'/lang/en.lng'; + include $lng_file; $app->tpl->setVar($wb); - + //* Limit each page - $limits = array('5'=>'5','15'=>'15','25'=>'25','50'=>'50','100'=>'100','999999999' => 'all'); + $limits = array('5'=>'5', '15'=>'15', '25'=>'25', '50'=>'50', '100'=>'100', '999999999' => 'all'); //* create options and set selected, if default -> 15 is selected $options = ''; foreach($limits as $key => $val){ - $options .= ''; + $options .= ''; } - $app->tpl->setVar('search_limit',''); - - $app->tpl->setVar('toolsarea_head_txt',$app->lng('toolsarea_head_txt')); + $app->tpl->setVar('search_limit', ''); + + $app->tpl->setVar('toolsarea_head_txt', $app->lng('toolsarea_head_txt')); $app->tpl->setVar($app->listform->wordbook); $app->tpl->setVar('form_action', $app->listform->listDef['file']); - - if(isset($_SESSION['show_info_msg'])) { - $app->tpl->setVar('show_info_msg', $_SESSION['show_info_msg']); - unset($_SESSION['show_info_msg']); - } - if(isset($_SESSION['show_error_msg'])) { - $app->tpl->setVar('show_error_msg', $_SESSION['show_error_msg']); - unset($_SESSION['show_error_msg']); - } - + + if(isset($_SESSION['show_info_msg'])) { + $app->tpl->setVar('show_info_msg', $_SESSION['show_info_msg']); + unset($_SESSION['show_info_msg']); + } + if(isset($_SESSION['show_error_msg'])) { + $app->tpl->setVar('show_error_msg', $_SESSION['show_error_msg']); + unset($_SESSION['show_error_msg']); + } + //* Parse the templates and send output to the browser $this->onShowEnd(); } - + public function onShowEnd() - { + { global $app; $app->tpl_defaults(); $app->tpl->pparse(); } + } -?> \ No newline at end of file +?> diff --git a/interface/lib/classes/listform_tpl_generator.inc.php b/interface/lib/classes/listform_tpl_generator.inc.php index e19b52c3ff66a511c54b2f5b60deb2dee6f7e8b9..b8a26a73ae71bdd3a125895ba9e887e3daf046f0 100644 --- a/interface/lib/classes/listform_tpl_generator.inc.php +++ b/interface/lib/classes/listform_tpl_generator.inc.php @@ -29,11 +29,11 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class listform_tpl_generator { - - function buildHTML($listDef,$module = '') { - + + function buildHTML($listDef, $module = '') { + global $app; - + if($module == '') $module = $_SESSION["s"]["module"]["name"]; $lang = array(); @@ -57,22 +57,22 @@ class listform_tpl_generator { '; - + $lang["list_head_txt"] = $listDef["name"]; - $colcount = 0; + $colcount = 0; foreach($listDef["item"] as $field) { $key = $field["field"]; $html .= " \n"; $lang[$key."_txt"] = $key; - $colcount++; + $colcount++; } - + $html .= '   '; - - foreach($listDef["item"] as $field) { + + foreach($listDef["item"] as $field) { $key = $field["field"]; if($field["formtype"] == 'SELECT') { $html .= " \n"; @@ -80,7 +80,7 @@ class listform_tpl_generator { $html .= " \n"; } } - + $html .= '
@@ -88,14 +88,14 @@ class listform_tpl_generator { '; - + foreach($listDef["item"] as $field) { $key = $field["field"]; $html .= " {tmpl_var name=\"".$key."\"}\n"; } - + $html .= " -
+ @@ -107,7 +107,7 @@ class listform_tpl_generator { "; - $html .= ' + $html .= ' @@ -119,26 +119,26 @@ class listform_tpl_generator {
'; - + if($module == '') { $filename = 'templates/'.$listDef["name"].'_list.htm'; } else { $filename = '../'.$module.'/templates/'.$listDef["name"].'_list.htm'; } - - + + // save template - if (!$handle = fopen($filename, 'w')) { - print "Cannot open file ($filename)"; - exit; - } - - if (!fwrite($handle, $html)) { - print "Cannot write to file ($filename)"; - exit; + if (!$handle = fopen($filename, 'w')) { + print "Cannot open file ($filename)"; + exit; + } + + if (!fwrite($handle, $html)) { + print "Cannot write to file ($filename)"; + exit; } fclose($handle); - + /*$lang["page_txt"] = 'Page'; $lang["page_of_txt"] = 'of'; $lang["page_next_txt"] = 'Next'; @@ -147,41 +147,41 @@ class listform_tpl_generator { $lang["filter_txt"] = 'Filter'; $lang["add_new_record_txt"] = 'Add new record'; */ - + // save language file - $this->lng_add($lang,$listDef,$module); - } - - function lng_add($lang,$listDef,$module = '') { - global $go_api, $go_info,$conf; - + $this->lng_add($lang, $listDef, $module); + } + + function lng_add($lang, $listDef, $module = '') { + global $go_api, $go_info, $conf; + if($module == '') { $lng_file = "lib/lang/".$conf["language"]."_".$listDef['name']."_list.lng"; } else { $lng_file = '../'.$module."/lib/lang/en_".$listDef['name']."_list.lng"; } - + if(is_file($lng_file)) { - include_once($lng_file); + include_once $lng_file; } else { $wb = array(); } - - $wb_out = array_merge($lang,$wb); - + + $wb_out = array_merge($lang, $wb); + if(is_array($wb_out)) { - $fp = fopen ($lng_file, "w"); - fwrite($fp," $val) { $new_line = '$wb["'.$key.'"] = '."'$val';\n"; - fwrite($fp,$new_line); - + fwrite($fp, $new_line); + } - fwrite($fp,"?>"); + fwrite($fp, "?>"); fclose($fp); } } } -?> \ No newline at end of file +?> diff --git a/interface/lib/classes/plugin.inc.php b/interface/lib/classes/plugin.inc.php index 341b186223d5f9c9381f3774e1c3f0bc7f6d6f5c..aaaf56797cf9a18c77ed5bc2cd3d2d912f752a1f 100644 --- a/interface/lib/classes/plugin.inc.php +++ b/interface/lib/classes/plugin.inc.php @@ -29,92 +29,92 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class plugin { - + private $subscribed_events = array(); private $debug = false; - - + + /* This function is called to load the plugins from the plugins folder and update the plugin cache */ - + private function loadPluginCache() { - global $app,$conf; - - + global $app, $conf; + + if(isset($_SESSION['s']['plugin_cache'])) unset($_SESSION['s']['plugin_cache']); - + $plugins_dir = ISPC_LIB_PATH.FS_DIV.'plugins'.FS_DIV; $_SESSION['s']['plugin_cache'] = array(); $tmp_plugins = array(); - + if (is_dir($plugins_dir)) { if ($dh = opendir($plugins_dir)) { //** Go trough all files in the plugin dir while (($file = readdir($dh)) !== false) { - if($file != '.' && $file != '..' && substr($file,-8,8) == '.inc.php') { - $plugin_name = substr($file,0,-8); + if($file != '.' && $file != '..' && substr($file, -8, 8) == '.inc.php') { + $plugin_name = substr($file, 0, -8); $tmp_plugins[$plugin_name] = $file; } } //** sort the plugins by name ksort($tmp_plugins); - + //** load the plugins foreach($tmp_plugins as $plugin_name => $file) { - include_once($plugins_dir.$file); - if($this->debug) $app->log('Loading plugin: '.$plugin_name,LOGLEVEL_DEBUG); + include_once $plugins_dir.$file; + if($this->debug) $app->log('Loading plugin: '.$plugin_name, LOGLEVEL_DEBUG); $app->loaded_plugins[$plugin_name] = new $plugin_name; $app->loaded_plugins[$plugin_name]->onLoad(); } } else { - $app->log('Unable to open the plugins directory: '.$plugins_dir,LOGLEVEL_ERROR); + $app->log('Unable to open the plugins directory: '.$plugins_dir, LOGLEVEL_ERROR); } } else { - $app->log('Plugins directory missing: '.$plugins_dir,LOGLEVEL_ERROR); + $app->log('Plugins directory missing: '.$plugins_dir, LOGLEVEL_ERROR); } - + } - + /* - This function is called by the plugin to register for an event which is saved into the plugin cache + This function is called by the plugin to register for an event which is saved into the plugin cache for faster lookups without the need to load all plugins for every page. */ - - public function registerEvent($event_name,$plugin_name,$function_name) { + + public function registerEvent($event_name, $plugin_name, $function_name) { global $app; - + $_SESSION['s']['plugin_cache'][$event_name][] = array('plugin' => $plugin_name, 'function' => $function_name); - if($this->debug) $app->log("Plugin '$plugin_name' has registered the function '$function_name' for the event '$event_name'",LOGLEVEL_DEBUG); + if($this->debug) $app->log("Plugin '$plugin_name' has registered the function '$function_name' for the event '$event_name'", LOGLEVEL_DEBUG); } - + /* This function is called when a certian action occurs, e.g. a form gets saved or a user is logged in. */ - - public function raiseEvent($event_name,$data) { + + public function raiseEvent($event_name, $data) { global $app; - + if(!isset($_SESSION['s']['plugin_cache'])) { $this->loadPluginCache(); - if($this->debug) $app->log('Loaded the plugin cache.',LOGLEVEL_DEBUG); + if($this->debug) $app->log('Loaded the plugin cache.', LOGLEVEL_DEBUG); } - - - $sub_events = explode(':',$event_name); - + + + $sub_events = explode(':', $event_name); + if(is_array($sub_events)) { if(count($sub_events) == 3) { $tmp_event = $sub_events[2]; - if($this->debug) $app->log("Called Event '$tmp_event'",LOGLEVEL_DEBUG); - $this->callPluginEvent($tmp_event,$data); + if($this->debug) $app->log("Called Event '$tmp_event'", LOGLEVEL_DEBUG); + $this->callPluginEvent($tmp_event, $data); $tmp_event = $sub_events[0].':'.$sub_events[2]; - if($this->debug) $app->log("Called Event '$tmp_event'",LOGLEVEL_DEBUG); - $this->callPluginEvent($tmp_event,$data); + if($this->debug) $app->log("Called Event '$tmp_event'", LOGLEVEL_DEBUG); + $this->callPluginEvent($tmp_event, $data); $tmp_event = $sub_events[0].':'.$sub_events[1].':'.$sub_events[2]; - if($this->debug) $app->log("Called Event '$tmp_event'",LOGLEVEL_DEBUG); - $this->callPluginEvent($tmp_event,$data); - + if($this->debug) $app->log("Called Event '$tmp_event'", LOGLEVEL_DEBUG); + $this->callPluginEvent($tmp_event, $data); + /*$sub_events = array_reverse($sub_events); $tmp_event = ''; foreach($sub_events as $n => $sub_event) { @@ -124,44 +124,44 @@ class plugin { } */ } else { - if($this->debug) $app->log("Called Event '$sub_events[0]'",LOGLEVEL_DEBUG); - $this->callPluginEvent($sub_events[0],$data); + if($this->debug) $app->log("Called Event '$sub_events[0]'", LOGLEVEL_DEBUG); + $this->callPluginEvent($sub_events[0], $data); } } - - } // end function raiseEvent - - //* Internal function to load the plugin and call the event function in the plugin. - private function callPluginEvent($event_name,$data) { - global $app; - - //* execute the functions for the events + + } // end function raiseEvent + + //* Internal function to load the plugin and call the event function in the plugin. + private function callPluginEvent($event_name, $data) { + global $app; + + //* execute the functions for the events if(@is_array($_SESSION['s']['plugin_cache'][$event_name])) { foreach($_SESSION['s']['plugin_cache'][$event_name] as $rec) { $plugin_name = $rec['plugin']; $function_name = $rec['function']; $plugin_file = ISPC_LIB_PATH.FS_DIV.'plugins'.FS_DIV.$plugin_name.'.inc.php'; - - + + if(is_file($plugin_file)) { if(!isset($app->loaded_plugins[$plugin_name])) { - include_once($plugin_file); + include_once $plugin_file; $app->loaded_plugins[$plugin_name] = new $plugin_name; } - - if($this->debug) $app->log("Called method: '$function_name' in plugin '$plugin_name' for event '$event_name'",LOGLEVEL_DEBUG); + + if($this->debug) $app->log("Called method: '$function_name' in plugin '$plugin_name' for event '$event_name'", LOGLEVEL_DEBUG); // call_user_method($function_name,$app->loaded_plugins[$plugin_name],$event_name,$data); - call_user_func(array($app->loaded_plugins[$plugin_name],$function_name),$event_name,$data); - + call_user_func(array($app->loaded_plugins[$plugin_name], $function_name), $event_name, $data); + } } - + } - - } // end functiom callPluginEvent - - + + } // end functiom callPluginEvent + + } ?> diff --git a/interface/lib/classes/plugin_backuplist.inc.php b/interface/lib/classes/plugin_backuplist.inc.php index 1f90496142764792f74927646484e1e636ad2e93..6d3cdd3a0927100755ea33fdc3e93a0a0f0343e5 100644 --- a/interface/lib/classes/plugin_backuplist.inc.php +++ b/interface/lib/classes/plugin_backuplist.inc.php @@ -30,121 +30,121 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class plugin_backuplist extends plugin_base { - var $module; - var $form; - var $tab; - var $record_id; - var $formdef; - var $options; - - function onShow() { - - global $app; - - $listTpl = new tpl; - $listTpl->newTemplate('templates/web_backup_list.htm'); - - //* Loading language file - $lng_file = "lib/lang/".$_SESSION["s"]["language"]."_web_backup_list.lng"; - include($lng_file); - $listTpl->setVar($wb); - - $message = ''; - $error = ''; - - if(isset($_GET['backup_action'])) { - $backup_id = $app->functions->intval($_GET['backup_id']); - - //* check if the user is owner of the parent domain - $domain_backup = $app->db->queryOneRecord("SELECT parent_domain_id FROM web_backup WHERE backup_id = ".$backup_id); - - $check_perm = 'u'; - if($_GET['backup_action'] == 'download') $check_perm = 'r'; // only check read permissions on download, not update permissions - - $get_domain = $app->db->queryOneRecord("SELECT domain_id FROM web_domain WHERE domain_id = ".$app->functions->intval($domain_backup["parent_domain_id"])." AND ".$app->tform->getAuthSQL($check_perm)); - if(empty($get_domain) || !$get_domain) { - $app->error($app->tform->lng('no_domain_perm')); - } - - if($_GET['backup_action'] == 'download' && $backup_id > 0) { - $sql = "SELECT count(action_id) as number FROM sys_remoteaction WHERE action_state = 'pending' AND action_type = 'backup_download' AND action_param = '$backup_id'"; - $tmp = $app->db->queryOneRecord($sql); - if($tmp['number'] == 0) { - $message .= $wb['download_info_txt']; - $sql = "INSERT INTO sys_remoteaction (server_id, tstamp, action_type, action_param, action_state, response) " . - "VALUES (". - (int)$this->form->dataRecord['server_id'] . ", " . - time() . ", " . - "'backup_download', " . - "'".$backup_id."', " . - "'pending', " . - "''" . - ")"; - $app->db->query($sql); - } else { - $error .= $wb['download_pending_txt']; - } - } - if($_GET['backup_action'] == 'restore' && $backup_id > 0) { - $sql = "SELECT count(action_id) as number FROM sys_remoteaction WHERE action_state = 'pending' AND action_type = 'backup_restore' AND action_param = '$backup_id'"; - $tmp = $app->db->queryOneRecord($sql); - if($tmp['number'] == 0) { - $message .= $wb['restore_info_txt']; - $sql = "INSERT INTO sys_remoteaction (server_id, tstamp, action_type, action_param, action_state, response) " . - "VALUES (". - (int)$this->form->dataRecord['server_id'] . ", " . - time() . ", " . - "'backup_restore', " . - "'".$backup_id."', " . - "'pending', " . - "''" . - ")"; - $app->db->query($sql); - } else { - $error .= $wb['restore_pending_txt']; - } - } - + var $module; + var $form; + var $tab; + var $record_id; + var $formdef; + var $options; + + function onShow() { + + global $app; + + $listTpl = new tpl; + $listTpl->newTemplate('templates/web_backup_list.htm'); + + //* Loading language file + $lng_file = "lib/lang/".$_SESSION["s"]["language"]."_web_backup_list.lng"; + include $lng_file; + $listTpl->setVar($wb); + + $message = ''; + $error = ''; + + if(isset($_GET['backup_action'])) { + $backup_id = $app->functions->intval($_GET['backup_id']); + + //* check if the user is owner of the parent domain + $domain_backup = $app->db->queryOneRecord("SELECT parent_domain_id FROM web_backup WHERE backup_id = ".$backup_id); + + $check_perm = 'u'; + if($_GET['backup_action'] == 'download') $check_perm = 'r'; // only check read permissions on download, not update permissions + + $get_domain = $app->db->queryOneRecord("SELECT domain_id FROM web_domain WHERE domain_id = ".$app->functions->intval($domain_backup["parent_domain_id"])." AND ".$app->tform->getAuthSQL($check_perm)); + if(empty($get_domain) || !$get_domain) { + $app->error($app->tform->lng('no_domain_perm')); + } + + if($_GET['backup_action'] == 'download' && $backup_id > 0) { + $sql = "SELECT count(action_id) as number FROM sys_remoteaction WHERE action_state = 'pending' AND action_type = 'backup_download' AND action_param = '$backup_id'"; + $tmp = $app->db->queryOneRecord($sql); + if($tmp['number'] == 0) { + $message .= $wb['download_info_txt']; + $sql = "INSERT INTO sys_remoteaction (server_id, tstamp, action_type, action_param, action_state, response) " . + "VALUES (". + (int)$this->form->dataRecord['server_id'] . ", " . + time() . ", " . + "'backup_download', " . + "'".$backup_id."', " . + "'pending', " . + "''" . + ")"; + $app->db->query($sql); + } else { + $error .= $wb['download_pending_txt']; + } + } + if($_GET['backup_action'] == 'restore' && $backup_id > 0) { + $sql = "SELECT count(action_id) as number FROM sys_remoteaction WHERE action_state = 'pending' AND action_type = 'backup_restore' AND action_param = '$backup_id'"; + $tmp = $app->db->queryOneRecord($sql); + if($tmp['number'] == 0) { + $message .= $wb['restore_info_txt']; + $sql = "INSERT INTO sys_remoteaction (server_id, tstamp, action_type, action_param, action_state, response) " . + "VALUES (". + (int)$this->form->dataRecord['server_id'] . ", " . + time() . ", " . + "'backup_restore', " . + "'".$backup_id."', " . + "'pending', " . + "''" . + ")"; + $app->db->query($sql); + } else { + $error .= $wb['restore_pending_txt']; } - - //* Get the data - $web = $app->db->queryOneRecord("SELECT server_id FROM web_domain WHERE domain_id = ".$this->form->id); - $sql = "SELECT * FROM web_backup WHERE parent_domain_id = ".$this->form->id." AND server_id = ".$web['server_id']." ORDER BY tstamp DESC, backup_type ASC"; - $records = $app->db->queryAllRecords($sql); - - $bgcolor = "#FFFFFF"; - if(is_array($records)) { - foreach($records as $rec) { - - // Change of color - $bgcolor = ($bgcolor == "#FFFFFF")?"#EEEEEE":"#FFFFFF"; - $rec["bgcolor"] = $bgcolor; - - $rec['date'] = date($app->lng('conf_format_datetime'),$rec['tstamp']); - $rec['backup_type'] = $wb[('backup_type_'.$rec['backup_type'])]; - - $records_new[] = $rec; - } - } - - $listTpl->setLoop('records',@$records_new); - - $listTpl->setVar('parent_id',$this->form->id); - $listTpl->setVar('msg',$message); - $listTpl->setVar('error',$error); - - // Setting Returnto information in the session - $list_name = 'backup_list'; - // $_SESSION["s"]["list"][$list_name]["parent_id"] = $app->tform_actions->id; - $_SESSION["s"]["list"][$list_name]["parent_id"] = $this->form->id; - $_SESSION["s"]["list"][$list_name]["parent_name"] = $app->tform->formDef["name"]; - $_SESSION["s"]["list"][$list_name]["parent_tab"] = $_SESSION["s"]["form"]["tab"]; - $_SESSION["s"]["list"][$list_name]["parent_script"] = $app->tform->formDef["action"]; - $_SESSION["s"]["form"]["return_to"] = $list_name; - - return $listTpl->grab(); - } - + } + + } + + //* Get the data + $web = $app->db->queryOneRecord("SELECT server_id FROM web_domain WHERE domain_id = ".$this->form->id); + $sql = "SELECT * FROM web_backup WHERE parent_domain_id = ".$this->form->id." AND server_id = ".$web['server_id']." ORDER BY tstamp DESC, backup_type ASC"; + $records = $app->db->queryAllRecords($sql); + + $bgcolor = "#FFFFFF"; + if(is_array($records)) { + foreach($records as $rec) { + + // Change of color + $bgcolor = ($bgcolor == "#FFFFFF")?"#EEEEEE":"#FFFFFF"; + $rec["bgcolor"] = $bgcolor; + + $rec['date'] = date($app->lng('conf_format_datetime'), $rec['tstamp']); + $rec['backup_type'] = $wb[('backup_type_'.$rec['backup_type'])]; + + $records_new[] = $rec; + } + } + + $listTpl->setLoop('records', @$records_new); + + $listTpl->setVar('parent_id', $this->form->id); + $listTpl->setVar('msg', $message); + $listTpl->setVar('error', $error); + + // Setting Returnto information in the session + $list_name = 'backup_list'; + // $_SESSION["s"]["list"][$list_name]["parent_id"] = $app->tform_actions->id; + $_SESSION["s"]["list"][$list_name]["parent_id"] = $this->form->id; + $_SESSION["s"]["list"][$list_name]["parent_name"] = $app->tform->formDef["name"]; + $_SESSION["s"]["list"][$list_name]["parent_tab"] = $_SESSION["s"]["form"]["tab"]; + $_SESSION["s"]["list"][$list_name]["parent_script"] = $app->tform->formDef["action"]; + $_SESSION["s"]["form"]["return_to"] = $list_name; + + return $listTpl->grab(); + } + } -?> \ No newline at end of file +?> diff --git a/interface/lib/classes/plugin_base.inc.php b/interface/lib/classes/plugin_base.inc.php index 5b69e03c4040ba8368b5ed9207c65d8b7f40b5bc..92b874437e03c93c034a220738a6a2c3ce4a3643 100644 --- a/interface/lib/classes/plugin_base.inc.php +++ b/interface/lib/classes/plugin_base.inc.php @@ -29,31 +29,31 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ class plugin_base { - + var $plugin_name; var $options; var $form; - + function onLoad() { - + } - + function onShow() { - + } - + function onInsert() { - + } - + function onUpdate() { - + } - + function onDelete() { - + } - + function setOptions($plugin_name, $options) { $this->options = $options; $this->plugin_name = $plugin_name; @@ -61,4 +61,4 @@ class plugin_base { } -?> \ No newline at end of file +?> diff --git a/interface/lib/classes/plugin_dbhistory.inc.php b/interface/lib/classes/plugin_dbhistory.inc.php index ebd9e745e64fae91adae9f9a188a35ca281c4365..c6547311106ab330d4cee9975af6b18711f9b4b8 100644 --- a/interface/lib/classes/plugin_dbhistory.inc.php +++ b/interface/lib/classes/plugin_dbhistory.inc.php @@ -30,40 +30,41 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class plugin_dbhistory extends plugin_base { - var $module; - var $form; - var $tab; - var $record_id; - var $formdef; - var $options; + var $module; + var $form; + var $tab; + var $record_id; + var $formdef; + var $options; - function onShow() { - - global $app, $conf; - - $content = ''; - - $db_table = $app->tform->formDef["db_table"]; - $db_table_idx = $app->tform->formDef["db_table_idx"]; - $primary_id = $this->form->id; - if($_SESSION["s"]["user"]["typ"] == 'admin') { - $sql = "SELECT action, tstamp, user, data FROM sys_datalog WHERE dbtable = '".$db_table."' AND dbidx = '".$db_table_idx.":".$primary_id."'"; - } else { - $sql = "SELECT action, tstamp, user, data FROM sys_datalog WHERE user = '".$_SESSION["s"]["user"]["username"]."' dbtable = '".$db_table."' AND dbidx = '".$db_table_idx.":".$primary_id."'"; - } - - $records = $app->db->queryAllRecords($sql); - if(is_array($records)) { - $content .= ''; - foreach($records as $rec) { - $content .= ""; - } - $content .= '
".date("d.m.Y",$rec["tstamp"])."".$rec["user"]."
'; + function onShow() { + + global $app, $conf; + + $content = ''; + + $db_table = $app->tform->formDef["db_table"]; + $db_table_idx = $app->tform->formDef["db_table_idx"]; + $primary_id = $this->form->id; + if($_SESSION["s"]["user"]["typ"] == 'admin') { + $sql = "SELECT action, tstamp, user, data FROM sys_datalog WHERE dbtable = '".$db_table."' AND dbidx = '".$db_table_idx.":".$primary_id."'"; + } else { + $sql = "SELECT action, tstamp, user, data FROM sys_datalog WHERE user = '".$_SESSION["s"]["user"]["username"]."' dbtable = '".$db_table."' AND dbidx = '".$db_table_idx.":".$primary_id."'"; + } + + $records = $app->db->queryAllRecords($sql); + if(is_array($records)) { + $content .= ''; + foreach($records as $rec) { + $content .= ""; } - - return $content; + $content .= '
".date("d.m.Y", $rec["tstamp"])."".$rec["user"]."
'; + } + + return $content; + + } - } } -?> \ No newline at end of file +?> diff --git a/interface/lib/classes/plugin_listview.inc.php b/interface/lib/classes/plugin_listview.inc.php index 30932b90f0946561029fe6ca03b534e8ab1f0de6..e7d576cd17a58c9af14ac3e4f7761ed4ea520bbb 100644 --- a/interface/lib/classes/plugin_listview.inc.php +++ b/interface/lib/classes/plugin_listview.inc.php @@ -30,153 +30,154 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. class plugin_listview extends plugin_base { - var $module; - var $form; - var $tab; - var $record_id; - var $formdef; - var $options; - - function onShow() { - - global $app; - - $app->uses('listform'); - $app->listform->loadListDef($this->options["listdef"]); - - //$app->listform->SQLExtWhere = "type = 'alias'"; - - $listTpl = new tpl; - $listTpl->newTemplate('templates/'.$app->listform->listDef["name"].'_list.htm'); - - //die(print_r($app->tform_actions)); - - // Changing some of the list values to reflect that the list is called within a tform page - $app->listform->listDef["file"] = $app->tform->formDef["action"]; - // $app->listform->listDef["page_params"] = "&id=".$app->tform_actions->id."&next_tab=".$_SESSION["s"]["form"]["tab"]; - $app->listform->listDef["page_params"] = "&id=".$this->form->id."&next_tab=".$_SESSION["s"]["form"]["tab"]; - $listTpl->setVar('parent_id',$this->form->id); - $listTpl->setVar('theme', $_SESSION['s']['theme']); - - // Generate the SQL for searching - $sql_where = ""; - if($app->listform->listDef["auth"] != 'no') { - if($_SESSION["s"]["user"]["typ"] != "admin") { + var $module; + var $form; + var $tab; + var $record_id; + var $formdef; + var $options; + + function onShow() { + + global $app; + + $app->uses('listform'); + $app->listform->loadListDef($this->options["listdef"]); + + //$app->listform->SQLExtWhere = "type = 'alias'"; + + $listTpl = new tpl; + $listTpl->newTemplate('templates/'.$app->listform->listDef["name"].'_list.htm'); + + //die(print_r($app->tform_actions)); + + // Changing some of the list values to reflect that the list is called within a tform page + $app->listform->listDef["file"] = $app->tform->formDef["action"]; + // $app->listform->listDef["page_params"] = "&id=".$app->tform_actions->id."&next_tab=".$_SESSION["s"]["form"]["tab"]; + $app->listform->listDef["page_params"] = "&id=".$this->form->id."&next_tab=".$_SESSION["s"]["form"]["tab"]; + $listTpl->setVar('parent_id', $this->form->id); + $listTpl->setVar('theme', $_SESSION['s']['theme']); + + // Generate the SQL for searching + $sql_where = ""; + if($app->listform->listDef["auth"] != 'no') { + if($_SESSION["s"]["user"]["typ"] != "admin") { $sql_where = $app->tform->getAuthSQL('r')." and"; - } - } - - if($this->options["sqlextwhere"] != '') { - $sql_where .= " ".$this->options["sqlextwhere"]." and"; - } - - $sql_where = $app->listform->getSearchSQL($sql_where); - $listTpl->setVar($app->listform->searchValues); - - // Generate SQL for paging - $limit_sql = $app->listform->getPagingSQL($sql_where); - $listTpl->setVar("paging",$app->listform->pagingHTML); - - $sql_order_by = ''; - if(isset($this->options["sql_order_by"])) { - $sql_order_by = $this->options["sql_order_by"]; - } + } + } + + if($this->options["sqlextwhere"] != '') { + $sql_where .= " ".$this->options["sqlextwhere"]." and"; + } + + $sql_where = $app->listform->getSearchSQL($sql_where); + $listTpl->setVar($app->listform->searchValues); + + // Generate SQL for paging + $limit_sql = $app->listform->getPagingSQL($sql_where); + $listTpl->setVar("paging", $app->listform->pagingHTML); + + $sql_order_by = ''; + if(isset($this->options["sql_order_by"])) { + $sql_order_by = $this->options["sql_order_by"]; + } //* Limit each page - $limits = array('5'=>'5','15'=>'15','25'=>'25','50'=>'50','100'=>'100','999999999' => 'all'); + $limits = array('5'=>'5', '15'=>'15', '25'=>'25', '50'=>'50', '100'=>'100', '999999999' => 'all'); //* create options and set selected, if default -> 15 is selected $options=''; foreach($limits as $key => $val){ - $options .= ''; + $options .= ''; } - $listTpl->setVar('search_limit',''); + $listTpl->setVar('search_limit', ''); //Sorting if(!isset($_SESSION['search'][$app->listform->listDef["name"]]['order'])){ - $_SESSION['search'][$app->listform->listDef["name"]]['order'] = ''; + $_SESSION['search'][$app->listform->listDef["name"]]['order'] = ''; } if(!empty($_GET['orderby'])){ - $order = str_replace('tbl_col_','',$_GET['orderby']); - //* Check the css class submited value - if (preg_match("/^[a-z\_]{1,}$/",$order)) { - if($_SESSION['search'][$app->listform->listDef["name"]]['order'] == $order){ - $_SESSION['search'][$app->listform->listDef["name"]]['order'] = $order.' DESC'; - } else { - $_SESSION['search'][$app->listform->listDef["name"]]['order'] = $order; - } - } + $order = str_replace('tbl_col_', '', $_GET['orderby']); + //* Check the css class submited value + if (preg_match("/^[a-z\_]{1,}$/", $order)) { + if($_SESSION['search'][$app->listform->listDef["name"]]['order'] == $order){ + $_SESSION['search'][$app->listform->listDef["name"]]['order'] = $order.' DESC'; + } else { + $_SESSION['search'][$app->listform->listDef["name"]]['order'] = $order; + } + } } // If a manuel oder by like customers isset the sorting will be infront if(!empty($_SESSION['search'][$app->listform->listDef["name"]]['order'])){ - if(empty($sql_order_by)){ - $sql_order_by = "ORDER BY ".$_SESSION['search'][$app->listform->listDef["name"]]['order']; - } else { - $sql_order_by = str_replace("ORDER BY ","ORDER BY ".$_SESSION['search'][$app->listform->listDef["name"]]['order'].', ',$sql_order_by); - } + if(empty($sql_order_by)){ + $sql_order_by = "ORDER BY ".$_SESSION['search'][$app->listform->listDef["name"]]['order']; + } else { + $sql_order_by = str_replace("ORDER BY ", "ORDER BY ".$_SESSION['search'][$app->listform->listDef["name"]]['order'].', ', $sql_order_by); + } } - - // Loading language field - $lng_file = "lib/lang/".$_SESSION["s"]["language"]."_".$app->listform->listDef['name']."_list.lng"; - include($lng_file); - $listTpl->setVar($wb); - - - // Get the data - $records = $app->db->queryAllRecords("SELECT * FROM ".$app->listform->listDef["table"]." WHERE $sql_where $sql_order_by $limit_sql"); - - $bgcolor = "#FFFFFF"; - if(is_array($records)) { - $idx_key = $app->listform->listDef["table_idx"]; - foreach($records as $rec) { - - $rec = $app->listform->decode($rec); - - // Change of color - $bgcolor = ($bgcolor == "#FFFFFF")?"#EEEEEE":"#FFFFFF"; - $rec["bgcolor"] = $bgcolor; - - // substitute value for select fields - foreach($app->listform->listDef["item"] as $field) { - $key = $field["field"]; - if($field['formtype'] == "SELECT") { - if(strtolower($rec[$key]) == 'y' or strtolower($rec[$key]) == 'n') { - // Set a additional image variable for bolean fields - $rec['_'.$key.'_'] = (strtolower($rec[$key]) == 'y')?'x16/tick_circle.png':'x16/cross_circle.png'; - } - //* substitute value for select field - @$rec[$key] = $field['value'][$rec[$key]]; - } - // Create a lowercase version of every item - $rec[$key.'_lowercase'] = strtolower($rec[$key]); - } - - // The variable "id" contains always the index field - $rec["id"] = $rec[$idx_key]; - $rec["delete_confirmation"] = $wb['delete_confirmation']; - - $records_new[] = $rec; - } - } - - $listTpl->setLoop('records',@$records_new); - - // Setting Returnto information in the session - $list_name = $app->listform->listDef["name"]; - // $_SESSION["s"]["list"][$list_name]["parent_id"] = $app->tform_actions->id; - $_SESSION["s"]["list"][$list_name]["parent_id"] = $this->form->id; - $_SESSION["s"]["list"][$list_name]["parent_name"] = $app->tform->formDef["name"]; - $_SESSION["s"]["list"][$list_name]["parent_tab"] = $_SESSION["s"]["form"]["tab"]; - $_SESSION["s"]["list"][$list_name]["parent_script"] = $app->tform->formDef["action"]; - $_SESSION["s"]["form"]["return_to"] = $list_name; - //die(print_r($_SESSION["s"]["list"][$list_name])); - - return $listTpl->grab(); - - } + + // Loading language field + $lng_file = "lib/lang/".$_SESSION["s"]["language"]."_".$app->listform->listDef['name']."_list.lng"; + include $lng_file; + $listTpl->setVar($wb); + + + // Get the data + $records = $app->db->queryAllRecords("SELECT * FROM ".$app->listform->listDef["table"]." WHERE $sql_where $sql_order_by $limit_sql"); + + $bgcolor = "#FFFFFF"; + if(is_array($records)) { + $idx_key = $app->listform->listDef["table_idx"]; + foreach($records as $rec) { + + $rec = $app->listform->decode($rec); + + // Change of color + $bgcolor = ($bgcolor == "#FFFFFF")?"#EEEEEE":"#FFFFFF"; + $rec["bgcolor"] = $bgcolor; + + // substitute value for select fields + foreach($app->listform->listDef["item"] as $field) { + $key = $field["field"]; + if($field['formtype'] == "SELECT") { + if(strtolower($rec[$key]) == 'y' or strtolower($rec[$key]) == 'n') { + // Set a additional image variable for bolean fields + $rec['_'.$key.'_'] = (strtolower($rec[$key]) == 'y')?'x16/tick_circle.png':'x16/cross_circle.png'; + } + //* substitute value for select field + @$rec[$key] = $field['value'][$rec[$key]]; + } + // Create a lowercase version of every item + $rec[$key.'_lowercase'] = strtolower($rec[$key]); + } + + // The variable "id" contains always the index field + $rec["id"] = $rec[$idx_key]; + $rec["delete_confirmation"] = $wb['delete_confirmation']; + + $records_new[] = $rec; + } + } + + $listTpl->setLoop('records', @$records_new); + + // Setting Returnto information in the session + $list_name = $app->listform->listDef["name"]; + // $_SESSION["s"]["list"][$list_name]["parent_id"] = $app->tform_actions->id; + $_SESSION["s"]["list"][$list_name]["parent_id"] = $this->form->id; + $_SESSION["s"]["list"][$list_name]["parent_name"] = $app->tform->formDef["name"]; + $_SESSION["s"]["list"][$list_name]["parent_tab"] = $_SESSION["s"]["form"]["tab"]; + $_SESSION["s"]["list"][$list_name]["parent_script"] = $app->tform->formDef["action"]; + $_SESSION["s"]["form"]["return_to"] = $list_name; + //die(print_r($_SESSION["s"]["list"][$list_name])); + + return $listTpl->grab(); + + } + } -?> \ No newline at end of file +?> diff --git a/interface/lib/classes/remoting.inc.php b/interface/lib/classes/remoting.inc.php index 55759f4bcea49cb6790c7beb966513ede96c36bd..bcd46659b161306c1410187545903e6bf5466772 100644 --- a/interface/lib/classes/remoting.inc.php +++ b/interface/lib/classes/remoting.inc.php @@ -35,38 +35,38 @@ Copyright (c) Tri-Plex technology */ class remoting { - + //* remote session timeout in seconds private $session_timeout = 600; - + protected $server; public $oldDataRecord; public $dataRecord; public $id; - + /* - These variables shall stay global. + These variables shall stay global. Please do not make them private variables. - + private $app; private $conf; */ - public function __construct() - { - global $server; - $this->server = $server; + public function __construct() + { + global $server; + $this->server = $server; /* $this->app = $app; $this->conf = $conf; */ - } + } //* remote login function public function login($username, $password) - { + { global $app, $conf, $server; - + // Maintenance mode $app->uses('ini_parser,getconf'); $server_config_array = $app->getconf->get_global_config('misc'); @@ -74,134 +74,136 @@ class remoting { $this->server->fault('maintenance_mode', 'This ISPConfig installation is currently under maintenance. We should be back shortly. Thank you for your patience.'); return false; } - + if(empty($username)) { $this->server->fault('login_username_empty', 'The login username is empty.'); return false; } - + if(empty($password)) { $this->server->fault('login_password_empty', 'The login password is empty.'); return false; } - + //* Delete old remoting sessions $sql = "DELETE FROM remote_session WHERE tstamp < ".time(); $app->db->query($sql); - + $username = $app->db->quote($username); $password = $app->db->quote($password); - + $sql = "SELECT * FROM remote_user WHERE remote_username = '$username' and remote_password = md5('$password')"; $remote_user = $app->db->queryOneRecord($sql); if($remote_user['remote_userid'] > 0) { //* Create a remote user session - srand ((double)microtime()*1000000); + srand((double)microtime()*1000000); $remote_session = md5(rand()); $remote_userid = $remote_user['remote_userid']; $remote_functions = $remote_user['remote_functions']; $tstamp = time() + $this->session_timeout; $sql = 'INSERT INTO remote_session (remote_session,remote_userid,remote_functions,tstamp' - .') VALUES (' - ." '$remote_session',$remote_userid,'$remote_functions',$tstamp)"; + .') VALUES (' + ." '$remote_session',$remote_userid,'$remote_functions',$tstamp)"; $app->db->query($sql); return $remote_session; } else { $this->server->fault('login_failed', 'The login failed. Username or password wrong.'); return false; } - + } - + //* remote logout function public function logout($session_id) - { + { global $app; - + if(empty($session_id)) { $this->server->fault('session_id_empty', 'The SessionID is empty.'); return false; } - + $session_id = $app->db->quote($session_id); - + $sql = "DELETE FROM remote_session WHERE remote_session = '$session_id'"; $app->db->query($sql); - return ($app->db->affectedRows() == 1); + return $app->db->affectedRows() == 1; + } + + + /** + Gets the server configuration + @param int session id + @param int server id + @param string section of the config field in the server table. Could be 'web', 'dns', 'mail', 'dns', 'cron', etc + @author Julio Montoya BeezNest 2010 + */ + + + public function server_get($session_id, $server_id, $section ='') { + global $app; + if(!$this->checkPerm($session_id, 'server_get')) { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + if (!empty($session_id) && !empty($server_id)) { + $app->uses('remoting_lib , getconf'); + $section_config = $app->getconf->get_server_config($server_id, $section); + return $section_config; + } else { + return false; + } } - - /** - Gets the server configuration - @param int session id - @param int server id - @param string section of the config field in the server table. Could be 'web', 'dns', 'mail', 'dns', 'cron', etc - @author Julio Montoya BeezNest 2010 - */ - public function server_get($session_id, $server_id, $section ='') { - global $app; - if(!$this->checkPerm($session_id, 'server_get')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; - } - if (!empty($session_id) && !empty($server_id)) { - $app->uses('remoting_lib , getconf'); - $section_config = $app->getconf->get_server_config($server_id,$section); - return $section_config; - } else { - return false; - } - } - public function server_get_serverid_by_ip($session_id, $ipaddress) - { - global $app; + { + global $app; if(!$this->checkPerm($session_id, 'server_get_serverid_by_ip')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; } - $sql = "SELECT server_id FROM server_ip WHERE ip_address = '$ipaddress' LIMIT 1 "; - $all = $app->db->queryAllRecords($sql); - return $all; + $sql = "SELECT server_id FROM server_ip WHERE ip_address = '$ipaddress' LIMIT 1 "; + $all = $app->db->queryAllRecords($sql); + return $all; } - + //* Add a IP address record public function server_ip_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'server_ip_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../admin/form/server_ip.tform.php',$client_id,$params); + return $this->insertQuery('../admin/form/server_ip.tform.php', $client_id, $params); } - + //* Update IP address record public function server_ip_update($session_id, $client_id, $ip_id, $params) - { + { if(!$this->checkPerm($session_id, 'server_ip_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../admin/form/server_ip.tform.php',$client_id,$ip_id,$params); + $affected_rows = $this->updateQuery('../admin/form/server_ip.tform.php', $client_id, $ip_id, $params); return $affected_rows; } - + //* Delete IP address record public function server_ip_delete($session_id, $ip_id) - { + { if(!$this->checkPerm($session_id, 'server_ip_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../admin/form/server_ip.tform.php',$ip_id); + $affected_rows = $this->deleteQuery('../admin/form/server_ip.tform.php', $ip_id); return $affected_rows; } - + //* Get mail domain details public function mail_domain_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_domain_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -210,21 +212,21 @@ class remoting { $app->remoting_lib->loadFormDef('../mail/form/mail_domain.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a mail domain public function mail_domain_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'mail_domain_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $primary_id = $this->insertQuery('../mail/form/mail_domain.tform.php',$client_id,$params); + $primary_id = $this->insertQuery('../mail/form/mail_domain.tform.php', $client_id, $params); return $primary_id; } - + //* Update a mail domain public function mail_domain_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'mail_domain_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -232,10 +234,10 @@ class remoting { $affected_rows = $this->updateQuery('../mail/form/mail_domain.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a mail domain public function mail_domain_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'mail_domain_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -243,12 +245,12 @@ class remoting { $affected_rows = $this->deleteQuery('../mail/form/mail_domain.tform.php', $primary_id); return $affected_rows; } - + //* Get alias details public function mail_aliasdomain_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_aliasdomain_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -257,13 +259,13 @@ class remoting { $app->remoting_lib->loadFormDef('../mail/form/mail_aliasdomain.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* aliasy email public function mail_aliasdomain_add($session_id, $client_id, $params) { if (!$this->checkPerm($session_id, 'mail_aliasdomain_add')) { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } $affected_rows = $this->insertQuery('../mail/form/mail_aliasdomain.tform.php', $client_id, $params); @@ -273,31 +275,31 @@ class remoting { public function mail_aliasdomain_update($session_id, $client_id, $primary_id, $params) { - if (!$this->checkPerm($session_id, 'mail_aliasdomain_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->updateQuery('../mail/form/mail_aliasdomain.tform.php', $client_id, $primary_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_aliasdomain_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->updateQuery('../mail/form/mail_aliasdomain.tform.php', $client_id, $primary_id, $params); + return $affected_rows; } public function mail_aliasdomain_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_aliasdomain_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/mail_aliasdomain.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_aliasdomain_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/mail_aliasdomain.tform.php', $primary_id); + return $affected_rows; } - + //* Get mail mailinglist details public function mail_mailinglist_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_mailinglist_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -306,21 +308,21 @@ class remoting { $app->remoting_lib->loadFormDef('../mail/form/mail_mailinglist.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a mail mailinglist public function mail_mailinglist_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'mail_mailinglist_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $primary_id = $this->insertQuery('../mail/form/mail_mailinglist.tform.php',$client_id,$params); + $primary_id = $this->insertQuery('../mail/form/mail_mailinglist.tform.php', $client_id, $params); return $primary_id; } - + //* Update a mail mailinglist public function mail_mailinglist_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'mail_mailinglist_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -328,10 +330,10 @@ class remoting { $affected_rows = $this->updateQuery('../mail/form/mail_mailinglist.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a mail mailinglist public function mail_mailinglist_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'mail_mailinglist_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -339,12 +341,12 @@ class remoting { $affected_rows = $this->deleteQuery('../mail/form/mail_mailinglist.tform.php', $primary_id); return $affected_rows; } - + //* Get mail user details public function mail_user_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_user_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -353,70 +355,70 @@ class remoting { $app->remoting_lib->loadFormDef('../mail/form/mail_user.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - - + + //* Add mail domain public function mail_user_add($session_id, $client_id, $params){ global $app; - + if (!$this->checkPerm($session_id, 'mail_user_add')){ - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + //* Check if mail domain exists - $email_parts = explode('@',$params['email']); + $email_parts = explode('@', $params['email']); $tmp = $app->db->queryOneRecord("SELECT domain FROM mail_domain WHERE domain = '".$app->db->quote($email_parts[1])."'"); if($tmp['domain'] != $email_parts[1]) { - $this->server->fault('mail_domain_does_not_exist','Mail domain - '.$email_parts[1].' - does not exist.'); + $this->server->fault('mail_domain_does_not_exist', 'Mail domain - '.$email_parts[1].' - does not exist.'); return false; } - + $affected_rows = $this->insertQuery('../mail/form/mail_user.tform.php', $client_id, $params); return $affected_rows; } - //* Update mail user + //* Update mail user public function mail_user_update($session_id, $client_id, $primary_id, $params) { global $app; - + if (!$this->checkPerm($session_id, 'mail_user_update')) { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + //* Check if mail domain exists - $email_parts = explode('@',$params['email']); + $email_parts = explode('@', $params['email']); $tmp = $app->db->queryOneRecord("SELECT domain FROM mail_domain WHERE domain = '".$app->db->quote($email_parts[1])."'"); if($tmp['domain'] != $email_parts[1]) { - $this->server->fault('mail_domain_does_not_exist','Mail domain - '.$email_parts[1].' - does not exist.'); + $this->server->fault('mail_domain_does_not_exist', 'Mail domain - '.$email_parts[1].' - does not exist.'); return false; } - + $affected_rows = $this->updateQuery('../mail/form/mail_user.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete mail user public function mail_user_delete($session_id, $primary_id) { if (!$this->checkPerm($session_id, 'mail_user_delete')) { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } $affected_rows = $this->deleteQuery('../mail/form/mail_user.tform.php', $primary_id); return $affected_rows; } - + //* Get mail user filter details public function mail_user_filter_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_user_filter_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -425,15 +427,15 @@ class remoting { $app->remoting_lib->loadFormDef('../mail/form/mail_user_filter.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + public function mail_user_filter_add($session_id, $client_id, $params) { global $app; if (!$this->checkPerm($session_id, 'mail_user_filter_add')){ - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->insertQuery('../mail/form/mail_user_filter.tform.php', $client_id, $params,'mail:mail_user_filter:on_after_insert'); + $affected_rows = $this->insertQuery('../mail/form/mail_user_filter.tform.php', $client_id, $params, 'mail:mail_user_filter:on_after_insert'); // $app->plugin->raiseEvent('mail:mail_user_filter:on_after_insert',$this); return $affected_rows; } @@ -443,10 +445,10 @@ class remoting { global $app; if (!$this->checkPerm($session_id, 'mail_user_filter_update')) { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../mail/form/mail_user_filter.tform.php', $client_id, $primary_id, $params,'mail:mail_user_filter:on_after_update'); + $affected_rows = $this->updateQuery('../mail/form/mail_user_filter.tform.php', $client_id, $primary_id, $params, 'mail:mail_user_filter:on_after_update'); // $app->plugin->raiseEvent('mail:mail_user_filter:on_after_update',$this); return $affected_rows; } @@ -456,19 +458,19 @@ class remoting { global $app; if (!$this->checkPerm($session_id, 'mail_user_filter_delete')) { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../mail/form/mail_user_filter.tform.php', $primary_id,'mail:mail_user_filter:on_after_delete'); + $affected_rows = $this->deleteQuery('../mail/form/mail_user_filter.tform.php', $primary_id, 'mail:mail_user_filter:on_after_delete'); // $app->plugin->raiseEvent('mail:mail_user_filter:on_after_delete',$this); return $affected_rows; } //* Get alias details public function mail_alias_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_alias_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -477,25 +479,25 @@ class remoting { $app->remoting_lib->loadFormDef('../mail/form/mail_alias.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* aliasy email public function mail_alias_add($session_id, $client_id, $params) { global $app; - + if (!$this->checkPerm($session_id, 'mail_alias_add')) { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + //* Check if there is no active mailbox with this address $tmp = $app->db->queryOneRecord("SELECT count(mailuser_id) as number FROM mail_user WHERE postfix = 'y' AND email = '".$app->db->quote($params["source"])."'"); if($tmp['number'] > 0) { - $this->server->fault('duplicate','There is already a mailbox with this email address.'); + $this->server->fault('duplicate', 'There is already a mailbox with this email address.'); } unset($tmp); - + $affected_rows = $this->insertQuery('../mail/form/mail_alias.tform.php', $client_id, $params); return $affected_rows; } @@ -504,40 +506,40 @@ class remoting { public function mail_alias_update($session_id, $client_id, $primary_id, $params) { global $app; - + if (!$this->checkPerm($session_id, 'mail_alias_update')) { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - - //* Check if there is no active mailbox with this address + + //* Check if there is no active mailbox with this address $tmp = $app->db->queryOneRecord("SELECT count(mailuser_id) as number FROM mail_user WHERE postfix = 'y' AND email = '".$app->db->quote($params["source"])."'"); if($tmp['number'] > 0) { - $this->server->fault('duplicate','There is already a mailbox with this email address.'); + $this->server->fault('duplicate', 'There is already a mailbox with this email address.'); } unset($tmp); - + $affected_rows = $this->updateQuery('../mail/form/mail_alias.tform.php', $client_id, $primary_id, $params); return $affected_rows; } public function mail_alias_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_alias_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/mail_alias.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_alias_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/mail_alias.tform.php', $primary_id); + return $affected_rows; } - + //* Get mail forwarding details public function mail_forward_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_forward_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -546,48 +548,48 @@ class remoting { $app->remoting_lib->loadFormDef('../mail/form/mail_forward.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - - //* przekierowania email + + //* przekierowania email public function mail_forward_add($session_id, $client_id, $params) { - if (!$this->checkPerm($session_id, 'mail_forward_add')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->insertQuery('../mail/form/mail_forward.tform.php', $client_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_forward_add')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->insertQuery('../mail/form/mail_forward.tform.php', $client_id, $params); + return $affected_rows; } public function mail_forward_update($session_id, $client_id, $primary_id, $params) { - if (!$this->checkPerm($session_id, 'mail_forward_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->updateQuery('../mail/form/mail_forward.tform.php', $client_id, $primary_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_forward_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->updateQuery('../mail/form/mail_forward.tform.php', $client_id, $primary_id, $params); + return $affected_rows; } public function mail_forward_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_forward_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/mail_forward.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_forward_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/mail_forward.tform.php', $primary_id); + return $affected_rows; } - + //* Get catchall details public function mail_catchall_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_catchall_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -598,44 +600,44 @@ class remoting { } //* catchall e-mail - public function mail_catchall_add($session_id, $client_id, $params) + public function mail_catchall_add($session_id, $client_id, $params) { - if (!$this->checkPerm($session_id, 'mail_catchall_add')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->insertQuery('../mail/form/mail_domain_catchall.tform.php', $client_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_catchall_add')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->insertQuery('../mail/form/mail_domain_catchall.tform.php', $client_id, $params); + return $affected_rows; } public function mail_catchall_update($session_id, $client_id, $primary_id, $params) { - if (!$this->checkPerm($session_id, 'mail_catchall_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->updateQuery('../mail/form/mail_domain_catchall.tform.php', $client_id, $primary_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_catchall_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->updateQuery('../mail/form/mail_domain_catchall.tform.php', $client_id, $primary_id, $params); + return $affected_rows; } public function mail_catchall_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_catchall_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/mail_domain_catchall.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_catchall_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/mail_domain_catchall.tform.php', $primary_id); + return $affected_rows; } - + //* Get transport details public function mail_transport_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_transport_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -644,48 +646,48 @@ class remoting { $app->remoting_lib->loadFormDef('../mail/form/mail_transport.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* przeniesienia e-mail public function mail_transport_add($session_id, $client_id, $params) { - if (!$this->checkPerm($session_id, 'mail_transport_add')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->insertQuery('../mail/form/mail_transport.tform.php', $client_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_transport_add')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->insertQuery('../mail/form/mail_transport.tform.php', $client_id, $params); + return $affected_rows; } public function mail_transport_update($session_id, $client_id, $primary_id, $params) { - if (!$this->checkPerm($session_id, 'mail_transport_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->updateQuery('../mail/form/mail_transport.tform.php', $client_id, $primary_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_transport_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->updateQuery('../mail/form/mail_transport.tform.php', $client_id, $primary_id, $params); + return $affected_rows; } public function mail_transport_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_transport_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/mail_transport.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_transport_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/mail_transport.tform.php', $primary_id); + return $affected_rows; } - + //* Get spamfilter whitelist details public function mail_spamfilter_whitelist_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_spamfilter_whitelist_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -695,47 +697,47 @@ class remoting { return $app->remoting_lib->getDataRecord($primary_id); } - //* biała lista e-mail + //* biała lista e-mail public function mail_spamfilter_whitelist_add($session_id, $client_id, $params) { - if (!$this->checkPerm($session_id, 'mail_spamfilter_whitelist_add')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->insertQuery('../mail/form/spamfilter_whitelist.tform.php', $client_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_spamfilter_whitelist_add')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->insertQuery('../mail/form/spamfilter_whitelist.tform.php', $client_id, $params); + return $affected_rows; } public function mail_spamfilter_whitelist_update($session_id, $client_id, $primary_id, $params) { - if (!$this->checkPerm($session_id, 'mail_spamfilter_whitelist_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->updateQuery('../mail/form/spamfilter_whitelist.tform.php', $client_id, $primary_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_spamfilter_whitelist_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->updateQuery('../mail/form/spamfilter_whitelist.tform.php', $client_id, $primary_id, $params); + return $affected_rows; } public function mail_spamfilter_whitelist_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_spamfilter_whitelist_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/spamfilter_whitelist.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_spamfilter_whitelist_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/spamfilter_whitelist.tform.php', $primary_id); + return $affected_rows; } - + //* Get spamfilter blacklist details public function mail_spamfilter_blacklist_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_spamfilter_blacklist_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -744,48 +746,48 @@ class remoting { $app->remoting_lib->loadFormDef('../mail/form/spamfilter_blacklist.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - - //* czarna lista e-mail + + //* czarna lista e-mail public function mail_spamfilter_blacklist_add($session_id, $client_id, $params) { - if (!$this->checkPerm($session_id, 'mail_spamfilter_blacklist_add')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->insertQuery('../mail/form/spamfilter_blacklist.tform.php', $client_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_spamfilter_blacklist_add')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->insertQuery('../mail/form/spamfilter_blacklist.tform.php', $client_id, $params); + return $affected_rows; } public function mail_spamfilter_blacklist_update($session_id, $client_id, $primary_id, $params) { - if (!$this->checkPerm($session_id, 'mail_spamfilter_blacklist_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->updateQuery('../mail/form/spamfilter_blacklist.tform.php', $client_id, $primary_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_spamfilter_blacklist_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->updateQuery('../mail/form/spamfilter_blacklist.tform.php', $client_id, $primary_id, $params); + return $affected_rows; } public function mail_spamfilter_blacklist_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_spamfilter_blacklist_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/spamfilter_blacklist.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_spamfilter_blacklist_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/spamfilter_blacklist.tform.php', $primary_id); + return $affected_rows; } - + //* Get spamfilter user details public function mail_spamfilter_user_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_spamfilter_user_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -798,44 +800,44 @@ class remoting { //* filtr spamu użytkowników e-mail public function mail_spamfilter_user_add($session_id, $client_id, $params) { - if (!$this->checkPerm($session_id, 'mail_spamfilter_user_add')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->insertQuery('../mail/form/spamfilter_users.tform.php', $client_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_spamfilter_user_add')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->insertQuery('../mail/form/spamfilter_users.tform.php', $client_id, $params); + return $affected_rows; } public function mail_spamfilter_user_update($session_id, $client_id, $primary_id, $params) { - if (!$this->checkPerm($session_id, 'mail_spamfilter_user_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->updateQuery('../mail/form/spamfilter_users.tform.php', $client_id, $primary_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_spamfilter_user_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->updateQuery('../mail/form/spamfilter_users.tform.php', $client_id, $primary_id, $params); + return $affected_rows; } public function mail_spamfilter_user_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_spamfilter_user_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/spamfilter_users.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_spamfilter_user_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/spamfilter_users.tform.php', $primary_id); + return $affected_rows; } - + //* Get policy details public function mail_policy_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_policy_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -844,48 +846,48 @@ class remoting { $app->remoting_lib->loadFormDef('../mail/form/spamfilter_policy.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - - //* polityki filtrów spamu e-mail + + //* polityki filtrów spamu e-mail public function mail_policy_add($session_id, $client_id, $params) { - if (!$this->checkPerm($session_id, 'mail_policy_add')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->insertQuery('../mail/form/spamfilter_policy.tform.php', $client_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_policy_add')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->insertQuery('../mail/form/spamfilter_policy.tform.php', $client_id, $params); + return $affected_rows; } public function mail_policy_update($session_id, $client_id, $primary_id, $params) { - if (!$this->checkPerm($session_id, 'mail_policy_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->updateQuery('../mail/form/spamfilter_policy.tform.php', $client_id, $primary_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_policy_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->updateQuery('../mail/form/spamfilter_policy.tform.php', $client_id, $primary_id, $params); + return $affected_rows; } public function mail_policy_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_policy_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/spamfilter_policy.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_policy_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/spamfilter_policy.tform.php', $primary_id); + return $affected_rows; } - + //* Get fetchmail details public function mail_fetchmail_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_fetchmail_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -895,47 +897,47 @@ class remoting { return $app->remoting_lib->getDataRecord($primary_id); } - //* fetchmail + //* fetchmail public function mail_fetchmail_add($session_id, $client_id, $params) { - if (!$this->checkPerm($session_id, 'mail_fetchmail_add')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->insertQuery('../mail/form/mail_get.tform.php', $client_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_fetchmail_add')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->insertQuery('../mail/form/mail_get.tform.php', $client_id, $params); + return $affected_rows; } public function mail_fetchmail_update($session_id, $client_id, $primary_id, $params) { - if (!$this->checkPerm($session_id, 'mail_fetchmail_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->updateQuery('../mail/form/mail_get.tform.php', $client_id, $primary_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_fetchmail_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->updateQuery('../mail/form/mail_get.tform.php', $client_id, $primary_id, $params); + return $affected_rows; } public function mail_fetchmail_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_fetchmail_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/mail_get.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_fetchmail_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/mail_get.tform.php', $primary_id); + return $affected_rows; } - + //* Get whitelist details public function mail_whitelist_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_whitelist_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -944,48 +946,48 @@ class remoting { $app->remoting_lib->loadFormDef('../mail/form/mail_whitelist.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* wpisy białej listy public function mail_whitelist_add($session_id, $client_id, $params) { - if (!$this->checkPerm($session_id, 'mail_whitelist_add')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->insertQuery('../mail/form/mail_whitelist.tform.php', $client_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_whitelist_add')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->insertQuery('../mail/form/mail_whitelist.tform.php', $client_id, $params); + return $affected_rows; } public function mail_whitelist_update($session_id, $client_id, $primary_id, $params) { - if (!$this->checkPerm($session_id, 'mail_whitelist_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->updateQuery('../mail/form/mail_whitelist.tform.php', $client_id, $primary_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_whitelist_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->updateQuery('../mail/form/mail_whitelist.tform.php', $client_id, $primary_id, $params); + return $affected_rows; } public function mail_whitelist_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_whitelist_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/mail_whitelist.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_whitelist_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/mail_whitelist.tform.php', $primary_id); + return $affected_rows; } - + //* Get Blacklist details public function mail_blacklist_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_blacklist_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -994,48 +996,48 @@ class remoting { $app->remoting_lib->loadFormDef('../mail/form/mail_blacklist.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* wpisy białej listy public function mail_blacklist_add($session_id, $client_id, $params) { - if (!$this->checkPerm($session_id, 'mail_blacklist_add')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->insertQuery('../mail/form/mail_blacklist.tform.php', $client_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_blacklist_add')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->insertQuery('../mail/form/mail_blacklist.tform.php', $client_id, $params); + return $affected_rows; } public function mail_blacklist_update($session_id, $client_id, $primary_id, $params) { - if (!$this->checkPerm($session_id, 'mail_blacklist_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->updateQuery('../mail/form/mail_blacklist.tform.php', $client_id, $primary_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_blacklist_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->updateQuery('../mail/form/mail_blacklist.tform.php', $client_id, $primary_id, $params); + return $affected_rows; } public function mail_blacklist_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_blacklist_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/mail_blacklist.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_blacklist_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/mail_blacklist.tform.php', $primary_id); + return $affected_rows; } - + //* Get filter details public function mail_filter_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'mail_filter_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -1048,55 +1050,55 @@ class remoting { //* wpisy filtrow e-mail public function mail_filter_add($session_id, $client_id, $params) { - if (!$this->checkPerm($session_id, 'mail_filter_add')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->insertQuery('../mail/form/mail_content_filter.tform.php', $client_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_filter_add')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->insertQuery('../mail/form/mail_content_filter.tform.php', $client_id, $params); + return $affected_rows; } public function mail_filter_update($session_id, $client_id, $primary_id, $params) { - if (!$this->checkPerm($session_id, 'mail_filter_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->updateQuery('../mail/form/mail_content_filter.tform.php', $client_id, $primary_id, $params); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_filter_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->updateQuery('../mail/form/mail_content_filter.tform.php', $client_id, $primary_id, $params); + return $affected_rows; } public function mail_filter_delete($session_id, $primary_id) { - if (!$this->checkPerm($session_id, 'mail_filter_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - $affected_rows = $this->deleteQuery('../mail/form/mail_content_filter.tform.php', $primary_id); - return $affected_rows; + if (!$this->checkPerm($session_id, 'mail_filter_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../mail/form/mail_content_filter.tform.php', $primary_id); + return $affected_rows; } -/* - * - * - * + /* + * + * + * * * Client functions - * - * + * + * */ //* Get client details public function client_get($session_id, $client_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'client_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -1104,51 +1106,51 @@ class remoting { $app->uses('remoting_lib'); $app->remoting_lib->loadFormDef('../client/form/client.tform.php'); $data = $app->remoting_lib->getDataRecord($client_id); - - // we need to get the new-style templates for backwards-compatibility - maybe we remove this in a later version - if(is_array($data) && count($data) > 0) { - if(isset($data['client_id'])) { - // this is a single record - if($data['template_additional'] == '') { - $tpls = $app->db->queryAllRecords('SELECT CONCAT(`assigned_template_id`, \':\', `client_template_id`) as `item` FROM `client_template_assigned` WHERE `client_id` = ' . $data['client_id']); - $tpl_arr = array(); - if($tpls) { - foreach($tpls as $tpl) $tpl_arr[] = $tpl['item']; - } - $data['template_additional'] = implode('/', $tpl_arr); - unset($tpl_arr); - unset($tpls); - } - } elseif(isset($data[0]['client_id'])) { - // multiple client records - foreach($data as $index => $client) { - if($client['template_additional'] == '') { - $tpls = $app->db->queryAllRecords('SELECT CONCAT(`assigned_template_id`, \':\', `client_template_id`) as `item` FROM `client_template_assigned` WHERE `client_id` = ' . $client['client_id']); - $tpl_arr = array(); - if($tpls) { - foreach($tpls as $tpl) $tpl_arr[] = $tpl['item']; - } - $data[$index]['template_additional'] = implode('/', $tpl_arr); // dont use the $client array here - changes would not be returned to soap - } - unset($tpl_arr); - unset($tpls); - } - } - } - - return $data; - } - + + // we need to get the new-style templates for backwards-compatibility - maybe we remove this in a later version + if(is_array($data) && count($data) > 0) { + if(isset($data['client_id'])) { + // this is a single record + if($data['template_additional'] == '') { + $tpls = $app->db->queryAllRecords('SELECT CONCAT(`assigned_template_id`, \':\', `client_template_id`) as `item` FROM `client_template_assigned` WHERE `client_id` = ' . $data['client_id']); + $tpl_arr = array(); + if($tpls) { + foreach($tpls as $tpl) $tpl_arr[] = $tpl['item']; + } + $data['template_additional'] = implode('/', $tpl_arr); + unset($tpl_arr); + unset($tpls); + } + } elseif(isset($data[0]['client_id'])) { + // multiple client records + foreach($data as $index => $client) { + if($client['template_additional'] == '') { + $tpls = $app->db->queryAllRecords('SELECT CONCAT(`assigned_template_id`, \':\', `client_template_id`) as `item` FROM `client_template_assigned` WHERE `client_id` = ' . $client['client_id']); + $tpl_arr = array(); + if($tpls) { + foreach($tpls as $tpl) $tpl_arr[] = $tpl['item']; + } + $data[$index]['template_additional'] = implode('/', $tpl_arr); // dont use the $client array here - changes would not be returned to soap + } + unset($tpl_arr); + unset($tpls); + } + } + } + + return $data; + } + public function client_get_id($session_id, $sys_userid) - { + { global $app; if(!$this->checkPerm($session_id, 'client_get_id')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + $sys_userid = $app->functions->intval($sys_userid); - + $rec = $app->db->queryOneRecord("SELECT client_id FROM sys_user WHERE userid = ".$sys_userid); if(isset($rec['client_id'])) { return $app->functions->intval($rec['client_id']); @@ -1156,19 +1158,19 @@ class remoting { $this->server->fault('no_client_found', 'There is no sysuser account for this client ID.'); return false; } - + } - + public function client_get_groupid($session_id, $client_id) - { + { global $app; if(!$this->checkPerm($session_id, 'client_get_id')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + $client_id = $app->functions->intval($client_id); - + $rec = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ".$client_id); if(isset($rec['groupid'])) { return $app->functions->intval($rec['groupid']); @@ -1176,228 +1178,228 @@ class remoting { $this->server->fault('no_group_found', 'There is no group for this client ID.'); return false; } - + } - - + + public function client_add($session_id, $reseller_id, $params) { if (!$this->checkPerm($session_id, 'client_add')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; - } - if(!isset($params['parent_client_id']) || $params['parent_client_id'] == 0) $params['parent_client_id'] = $reseller_id; - $affected_rows = $this->klientadd('../client/form/' . (isset($params['limit_client']) && $params['limit_client'] > 0 ? 'reseller' : 'client') . '.tform.php',$reseller_id, $params); - return $affected_rows; - + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + if(!isset($params['parent_client_id']) || $params['parent_client_id'] == 0) $params['parent_client_id'] = $reseller_id; + $affected_rows = $this->klientadd('../client/form/' . (isset($params['limit_client']) && $params['limit_client'] > 0 ? 'reseller' : 'client') . '.tform.php', $reseller_id, $params); + return $affected_rows; + } - + public function client_update($session_id, $client_id, $reseller_id, $params) { - global $app; - - if (!$this->checkPerm($session_id, 'client_update')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; + global $app; + + if (!$this->checkPerm($session_id, 'client_update')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + + $app->uses('remoting_lib'); + $app->remoting_lib->loadFormDef('../client/form/' . (isset($params['limit_client']) && $params['limit_client'] > 0 ? 'reseller' : 'client') . '.tform.php'); + $old_rec = $app->remoting_lib->getDataRecord($client_id); + + // we need the previuos templates assigned here + $this->oldTemplatesAssigned = $app->db->queryAllRecords('SELECT * FROM `client_template_assigned` WHERE `client_id` = ' . $client_id); + if(!is_array($this->oldTemplatesAssigned) || count($this->oldTemplatesAssigned) < 1) { + // check previous type of storing templates + $tpls = explode('/', $old_rec['template_additional']); + $this->oldTemplatesAssigned = array(); + foreach($tpls as $item) { + $item = trim($item); + if(!$item) continue; + $this->oldTemplatesAssigned[] = array('assigned_template_id' => 0, 'client_template_id' => $item, 'client_id' => $client_id); } - - $app->uses('remoting_lib'); - $app->remoting_lib->loadFormDef('../client/form/' . (isset($params['limit_client']) && $params['limit_client'] > 0 ? 'reseller' : 'client') . '.tform.php'); - $old_rec = $app->remoting_lib->getDataRecord($client_id); - - // we need the previuos templates assigned here - $this->oldTemplatesAssigned = $app->db->queryAllRecords('SELECT * FROM `client_template_assigned` WHERE `client_id` = ' . $client_id); - if(!is_array($this->oldTemplatesAssigned) || count($this->oldTemplatesAssigned) < 1) { - // check previous type of storing templates - $tpls = explode('/', $old_rec['template_additional']); - $this->oldTemplatesAssigned = array(); - foreach($tpls as $item) { - $item = trim($item); - if(!$item) continue; - $this->oldTemplatesAssigned[] = array('assigned_template_id' => 0, 'client_template_id' => $item, 'client_id' => $client_id); - } - unset($tpls); - } - if(isset($params['template_additional'])) { - $app->uses('client_templates'); - $templates = explode('/', $params['template_additional']); - $params['template_additional'] = ''; - $app->client_templates->update_client_templates($client_id, $templates); - unset($templates); - } - - - if(!isset($params['parent_client_id']) || $params['parent_client_id'] == 0) $params['parent_client_id'] = $reseller_id; - $affected_rows = $this->updateQuery('../client/form/' . (isset($params['limit_client']) && $params['limit_client'] > 0 ? 'reseller' : 'client') . '.tform.php', $reseller_id, $client_id, $params, 'client:' . ($reseller_id ? 'reseller' : 'client') . ':on_after_update'); - - $app->remoting_lib->ispconfig_sysuser_update($params,$client_id); - - return $affected_rows; + unset($tpls); + } + if(isset($params['template_additional'])) { + $app->uses('client_templates'); + $templates = explode('/', $params['template_additional']); + $params['template_additional'] = ''; + $app->client_templates->update_client_templates($client_id, $templates); + unset($templates); + } + + + if(!isset($params['parent_client_id']) || $params['parent_client_id'] == 0) $params['parent_client_id'] = $reseller_id; + $affected_rows = $this->updateQuery('../client/form/' . (isset($params['limit_client']) && $params['limit_client'] > 0 ? 'reseller' : 'client') . '.tform.php', $reseller_id, $client_id, $params, 'client:' . ($reseller_id ? 'reseller' : 'client') . ':on_after_update'); + + $app->remoting_lib->ispconfig_sysuser_update($params, $client_id); + + return $affected_rows; } - - public function client_template_additional_get($session_id, $client_id) { - global $app; + + public function client_template_additional_get($session_id, $client_id) { + global $app; if(!$this->checkPerm($session_id, 'client_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - - if(@is_numeric($client_id)) { - $sql = "SELECT * FROM `client_template_assigned` WHERE `client_id` = ".$client_id; - return $app->db->queryOneRecord($sql); - } else { - $this->server->fault('The ID must be an integer.'); - return array(); - } - } - - private function _set_client_formdata($client_id) { - global $app; - - $this->id = $client_id; - $this->dataRecord = $app->db->queryOneRecord('SELECT * FROM `client` WHERE `client_id` = ' . $client_id); - $this->oldDataRecord = $this->dataRecord; - - $this->oldTemplatesAssigned = $app->db->queryAllRecords('SELECT * FROM `client_template_assigned` WHERE `client_id` = ' . $client_id); - if(!is_array($this->oldTemplatesAssigned) || count($this->oldTemplatesAssigned) < 1) { - // check previous type of storing templates - $tpls = explode('/', $this->oldDataRecord['template_additional']); - $this->oldTemplatesAssigned = array(); - foreach($tpls as $item) { - $item = trim($item); - if(!$item) continue; - $this->oldTemplatesAssigned[] = array('assigned_template_id' => 0, 'client_template_id' => $item, 'client_id' => $client_id); - } - unset($tpls); - } - } - - public function client_template_additional_add($session_id, $client_id, $template_id) { - global $app; - + + if(@is_numeric($client_id)) { + $sql = "SELECT * FROM `client_template_assigned` WHERE `client_id` = ".$client_id; + return $app->db->queryOneRecord($sql); + } else { + $this->server->fault('The ID must be an integer.'); + return array(); + } + } + + private function _set_client_formdata($client_id) { + global $app; + + $this->id = $client_id; + $this->dataRecord = $app->db->queryOneRecord('SELECT * FROM `client` WHERE `client_id` = ' . $client_id); + $this->oldDataRecord = $this->dataRecord; + + $this->oldTemplatesAssigned = $app->db->queryAllRecords('SELECT * FROM `client_template_assigned` WHERE `client_id` = ' . $client_id); + if(!is_array($this->oldTemplatesAssigned) || count($this->oldTemplatesAssigned) < 1) { + // check previous type of storing templates + $tpls = explode('/', $this->oldDataRecord['template_additional']); + $this->oldTemplatesAssigned = array(); + foreach($tpls as $item) { + $item = trim($item); + if(!$item) continue; + $this->oldTemplatesAssigned[] = array('assigned_template_id' => 0, 'client_template_id' => $item, 'client_id' => $client_id); + } + unset($tpls); + } + } + + public function client_template_additional_add($session_id, $client_id, $template_id) { + global $app; + if(!$this->checkPerm($session_id, 'client_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - - if(@is_numeric($client_id) && @is_numeric($template_id)) { - // check if client exists - $check = $app->db->queryOneRecord('SELECT `client_id` FROM `client` WHERE `client_id` = ' . $client_id); - if(!$check) { - $this->server->fault('Invalid client'); - return false; - } - // check if template exists - $check = $app->db->queryOneRecord('SELECT `template_id` FROM `client_template` WHERE `template_id` = ' . $template_id); - if(!$check) { - $this->server->fault('Invalid template'); - return false; - } - - // for the update event we have to cheat a bit - $this->_set_client_formdata($client_id); - - $sql = "INSERT INTO `client_template_assigned` (`client_id`, `client_template_id`) VALUES (" . $client_id . ", " . $template_id . ")"; - $app->db->query($sql); - $insert_id = $app->db->insertID(); - - $app->plugin->raiseEvent('client:client:on_after_update',$this); - - return $insert_id; - } else { - $this->server->fault('The IDs must be of type integer.'); - return false; - } - } - - public function client_template_additional_delete($session_id, $client_id, $assigned_template_id) { - global $app; - + + if(@is_numeric($client_id) && @is_numeric($template_id)) { + // check if client exists + $check = $app->db->queryOneRecord('SELECT `client_id` FROM `client` WHERE `client_id` = ' . $client_id); + if(!$check) { + $this->server->fault('Invalid client'); + return false; + } + // check if template exists + $check = $app->db->queryOneRecord('SELECT `template_id` FROM `client_template` WHERE `template_id` = ' . $template_id); + if(!$check) { + $this->server->fault('Invalid template'); + return false; + } + + // for the update event we have to cheat a bit + $this->_set_client_formdata($client_id); + + $sql = "INSERT INTO `client_template_assigned` (`client_id`, `client_template_id`) VALUES (" . $client_id . ", " . $template_id . ")"; + $app->db->query($sql); + $insert_id = $app->db->insertID(); + + $app->plugin->raiseEvent('client:client:on_after_update', $this); + + return $insert_id; + } else { + $this->server->fault('The IDs must be of type integer.'); + return false; + } + } + + public function client_template_additional_delete($session_id, $client_id, $assigned_template_id) { + global $app; + if(!$this->checkPerm($session_id, 'client_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - - if(@is_numeric($client_id) && @is_numeric($template_id)) { - // check if client exists - $check = $app->db->queryOneRecord('SELECT `client_id` FROM `client` WHERE `client_id` = ' . $client_id); - if(!$check) { - $this->server->fault('Invalid client'); - return false; - } - // check if template exists - $check = $app->db->queryOneRecord('SELECT `assigned_template_id` FROM `client_template_assigned` WHERE `assigned_template_id` = ' . $assigned_template_id); - if(!$check) { - $this->server->fault('Invalid template'); - return false; - } - - // for the update event we have to cheat a bit - $this->_set_client_formdata($client_id); - - $sql = "DELETE FROM `client_template_assigned` WHERE `assigned_template_id` = " . $template_id . " AND `client_id` = " . $client_id; - $app->db->query($sql); - $affected_rows = $app->db->affectedRows(); - - $app->plugin->raiseEvent('client:client:on_after_update',$this); - - return $affected_rows; - } else { - $this->server->fault('The IDs must be of type integer.'); - return false; - } - } - - public function client_delete($session_id,$client_id) - { - global $app; - - if (!$this->checkPerm($session_id, 'client_delete')) - { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); - return false; + + if(@is_numeric($client_id) && @is_numeric($template_id)) { + // check if client exists + $check = $app->db->queryOneRecord('SELECT `client_id` FROM `client` WHERE `client_id` = ' . $client_id); + if(!$check) { + $this->server->fault('Invalid client'); + return false; + } + // check if template exists + $check = $app->db->queryOneRecord('SELECT `assigned_template_id` FROM `client_template_assigned` WHERE `assigned_template_id` = ' . $assigned_template_id); + if(!$check) { + $this->server->fault('Invalid template'); + return false; } - $affected_rows = $this->deleteQuery('../client/form/client.tform.php',$client_id); - - $app->remoting_lib->ispconfig_sysuser_delete($client_id); - + + // for the update event we have to cheat a bit + $this->_set_client_formdata($client_id); + + $sql = "DELETE FROM `client_template_assigned` WHERE `assigned_template_id` = " . $template_id . " AND `client_id` = " . $client_id; + $app->db->query($sql); + $affected_rows = $app->db->affectedRows(); + + $app->plugin->raiseEvent('client:client:on_after_update', $this); + return $affected_rows; + } else { + $this->server->fault('The IDs must be of type integer.'); + return false; + } + } + + public function client_delete($session_id, $client_id) + { + global $app; + + if (!$this->checkPerm($session_id, 'client_delete')) + { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $affected_rows = $this->deleteQuery('../client/form/client.tform.php', $client_id); + + $app->remoting_lib->ispconfig_sysuser_delete($client_id); + + return $affected_rows; } - + // ----------------------------------------------------------------------------------------------- - + public function client_delete_everything($session_id, $client_id) - { - global $app, $conf; - + { + global $app, $conf; + if(!$this->checkPerm($session_id, 'client_delete_everything')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; } - + $client_id = $app->functions->intval($client_id); - if($client_id > 0) { + if($client_id > 0) { //* remove the group of the client from the resellers group $parent_client_id = $app->functions->intval($this->dataRecord['parent_client_id']); $parent_user = $app->db->queryOneRecord("SELECT userid FROM sys_user WHERE client_id = $parent_client_id"); $client_group = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = $client_id"); - $app->auth->remove_group_from_user($parent_user['userid'],$client_group['groupid']); - + $app->auth->remove_group_from_user($parent_user['userid'], $client_group['groupid']); + //* delete the group of the client $app->db->query("DELETE FROM sys_group WHERE client_id = $client_id"); - + //* delete the sys user(s) of the client $app->db->query("DELETE FROM sys_user WHERE client_id = $client_id"); - + //* Delete all records (sub-clients, mail, web, etc....) of this client. $tables = 'client,dns_rr,dns_soa,dns_slave,ftp_user,mail_access,mail_content_filter,mail_domain,mail_forwarding,mail_get,mail_user,mail_user_filter,shell_user,spamfilter_users,support_message,web_database,web_database_user,web_domain,web_traffic'; - $tables_array = explode(',',$tables); + $tables_array = explode(',', $tables); $client_group_id = $app->functions->intval($client_group['groupid']); - + if($client_group_id > 1) { foreach($tables_array as $table) { if($table != '') { @@ -1425,29 +1427,29 @@ class remoting { } } } - + } } } - + } - + if (!$this->checkPerm($session_id, 'client_delete')) { - $this->server->fault('permission_denied','You do not have the permissions to access this function.'); + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../client/form/client.tform.php',$client_id); + $affected_rows = $this->deleteQuery('../client/form/client.tform.php', $client_id); - return $affected_rows; + return $affected_rows; } - + // Website functions --------------------------------------------------------------------------------------- - + //* Get cron details public function sites_cron_get($session_id, $cron_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'sites_cron_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -1456,46 +1458,46 @@ class remoting { $app->remoting_lib->loadFormDef('../sites/form/cron.tform.php'); return $app->remoting_lib->getDataRecord($cron_id); } - + //* Add a cron record public function sites_cron_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_cron_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../sites/form/cron.tform.php',$client_id,$params); + return $this->insertQuery('../sites/form/cron.tform.php', $client_id, $params); } - + //* Update cron record public function sites_cron_update($session_id, $client_id, $cron_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_cron_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../sites/form/cron.tform.php',$client_id,$cron_id,$params); + $affected_rows = $this->updateQuery('../sites/form/cron.tform.php', $client_id, $cron_id, $params); return $affected_rows; } - + //* Delete cron record public function sites_cron_delete($session_id, $cron_id) - { + { if(!$this->checkPerm($session_id, 'sites_cron_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../sites/form/cron.tform.php',$cron_id); + $affected_rows = $this->deleteQuery('../sites/form/cron.tform.php', $cron_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------- - + //* Get record details public function sites_database_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'sites_database_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -1504,17 +1506,17 @@ class remoting { $app->remoting_lib->loadFormDef('../sites/form/database.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function sites_database_add($session_id, $client_id, $params) - { - global $app; - + { + global $app; + if(!$this->checkPerm($session_id, 'sites_database_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + //* Check for duplicates $tmp = $app->db->queryOneRecord("SELECT count(database_id) as dbnum FROM web_database WHERE database_name = '".$app->db->quote($params['database_name'])."' AND server_id = '".intval($params["server_id"])."'"); if($tmp['dbnum'] > 0) { @@ -1522,66 +1524,66 @@ class remoting { return false; } - $sql = $this->insertQueryPrepare('../sites/form/database.tform.php', $client_id, $params); - if($sql !== false) { - $app->uses('sites_database_plugin'); - - $this->id = 0; - $this->dataRecord = $params; - $app->sites_database_plugin->processDatabaseInsert($this); + $sql = $this->insertQueryPrepare('../sites/form/database.tform.php', $client_id, $params); + if($sql !== false) { + $app->uses('sites_database_plugin'); + + $this->id = 0; + $this->dataRecord = $params; + $app->sites_database_plugin->processDatabaseInsert($this); + + return $this->insertQueryExecute($sql, $params); + } - return $this->insertQueryExecute($sql, $params); - } - - return false; + return false; } - + //* Update a record public function sites_database_update($session_id, $client_id, $primary_id, $params) - { - global $app; - + { + global $app; + if(!$this->checkPerm($session_id, 'sites_database_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + $sql = $this->updateQueryPrepare('../sites/form/database.tform.php', $client_id, $primary_id, $params); - if($sql !== false) { - $app->uses('sites_database_plugin'); - - $this->id = $primary_id; - $this->dataRecord = $params; - $app->sites_database_plugin->processDatabaseUpdate($this); - return $this->updateQueryExecute($sql, $primary_id, $params); - } - - return false; - } - + if($sql !== false) { + $app->uses('sites_database_plugin'); + + $this->id = $primary_id; + $this->dataRecord = $params; + $app->sites_database_plugin->processDatabaseUpdate($this); + return $this->updateQueryExecute($sql, $primary_id, $params); + } + + return false; + } + //* Delete a record public function sites_database_delete($session_id, $primary_id) - { - global $app; + { + global $app; if(!$this->checkPerm($session_id, 'sites_database_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - - $app->uses('sites_database_plugin'); - $app->sites_database_plugin->processDatabaseDelete($primary_id); - - $affected_rows = $this->deleteQuery('../sites/form/database.tform.php',$primary_id); + + $app->uses('sites_database_plugin'); + $app->sites_database_plugin->processDatabaseDelete($primary_id); + + $affected_rows = $this->deleteQuery('../sites/form/database.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------- - + //* Get record details public function sites_database_user_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'sites_database_user_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -1590,81 +1592,81 @@ class remoting { $app->remoting_lib->loadFormDef('../sites/form/database_user.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function sites_database_user_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_database_user_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../sites/form/database_user.tform.php', $client_id, $params); + return $this->insertQuery('../sites/form/database_user.tform.php', $client_id, $params); } - + //* Update a record public function sites_database_user_update($session_id, $client_id, $primary_id, $params) - { - global $app; - + { + global $app; + if(!$this->checkPerm($session_id, 'sites_database_user_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } $app->uses('remoting_lib'); $app->remoting_lib->loadFormDef('../sites/form/database_user.tform.php'); - $old_rec = $app->remoting_lib->getDataRecord($primary_id); - + $old_rec = $app->remoting_lib->getDataRecord($primary_id); + $result = $this->updateQuery('../sites/form/database_user.tform.php', $client_id, $primary_id, $params); - - $new_rec = $app->remoting_lib->getDataRecord($primary_id); - - $records = $app->db->queryAllRecords("SELECT DISTINCT server_id FROM web_database WHERE database_user_id = '".$app->functions->intval($primary_id)."' UNION SELECT DISTINCT server_id FROM web_database WHERE database_ro_user_id = '".$app->functions->intval($primary_id)."'"); - foreach($records as $rec) { - $tmp_rec = $new_rec; - $tmp_rec['server_id'] = $rec['server_id']; - $app->remoting_lib->datalogSave('UPDATE', $primary_id, $old_rec, $tmp_rec); - } - unset($new_rec); - unset($old_rec); - unset($records); - - return $result; - } - + + $new_rec = $app->remoting_lib->getDataRecord($primary_id); + + $records = $app->db->queryAllRecords("SELECT DISTINCT server_id FROM web_database WHERE database_user_id = '".$app->functions->intval($primary_id)."' UNION SELECT DISTINCT server_id FROM web_database WHERE database_ro_user_id = '".$app->functions->intval($primary_id)."'"); + foreach($records as $rec) { + $tmp_rec = $new_rec; + $tmp_rec['server_id'] = $rec['server_id']; + $app->remoting_lib->datalogSave('UPDATE', $primary_id, $old_rec, $tmp_rec); + } + unset($new_rec); + unset($old_rec); + unset($records); + + return $result; + } + //* Delete a record public function sites_database_user_delete($session_id, $primary_id) - { - global $app; - + { + global $app; + if(!$this->checkPerm($session_id, 'sites_database_user_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - - $app->db->datalogDelete('web_database_user', 'database_user_id', $primary_id); - $affected_rows = $this->deleteQuery('../sites/form/database_user.tform.php',$primary_id); - - $records = $app->db->queryAllRecords("SELECT database_id FROM web_database WHERE database_user_id = '".$app->functions->intval($primary_id)."'"); - foreach($records as $rec) { - $app->db->datalogUpdate('web_database','database_user_id=NULL','database_id', $rec['database_id']); - - } - $records = $app->db->queryAllRecords("SELECT database_id FROM web_database WHERE database_ro_user_id = '".$app->functions->intval($primary_id)."'"); - foreach($records as $rec) { - $app->db->datalogUpdate('web_database','database_ro_user_id=NULL','database_id', $rec['database_id']); - } - + + $app->db->datalogDelete('web_database_user', 'database_user_id', $primary_id); + $affected_rows = $this->deleteQuery('../sites/form/database_user.tform.php', $primary_id); + + $records = $app->db->queryAllRecords("SELECT database_id FROM web_database WHERE database_user_id = '".$app->functions->intval($primary_id)."'"); + foreach($records as $rec) { + $app->db->datalogUpdate('web_database', 'database_user_id=NULL', 'database_id', $rec['database_id']); + + } + $records = $app->db->queryAllRecords("SELECT database_id FROM web_database WHERE database_ro_user_id = '".$app->functions->intval($primary_id)."'"); + foreach($records as $rec) { + $app->db->datalogUpdate('web_database', 'database_ro_user_id=NULL', 'database_id', $rec['database_id']); + } + return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------- - + //* Get record details public function sites_ftp_user_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'sites_ftp_user_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -1673,66 +1675,66 @@ class remoting { $app->remoting_lib->loadFormDef('../sites/form/ftp_user.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function sites_ftp_user_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_ftp_user_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../sites/form/ftp_user.tform.php',$client_id,$params); + return $this->insertQuery('../sites/form/ftp_user.tform.php', $client_id, $params); } - + //* Update a record public function sites_ftp_user_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_ftp_user_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../sites/form/ftp_user.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../sites/form/ftp_user.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function sites_ftp_user_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'sites_ftp_user_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../sites/form/ftp_user.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../sites/form/ftp_user.tform.php', $primary_id); return $affected_rows; } - + //* Get server for an ftp user public function sites_ftp_user_server_get($session_id, $ftp_user) - { + { global $app; - + if(!$this->checkPerm($session_id, 'sites_ftp_user_server_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + $data = $app->db->queryOneRecord("SELECT server_id FROM ftp_user WHERE username = '".$app->db->quote($ftp_user)."'"); //file_put_contents('/tmp/test.txt', serialize($data)); - if(!isset($data['server_id'])) return false; - - $server = $this->server_get($session_id, $data['server_id'], 'server'); - //file_put_contents('/tmp/test2.txt', serialize($server)); - + if(!isset($data['server_id'])) return false; + + $server = $this->server_get($session_id, $data['server_id'], 'server'); + //file_put_contents('/tmp/test2.txt', serialize($server)); + return $server; } - + // ---------------------------------------------------------------------------------------------------------- - + //* Get record details public function sites_shell_user_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'sites_shell_user_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -1741,46 +1743,46 @@ class remoting { $app->remoting_lib->loadFormDef('../sites/form/shell_user.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function sites_shell_user_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_shell_user_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../sites/form/shell_user.tform.php',$client_id,$params); + return $this->insertQuery('../sites/form/shell_user.tform.php', $client_id, $params); } - + //* Update a record public function sites_shell_user_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_shell_user_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../sites/form/shell_user.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../sites/form/shell_user.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function sites_shell_user_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'sites_shell_user_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../sites/form/shell_user.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../sites/form/shell_user.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------- - + //* Get record details public function sites_web_domain_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'sites_web_domain_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -1789,7 +1791,7 @@ class remoting { $app->remoting_lib->loadFormDef('../sites/form/web_domain.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function sites_web_domain_add($session_id, $client_id, $params, $readonly = false) { @@ -1798,65 +1800,65 @@ class remoting { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + if(!isset($params['client_group_id']) or (isset($params['client_group_id']) && empty($params['client_group_id']))) { $rec = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = ".$app->functions->intval($client_id)); $params['client_group_id'] = $rec['groupid']; } - + //* Set a few params to "not empty" values which get overwritten by the sites_web_domain_plugin if($params['document_root'] == '') $params['document_root'] = '-'; if($params['system_user'] == '') $params['system_user'] = '-'; if($params['system_group'] == '') $params['system_group'] = '-'; - + //* Set a few defaults for nginx servers if($params['pm_max_children'] == '') $params['pm_max_children'] = 1; if($params['pm_start_servers'] == '') $params['pm_start_servers'] = 1; if($params['pm_min_spare_servers'] == '') $params['pm_min_spare_servers'] = 1; if($params['pm_max_spare_servers'] == '') $params['pm_max_spare_servers'] = 1; - - $domain_id = $this->insertQuery('../sites/form/web_domain.tform.php',$client_id,$params, 'sites:web_domain:on_after_insert'); + + $domain_id = $this->insertQuery('../sites/form/web_domain.tform.php', $client_id, $params, 'sites:web_domain:on_after_insert'); if ($readonly === true) $app->db->query("UPDATE web_domain SET `sys_userid` = '1' WHERE domain_id = ".$domain_id); - return $domain_id; - } - + return $domain_id; + } + //* Update a record public function sites_web_domain_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_web_domain_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + //* Set a few defaults for nginx servers if($params['pm_max_children'] == '') $params['pm_max_children'] = 1; if($params['pm_start_servers'] == '') $params['pm_start_servers'] = 1; if($params['pm_min_spare_servers'] == '') $params['pm_min_spare_servers'] = 1; if($params['pm_max_spare_servers'] == '') $params['pm_max_spare_servers'] = 1; - - $affected_rows = $this->updateQuery('../sites/form/web_domain.tform.php',$client_id,$primary_id,$params); + + $affected_rows = $this->updateQuery('../sites/form/web_domain.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function sites_web_domain_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'sites_web_domain_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../sites/form/web_domain.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../sites/form/web_domain.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------- - + //* Get record details public function sites_web_vhost_subdomain_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'sites_web_subdomain_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -1865,7 +1867,7 @@ class remoting { $app->remoting_lib->loadFormDef('../sites/form/web_vhost_subdomain.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function sites_web_vhost_subdomain_add($session_id, $client_id, $params) { @@ -1874,58 +1876,58 @@ class remoting { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + //* Set a few params to "not empty" values which get overwritten by the sites_web_domain_plugin if($params['document_root'] == '') $params['document_root'] = '-'; if($params['system_user'] == '') $params['system_user'] = '-'; if($params['system_group'] == '') $params['system_group'] = '-'; - + //* Set a few defaults for nginx servers if($params['pm_max_children'] == '') $params['pm_max_children'] = 1; if($params['pm_start_servers'] == '') $params['pm_start_servers'] = 1; if($params['pm_min_spare_servers'] == '') $params['pm_min_spare_servers'] = 1; if($params['pm_max_spare_servers'] == '') $params['pm_max_spare_servers'] = 1; - - $domain_id = $this->insertQuery('../sites/form/web_vhost_subdomain.tform.php',$client_id,$params, 'sites:web_vhost_subdomain:on_after_insert'); - return $domain_id; - } - + + $domain_id = $this->insertQuery('../sites/form/web_vhost_subdomain.tform.php', $client_id, $params, 'sites:web_vhost_subdomain:on_after_insert'); + return $domain_id; + } + //* Update a record public function sites_web_vhost_subdomain_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_web_subdomain_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + //* Set a few defaults for nginx servers if($params['pm_max_children'] == '') $params['pm_max_children'] = 1; if($params['pm_start_servers'] == '') $params['pm_start_servers'] = 1; if($params['pm_min_spare_servers'] == '') $params['pm_min_spare_servers'] = 1; if($params['pm_max_spare_servers'] == '') $params['pm_max_spare_servers'] = 1; - - $affected_rows = $this->updateQuery('../sites/form/web_vhost_subdomain.tform.php',$client_id,$primary_id,$params, 'sites:web_vhost_subdomain:on_after_insert'); + + $affected_rows = $this->updateQuery('../sites/form/web_vhost_subdomain.tform.php', $client_id, $primary_id, $params, 'sites:web_vhost_subdomain:on_after_insert'); return $affected_rows; } - + //* Delete a record public function sites_web_vhost_subdomain_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'sites_web_subdomain_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../sites/form/web_vhost_subdomain.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../sites/form/web_vhost_subdomain.tform.php', $primary_id); return $affected_rows; } - + // ----------------------------------------------------------------------------------------------- - + //* Get record details public function sites_web_aliasdomain_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'sites_web_aliasdomain_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -1934,46 +1936,46 @@ class remoting { $app->remoting_lib->loadFormDef('../sites/form/web_aliasdomain.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function sites_web_aliasdomain_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_web_aliasdomain_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../sites/form/web_aliasdomain.tform.php',$client_id,$params); + return $this->insertQuery('../sites/form/web_aliasdomain.tform.php', $client_id, $params); } - + //* Update a record public function sites_web_aliasdomain_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_web_aliasdomain_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../sites/form/web_aliasdomain.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../sites/form/web_aliasdomain.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function sites_web_aliasdomain_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'sites_web_aliasdomain_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../sites/form/web_aliasdomain.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../sites/form/web_aliasdomain.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------- - + //* Get record details public function sites_web_subdomain_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'sites_web_subdomain_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -1982,46 +1984,46 @@ class remoting { $app->remoting_lib->loadFormDef('../sites/form/web_subdomain.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function sites_web_subdomain_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_web_subdomain_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../sites/form/web_subdomain.tform.php',$client_id,$params); + return $this->insertQuery('../sites/form/web_subdomain.tform.php', $client_id, $params); } - + //* Update a record public function sites_web_subdomain_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_web_subdomain_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../sites/form/web_subdomain.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../sites/form/web_subdomain.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function sites_web_subdomain_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'sites_web_subdomain_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../sites/form/web_subdomain.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../sites/form/web_subdomain.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------- - + //* Get record details public function sites_web_folder_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'sites_web_folder_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2030,56 +2032,56 @@ class remoting { $app->remoting_lib->loadFormDef('../sites/form/web_folder.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function sites_web_folder_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_web_folder_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../sites/form/web_folder.tform.php',$client_id,$params); + return $this->insertQuery('../sites/form/web_folder.tform.php', $client_id, $params); } - + //* Update a record public function sites_web_folder_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_web_folder_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../sites/form/web_folder.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../sites/form/web_folder.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function sites_web_folder_delete($session_id, $primary_id) - { + { global $app; if(!$this->checkPerm($session_id, 'sites_web_folder_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - - // Delete all users that belong to this folder. - taken from web_folder_delete.php + + // Delete all users that belong to this folder. - taken from web_folder_delete.php $records = $app->db->queryAllRecords("SELECT web_folder_user_id FROM web_folder_user WHERE web_folder_id = '".$app->functions->intval($primary_id)."'"); foreach($records as $rec) { - $this->deleteQuery('../sites/form/web_folder_user.tform.php',$rec['web_folder_user_id']); + $this->deleteQuery('../sites/form/web_folder_user.tform.php', $rec['web_folder_user_id']); //$app->db->datalogDelete('web_folder_user','web_folder_user_id',$rec['web_folder_user_id']); } unset($records); - - $affected_rows = $this->deleteQuery('../sites/form/web_folder.tform.php',$primary_id); + + $affected_rows = $this->deleteQuery('../sites/form/web_folder.tform.php', $primary_id); return $affected_rows; } - + // ----------------------------------------------------------------------------------------------- - + //* Get record details public function sites_web_folder_user_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'sites_web_folder_user_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2088,46 +2090,46 @@ class remoting { $app->remoting_lib->loadFormDef('../sites/form/web_folder_user.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function sites_web_folder_user_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_web_folder_user_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../sites/form/web_folder_user.tform.php',$client_id,$params); + return $this->insertQuery('../sites/form/web_folder_user.tform.php', $client_id, $params); } - + //* Update a record public function sites_web_folder_user_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'sites_web_folder_user_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../sites/form/web_folder_user.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../sites/form/web_folder_user.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function sites_web_folder_user_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'sites_web_folder_user_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../sites/form/web_folder_user.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../sites/form/web_folder_user.tform.php', $primary_id); return $affected_rows; } - + // ----------------------------------------------------------------------------------------------- - + //* Get record details public function domains_domain_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'domains_domain_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2139,77 +2141,77 @@ class remoting { //* Add a record public function domains_domain_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'domains_domain_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../client/form/domain.tform.php',$client_id,$params); + return $this->insertQuery('../client/form/domain.tform.php', $client_id, $params); } //* Delete a record public function domains_domain_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'domains_domain_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../client/form/domain.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../client/form/domain.tform.php', $primary_id); return $affected_rows; } -// ----------------------------------------------------------------------------------------------- + // ----------------------------------------------------------------------------------------------- public function domains_get_all_by_user($session_id, $group_id) - { - global $app; + { + global $app; if(!$this->checkPerm($session_id, 'domains_get_all_by_user')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; } - $group_id = $app->functions->intval($group_id); - $sql = "SELECT domain_id, domain FROM domain WHERE sys_groupid = $group_id "; - $all = $app->db->queryAllRecords($sql); - return $all; + $group_id = $app->functions->intval($group_id); + $sql = "SELECT domain_id, domain FROM domain WHERE sys_groupid = $group_id "; + $all = $app->db->queryAllRecords($sql); + return $all; } - - + + // DNS Function -------------------------------------------------------------------------------------------------- - + //* Create Zone with Template public function dns_templatezone_add($session_id, $client_id, $template_id, $domain, $ip, $ns1, $ns2, $email) - { - global $app, $conf; + { + global $app, $conf; if(!$this->checkPerm($session_id, 'dns_templatezone_add')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; } $client = $app->db->queryOneRecord("SELECT default_dnsserver FROM client WHERE client_id = ".$app->functions->intval($client_id)); $server_id = $client["default_dnsserver"]; $template_record = $app->db->queryOneRecord("SELECT * FROM dns_template WHERE template_id = '$template_id'"); - $fields = explode(',',$template_record['fields']); + $fields = explode(',', $template_record['fields']); $tform_def_file = "../../web/dns/form/dns_soa.tform.php"; $app->uses('tform'); $app->tform->loadFormDef($tform_def_file); $app->uses('tpl,validate_dns'); - + //* replace template placeholders $tpl_content = $template_record['template']; - if($domain != '') $tpl_content = str_replace('{DOMAIN}',$domain,$tpl_content); - if($ip != '') $tpl_content = str_replace('{IP}',$ip,$tpl_content); - if($ns1 != '') $tpl_content = str_replace('{NS1}',$ns1,$tpl_content); - if($ns2 != '') $tpl_content = str_replace('{NS2}',$ns2,$tpl_content); - if($email != '') $tpl_content = str_replace('{EMAIL}',$email,$tpl_content); - + if($domain != '') $tpl_content = str_replace('{DOMAIN}', $domain, $tpl_content); + if($ip != '') $tpl_content = str_replace('{IP}', $ip, $tpl_content); + if($ns1 != '') $tpl_content = str_replace('{NS1}', $ns1, $tpl_content); + if($ns2 != '') $tpl_content = str_replace('{NS2}', $ns2, $tpl_content); + if($email != '') $tpl_content = str_replace('{EMAIL}', $email, $tpl_content); + //* Parse the template - $tpl_rows = explode("\n",$tpl_content); + $tpl_rows = explode("\n", $tpl_content); $section = ''; $vars = array(); $dns_rr = array(); foreach($tpl_rows as $row) { $row = trim($row); - if(substr($row,0,1) == '[') { + if(substr($row, 0, 1) == '[') { if($row == '[ZONE]') { $section = 'zone'; } elseif($row == '[DNS_RECORDS]') { @@ -2221,14 +2223,14 @@ class remoting { if($row != '') { //* Handle zone section if($section == 'zone') { - $parts = explode('=',$row); + $parts = explode('=', $row); $key = trim($parts[0]); $val = trim($parts[1]); if($key != '') $vars[$key] = $val; } //* Handle DNS Record rows if($section == 'dns_records') { - $parts = explode('|',$row); + $parts = explode('|', $row); $dns_rr[] = array( 'name' => $app->db->quote($parts[1]), 'type' => $app->db->quote($parts[0]), @@ -2238,9 +2240,9 @@ class remoting { ); } } - } + } } // end foreach - + if($vars['origin'] == '') $error .= $app->lng('error_origin_empty').'
'; if($vars['ns'] == '') $error .= $app->lng('error_ns_empty').'
'; if($vars['mbox'] == '') $error .= $app->lng('error_mbox_empty').'
'; @@ -2248,8 +2250,8 @@ class remoting { if($vars['retry'] == '') $error .= $app->lng('error_retry_empty').'
'; if($vars['expire'] == '') $error .= $app->lng('error_expire_empty').'
'; if($vars['minimum'] == '') $error .= $app->lng('error_minimum_empty').'
'; - if($vars['ttl'] == '') $error .= $app->lng('error_ttl_empty').'
'; - + if($vars['ttl'] == '') $error .= $app->lng('error_ttl_empty').'
'; + if($error == '') { // Insert the soa record $tmp = $app->db->queryOneRecord("SELECT userid,default_group FROM sys_user WHERE client_id = ".$app->functions->intval($client_id)); @@ -2258,7 +2260,7 @@ class remoting { unset($tmp); $origin = $app->db->quote($vars['origin']); $ns = $app->db->quote($vars['ns']); - $mbox = $app->db->quote(str_replace('@','.',$vars['mbox'])); + $mbox = $app->db->quote(str_replace('@', '.', $vars['mbox'])); $refresh = $app->db->quote($vars['refresh']); $retry = $app->db->quote($vars['retry']); $expire = $app->db->quote($vars['expire']); @@ -2267,14 +2269,14 @@ class remoting { $xfer = $app->db->quote($vars['xfer']); $also_notify = $app->db->quote($vars['also_notify']); $update_acl = $app->db->quote($vars['update_acl']); - $serial = $app->validate_dns->increase_serial(0); - $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `origin`, `ns`, `mbox`, `serial`, `refresh`, `retry`, `expire`, `minimum`, `ttl`, `active`, `xfer`, `also_notify`, `update_acl`) VALUES + $serial = $app->validate_dns->increase_serial(0); + $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `origin`, `ns`, `mbox`, `serial`, `refresh`, `retry`, `expire`, `minimum`, `ttl`, `active`, `xfer`, `also_notify`, `update_acl`) VALUES ('$sys_userid', '$sys_groupid', 'riud', 'riud', '', '$server_id', '$origin', '$ns', '$mbox', '$serial', '$refresh', '$retry', '$expire', '$minimum', '$ttl', 'Y', '$xfer', '$also_notify', '$update_acl')"; - $dns_soa_id = $app->db->datalogInsert('dns_soa', $insert_data, 'id'); + $dns_soa_id = $app->db->datalogInsert('dns_soa', $insert_data, 'id'); // Insert the dns_rr records if(is_array($dns_rr) && $dns_soa_id > 0) { foreach($dns_rr as $rr) { - $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `zone`, `name`, `type`, `data`, `aux`, `ttl`, `active`) VALUES + $insert_data = "(`sys_userid`, `sys_groupid`, `sys_perm_user`, `sys_perm_group`, `sys_perm_other`, `server_id`, `zone`, `name`, `type`, `data`, `aux`, `ttl`, `active`) VALUES ('$sys_userid', '$sys_groupid', 'riud', 'riud', '', '$server_id', '$dns_soa_id', '$rr[name]', '$rr[type]', '$rr[data]', '$rr[aux]', '$rr[ttl]', 'Y')"; $dns_rr_id = $app->db->datalogInsert('dns_rr', $insert_data, 'id'); } @@ -2284,13 +2286,13 @@ class remoting { $this->server->fault('permission_denied', $error); } } - - + + //* Get record details public function dns_zone_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'dns_zone_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2299,70 +2301,70 @@ class remoting { $app->remoting_lib->loadFormDef('../dns/form/dns_soa.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - - //* Get record id by origin - public function dns_zone_get_id($session_id, $origin) - { - global $app; - - if(!$this->checkPerm($session_id, 'dns_zone_get_id')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; - } - - if(!preg_match('/^[a-z0-9][a-z0-9\-]+[a-z0-9](\.[a-z]{2,4})+$/i', $origin)){ - $this->server->fault('no_domain_found', 'Invalid domain name.'); - return false; - } - - $rec = $app->db->queryOneRecord("SELECT id FROM dns_soa WHERE origin like '".$origin."%'"); - if(isset($rec['id'])) { - return $app->functions->intval($rec['id']); - } else { - $this->server->fault('no_domain_found', 'There is no domain ID with informed domain name.'); - return false; - } - } - + + //* Get record id by origin + public function dns_zone_get_id($session_id, $origin) + { + global $app; + + if(!$this->checkPerm($session_id, 'dns_zone_get_id')) { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + + if(!preg_match('/^[a-z0-9][a-z0-9\-]+[a-z0-9](\.[a-z]{2,4})+$/i', $origin)){ + $this->server->fault('no_domain_found', 'Invalid domain name.'); + return false; + } + + $rec = $app->db->queryOneRecord("SELECT id FROM dns_soa WHERE origin like '".$origin."%'"); + if(isset($rec['id'])) { + return $app->functions->intval($rec['id']); + } else { + $this->server->fault('no_domain_found', 'There is no domain ID with informed domain name.'); + return false; + } + } + //* Add a record public function dns_zone_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_zone_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../dns/form/dns_soa.tform.php',$client_id,$params); + return $this->insertQuery('../dns/form/dns_soa.tform.php', $client_id, $params); } - + //* Update a record public function dns_zone_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_zone_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../dns/form/dns_soa.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../dns/form/dns_soa.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function dns_zone_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'dns_zone_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../dns/form/dns_soa.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../dns/form/dns_soa.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------------- - + //* Get record details public function dns_aaaa_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'dns_aaaa_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2371,46 +2373,46 @@ class remoting { $app->remoting_lib->loadFormDef('../dns/form/dns_aaaa.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function dns_aaaa_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_aaaa_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../dns/form/dns_aaaa.tform.php',$client_id,$params); + return $this->insertQuery('../dns/form/dns_aaaa.tform.php', $client_id, $params); } - + //* Update a record public function dns_aaaa_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_aaaa_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../dns/form/dns_aaaa.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../dns/form/dns_aaaa.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function dns_aaaa_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'dns_aaaa_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../dns/form/dns_aaaa.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../dns/form/dns_aaaa.tform.php', $primary_id); return $affected_rows; } // ---------------------------------------------------------------------------------------------------------------- - + //* Get record details public function dns_a_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'dns_a_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2419,46 +2421,46 @@ class remoting { $app->remoting_lib->loadFormDef('../dns/form/dns_a.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function dns_a_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_a_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../dns/form/dns_a.tform.php',$client_id,$params); + return $this->insertQuery('../dns/form/dns_a.tform.php', $client_id, $params); } - + //* Update a record public function dns_a_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_a_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../dns/form/dns_a.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../dns/form/dns_a.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function dns_a_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'dns_a_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../dns/form/dns_a.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../dns/form/dns_a.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------------- - + //* Get record details public function dns_alias_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'dns_alias_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2467,46 +2469,46 @@ class remoting { $app->remoting_lib->loadFormDef('../dns/form/dns_alias.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function dns_alias_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_alias_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../dns/form/dns_alias.tform.php',$client_id,$params); + return $this->insertQuery('../dns/form/dns_alias.tform.php', $client_id, $params); } - + //* Update a record public function dns_alias_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_alias_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../dns/form/dns_alias.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../dns/form/dns_alias.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function dns_alias_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'dns_alias_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../dns/form/dns_alias.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../dns/form/dns_alias.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------------- - + //* Get record details public function dns_cname_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'dns_cname_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2515,46 +2517,46 @@ class remoting { $app->remoting_lib->loadFormDef('../dns/form/dns_cname.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function dns_cname_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_cname_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../dns/form/dns_cname.tform.php',$client_id,$params); + return $this->insertQuery('../dns/form/dns_cname.tform.php', $client_id, $params); } - + //* Update a record public function dns_cname_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_cname_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../dns/form/dns_cname.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../dns/form/dns_cname.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function dns_cname_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'dns_cname_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../dns/form/dns_cname.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../dns/form/dns_cname.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------------- - + //* Get record details public function dns_hinfo_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'dns_hinfo_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2563,46 +2565,46 @@ class remoting { $app->remoting_lib->loadFormDef('../dns/form/dns_hinfo.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function dns_hinfo_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_hinfo_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../dns/form/dns_hinfo.tform.php',$client_id,$params); + return $this->insertQuery('../dns/form/dns_hinfo.tform.php', $client_id, $params); } - + //* Update a record public function dns_hinfo_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_hinfo_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../dns/form/dns_hinfo.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../dns/form/dns_hinfo.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function dns_hinfo_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'dns_hinfo_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../dns/form/dns_hinfo.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../dns/form/dns_hinfo.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------------- - + //* Get record details public function dns_mx_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'dns_mx_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2611,46 +2613,46 @@ class remoting { $app->remoting_lib->loadFormDef('../dns/form/dns_mx.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function dns_mx_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_mx_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../dns/form/dns_mx.tform.php',$client_id,$params); + return $this->insertQuery('../dns/form/dns_mx.tform.php', $client_id, $params); } - + //* Update a record public function dns_mx_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_mx_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../dns/form/dns_mx.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../dns/form/dns_mx.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function dns_mx_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'dns_mx_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../dns/form/dns_mx.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../dns/form/dns_mx.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------------- - + //* Get record details public function dns_ns_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'dns_ns_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2659,46 +2661,46 @@ class remoting { $app->remoting_lib->loadFormDef('../dns/form/dns_ns.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function dns_ns_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_ns_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../dns/form/dns_ns.tform.php',$client_id,$params); + return $this->insertQuery('../dns/form/dns_ns.tform.php', $client_id, $params); } - + //* Update a record public function dns_ns_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_ns_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../dns/form/dns_ns.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../dns/form/dns_ns.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function dns_ns_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'dns_ns_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../dns/form/dns_ns.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../dns/form/dns_ns.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------------- - + //* Get record details public function dns_ptr_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'dns_ptr_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2707,46 +2709,46 @@ class remoting { $app->remoting_lib->loadFormDef('../dns/form/dns_ptr.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function dns_ptr_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_ptr_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../dns/form/dns_ptr.tform.php',$client_id,$params); + return $this->insertQuery('../dns/form/dns_ptr.tform.php', $client_id, $params); } - + //* Update a record public function dns_ptr_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_ptr_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../dns/form/dns_ptr.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../dns/form/dns_ptr.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function dns_ptr_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'dns_ptr_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../dns/form/dns_ptr.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../dns/form/dns_ptr.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------------- - + //* Get record details public function dns_rp_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'dns_rp_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2755,46 +2757,46 @@ class remoting { $app->remoting_lib->loadFormDef('../dns/form/dns_rp.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function dns_rp_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_rp_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../dns/form/dns_rp.tform.php',$client_id,$params); + return $this->insertQuery('../dns/form/dns_rp.tform.php', $client_id, $params); } - + //* Update a record public function dns_rp_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_rp_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../dns/form/dns_rp.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../dns/form/dns_rp.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function dns_rp_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'dns_rp_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../dns/form/dns_rp.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../dns/form/dns_rp.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------------- - + //* Get record details public function dns_srv_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'dns_srv_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2803,46 +2805,46 @@ class remoting { $app->remoting_lib->loadFormDef('../dns/form/dns_srv.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function dns_srv_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_srv_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../dns/form/dns_srv.tform.php',$client_id,$params); + return $this->insertQuery('../dns/form/dns_srv.tform.php', $client_id, $params); } - + //* Update a record public function dns_srv_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_srv_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../dns/form/dns_srv.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../dns/form/dns_srv.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function dns_srv_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'dns_srv_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../dns/form/dns_srv.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../dns/form/dns_srv.tform.php', $primary_id); return $affected_rows; } - + // ---------------------------------------------------------------------------------------------------------------- - + //* Get record details public function dns_txt_get($session_id, $primary_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'dns_txt_get')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -2851,646 +2853,657 @@ class remoting { $app->remoting_lib->loadFormDef('../dns/form/dns_txt.tform.php'); return $app->remoting_lib->getDataRecord($primary_id); } - + //* Add a record public function dns_txt_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_txt_add')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../dns/form/dns_txt.tform.php',$client_id,$params); + return $this->insertQuery('../dns/form/dns_txt.tform.php', $client_id, $params); } - + //* Update a record public function dns_txt_update($session_id, $client_id, $primary_id, $params) - { + { if(!$this->checkPerm($session_id, 'dns_txt_update')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../dns/form/dns_txt.tform.php',$client_id,$primary_id,$params); + $affected_rows = $this->updateQuery('../dns/form/dns_txt.tform.php', $client_id, $primary_id, $params); return $affected_rows; } - + //* Delete a record public function dns_txt_delete($session_id, $primary_id) - { + { if(!$this->checkPerm($session_id, 'dns_txt_delete')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../dns/form/dns_txt.tform.php',$primary_id); + $affected_rows = $this->deleteQuery('../dns/form/dns_txt.tform.php', $primary_id); return $affected_rows; } - - - - - - - - - - - + + + + + + + + + + + //** protected functions ----------------------------------------------------------------------------------- - - + + protected function klientadd($formdef_file, $reseller_id, $params) - { + { global $app; $app->uses('remoting_lib'); - + //* Load the form definition $app->remoting_lib->loadFormDef($formdef_file); - + //* load the user profile of the client $app->remoting_lib->loadUserProfile($reseller_id); - + //* Get the SQL query - $sql = $app->remoting_lib->getSQL($params,'INSERT',0); - + $sql = $app->remoting_lib->getSQL($params, 'INSERT', 0); + //* Check if no system user with that username exists $username = $app->db->quote($params["username"]); $tmp = $app->db->queryOneRecord("SELECT count(userid) as number FROM sys_user WHERE username = '$username'"); if($tmp['number'] > 0) $app->remoting_lib->errorMessage .= "Duplicate username
"; - + //* Stop on error while preparing the sql query if($app->remoting_lib->errorMessage != '') { $this->server->fault('data_processing_error', $app->remoting_lib->errorMessage); return false; } - + //* Execute the SQL query $app->db->query($sql); $insert_id = $app->db->insertID(); - - + + //* Stop on error while executing the sql query if($app->remoting_lib->errorMessage != '') { $this->server->fault('data_processing_error', $app->remoting_lib->errorMessage); return false; } - + $this->id = $insert_id; $this->dataRecord = $params; - - $app->plugin->raiseEvent('client:' . (isset($params['limit_client']) && $params['limit_client'] > 0 ? 'reseller' : 'client') . ':on_after_insert',$this); - + + $app->plugin->raiseEvent('client:' . (isset($params['limit_client']) && $params['limit_client'] > 0 ? 'reseller' : 'client') . ':on_after_insert', $this); + /* if($app->db->errorMessage != '') { $this->server->fault('database_error', $app->db->errorMessage . ' '.$sql); return false; } */ - - /* copied from the client_edit php */ + + /* copied from the client_edit php */ exec('ssh-keygen -t rsa -C '.$username.'-rsa-key-'.time().' -f /tmp/id_rsa -N ""'); $app->db->query("UPDATE client SET created_at = ".time().", id_rsa = '".$app->db->quote(@file_get_contents('/tmp/id_rsa'))."', ssh_rsa = '".$app->db->quote(@file_get_contents('/tmp/id_rsa.pub'))."' WHERE client_id = ".$this->id); exec('rm -f /tmp/id_rsa /tmp/id_rsa.pub'); - - - + + + //$app->uses('tform'); //* Save changes to Datalog if($app->remoting_lib->formDef["db_history"] == 'yes') { $new_rec = $app->remoting_lib->getDataRecord($insert_id); - $app->remoting_lib->datalogSave('INSERT',$primary_id,array(),$new_rec); - $app->remoting_lib->ispconfig_sysuser_add($params,$insert_id); - - if($reseller_id) { - $client_group = $app->db->queryOneRecord("SELECT * FROM sys_group WHERE client_id = ".$insert_id); - $reseller_user = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE client_id = ".$reseller_id); - $app->auth->add_group_to_user($reseller_user['userid'], $client_group['groupid']); - $app->db->query("UPDATE client SET parent_client_id = ".$reseller_id." WHERE client_id = ".$insert_id); - } + $app->remoting_lib->datalogSave('INSERT', $primary_id, array(), $new_rec); + $app->remoting_lib->ispconfig_sysuser_add($params, $insert_id); + + if($reseller_id) { + $client_group = $app->db->queryOneRecord("SELECT * FROM sys_group WHERE client_id = ".$insert_id); + $reseller_user = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE client_id = ".$reseller_id); + $app->auth->add_group_to_user($reseller_user['userid'], $client_group['groupid']); + $app->db->query("UPDATE client SET parent_client_id = ".$reseller_id." WHERE client_id = ".$insert_id); + } } return $insert_id; } - protected function insertQuery($formdef_file, $client_id, $params,$event_identifier = '') - { - $sql = $this->insertQueryPrepare($formdef_file, $client_id, $params); - if($sql !== false) return $this->insertQueryExecute($sql, $params,$event_identifier); - else return false; - } + protected function insertQuery($formdef_file, $client_id, $params, $event_identifier = '') + { + $sql = $this->insertQueryPrepare($formdef_file, $client_id, $params); + if($sql !== false) return $this->insertQueryExecute($sql, $params, $event_identifier); + else return false; + } protected function insertQueryPrepare($formdef_file, $client_id, $params) - { + { global $app; - + $app->uses('remoting_lib'); - + //* load the user profile of the client $app->remoting_lib->loadUserProfile($client_id); - + //* Load the form definition $app->remoting_lib->loadFormDef($formdef_file); - + //* Get the SQL query - $sql = $app->remoting_lib->getSQL($params,'INSERT',0); + $sql = $app->remoting_lib->getSQL($params, 'INSERT', 0); if($app->remoting_lib->errorMessage != '') { $this->server->fault('data_processing_error', $app->remoting_lib->errorMessage); return false; } $app->log('Executed insertQueryPrepare', LOGLEVEL_DEBUG); - return $sql; + return $sql; } - - protected function insertQueryExecute($sql, $params,$event_identifier = '') - { + + protected function insertQueryExecute($sql, $params, $event_identifier = '') + { global $app; - + $app->uses('remoting_lib'); - + $app->db->query($sql); - + if($app->db->errorMessage != '') { $this->server->fault('database_error', $app->db->errorMessage . ' '.$sql); return false; } - + $insert_id = $app->db->insertID(); - + // set a few values for compatibility with tform actions, mostly used by plugins $this->id = $insert_id; $this->dataRecord = $params; $app->log('Executed insertQueryExecute, raising events now if any: ' . $event_identifier, LOGLEVEL_DEBUG); - if($event_identifier != '') $app->plugin->raiseEvent($event_identifier,$this); - + if($event_identifier != '') $app->plugin->raiseEvent($event_identifier, $this); + //$app->uses('tform'); //* Save changes to Datalog if($app->remoting_lib->formDef["db_history"] == 'yes') { $new_rec = $app->remoting_lib->getDataRecord($insert_id); - $app->remoting_lib->datalogSave('INSERT',$primary_id,array(),$new_rec); - } + $app->remoting_lib->datalogSave('INSERT', $primary_id, array(), $new_rec); + } return $insert_id; } - + protected function updateQuery($formdef_file, $client_id, $primary_id, $params, $event_identifier = '') - { + { global $app; - + $sql = $this->updateQueryPrepare($formdef_file, $client_id, $primary_id, $params); - if($sql !== false) return $this->updateQueryExecute($sql, $primary_id, $params,$event_identifier); - else return false; + if($sql !== false) return $this->updateQueryExecute($sql, $primary_id, $params, $event_identifier); + else return false; } - + protected function updateQueryPrepare($formdef_file, $client_id, $primary_id, $params) - { + { global $app; - + $app->uses('remoting_lib'); - + //* load the user profile of the client $app->remoting_lib->loadUserProfile($client_id); - + //* Load the form definition $app->remoting_lib->loadFormDef($formdef_file); - + //* Get the SQL query - $sql = $app->remoting_lib->getSQL($params,'UPDATE',$primary_id); + $sql = $app->remoting_lib->getSQL($params, 'UPDATE', $primary_id); // $this->server->fault('debug', $sql); if($app->remoting_lib->errorMessage != '') { $this->server->fault('data_processing_error', $app->remoting_lib->errorMessage); return false; } - - return $sql; + + return $sql; } protected function updateQueryExecute($sql, $primary_id, $params, $event_identifier = '') - { + { global $app; - + $app->uses('remoting_lib'); - + $old_rec = $app->remoting_lib->getDataRecord($primary_id); - + // set a few values for compatibility with tform actions, mostly used by plugins $this->oldDataRecord = $old_rec; $this->id = $primary_id; $this->dataRecord = $params; - + $app->db->query($sql); - + if($app->db->errorMessage != '') { $this->server->fault('database_error', $app->db->errorMessage . ' '.$sql); return false; } - + $affected_rows = $app->db->affectedRows(); $app->log('Executed updateQueryExecute, raising events now if any: ' . $event_identifier, LOGLEVEL_DEBUG); - - if($event_identifier != '') $app->plugin->raiseEvent($event_identifier,$this); - + + if($event_identifier != '') $app->plugin->raiseEvent($event_identifier, $this); + //* Save changes to Datalog if($app->remoting_lib->formDef["db_history"] == 'yes') { $new_rec = $app->remoting_lib->getDataRecord($primary_id); - $app->remoting_lib->datalogSave('UPDATE',$primary_id,$old_rec,$new_rec); + $app->remoting_lib->datalogSave('UPDATE', $primary_id, $old_rec, $new_rec); } - + return $affected_rows; } protected function deleteQuery($formdef_file, $primary_id, $event_identifier = '') - { + { global $app; - + $app->uses('remoting_lib'); - + //* load the user profile of the client $app->remoting_lib->loadUserProfile(0); - + //* Load the form definition $app->remoting_lib->loadFormDef($formdef_file); - + $old_rec = $app->remoting_lib->getDataRecord($primary_id); - + // set a few values for compatibility with tform actions, mostly used by plugins $this->oldDataRecord = $old_rec; $this->id = $primary_id; $this->dataRecord = $old_rec; $app->log('Executed deleteQuery, raising events now if any: ' . $event_identifier, LOGLEVEL_DEBUG); //$this->dataRecord = $params; - + //* Get the SQL query $sql = $app->remoting_lib->getDeleteSQL($primary_id); $app->db->errorMessage = ''; $app->db->query($sql); $affected_rows = $app->db->affectedRows(); - + if($app->db->errorMessage != '') { $this->server->fault('database_error', $app->db->errorMessage . ' '.$sql); return false; } - + if($event_identifier != '') { - $app->plugin->raiseEvent($event_identifier,$this); + $app->plugin->raiseEvent($event_identifier, $this); } - + //* Save changes to Datalog if($app->remoting_lib->formDef["db_history"] == 'yes') { - $app->remoting_lib->datalogSave('DELETE',$primary_id,$old_rec,array()); + $app->remoting_lib->datalogSave('DELETE', $primary_id, $old_rec, array()); } - - + + return $affected_rows; } - - + + protected function checkPerm($session_id, $function_name) - { - global $app; - $dobre=array(); - $session = $this->getSession($session_id); - if(!$session){ - return false; - } - - $dobre= str_replace(';',',',$session['remote_functions']); + { + global $app; + $dobre=array(); + $session = $this->getSession($session_id); + if(!$session){ + return false; + } + + $dobre= str_replace(';', ',', $session['remote_functions']); $check = in_array($function_name, explode(',', $dobre) ); if(!$check) { - $app->log("REMOTE-LIB DENY: ".$session_id ." /". $function_name, LOGLEVEL_WARN); + $app->log("REMOTE-LIB DENY: ".$session_id ." /". $function_name, LOGLEVEL_WARN); } return $check; } - - + + protected function getSession($session_id) - { + { global $app; - + if(empty($session_id)) { - $this->server->fault('session_id_empty','The SessionID is empty.'); + $this->server->fault('session_id_empty', 'The SessionID is empty.'); return false; } - + $session_id = $app->db->quote($session_id); - + $now = time(); $sql = "SELECT * FROM remote_session WHERE remote_session = '$session_id' AND tstamp >= $now"; $session = $app->db->queryOneRecord($sql); if($session['remote_userid'] > 0) { return $session; } else { - $this->server->fault('session_does_not_exist','The Session is expired or does not exist.'); + $this->server->fault('session_does_not_exist', 'The Session is expired or does not exist.'); return false; } } - + //--- - - + + /** * Gets sites by $sys_userid & $sys_groupid - * @param int session id - * @param int user id - * @param array list of groups - * @return mixed array with sites by user - * @author Julio Montoya BeezNest 2010 + * @param int session id + * @param int user id + * @param array list of groups + * @return mixed array with sites by user + * @author Julio Montoya BeezNest 2010 */ public function client_get_sites_by_user($session_id, $sys_userid, $sys_groupid) { - global $app; - if(!$this->checkPerm($session_id, 'client_get_sites_by_user')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; - } - $sys_userid = $app->functions->intval($sys_userid); - $sys_groupid = explode(',', $sys_groupid); - $new_group = array(); - foreach($sys_groupid as $group_id) { + global $app; + if(!$this->checkPerm($session_id, 'client_get_sites_by_user')) { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $sys_userid = $app->functions->intval($sys_userid); + $sys_groupid = explode(',', $sys_groupid); + $new_group = array(); + foreach($sys_groupid as $group_id) { $new_group[] = $app->functions->intval( $group_id); - } - $group_list = implode(',', $new_group); + } + $group_list = implode(',', $new_group); $sql ="SELECT domain, domain_id, document_root, active FROM web_domain WHERE ( (sys_userid = $sys_userid AND sys_perm_user LIKE '%r%') OR (sys_groupid IN ($group_list) AND sys_perm_group LIKE '%r%') OR sys_perm_other LIKE '%r%') AND type = 'vhost'"; - $result = $app->db->queryAllRecords($sql); - if(isset($result)) { + $result = $app->db->queryAllRecords($sql); + if(isset($result)) { return $result; - } else { + } else { $this->server->fault('no_client_found', 'There is no site for this user'); return false; - } - } - - /** - * Change domains status - * @param int session id - * @param int site id - * @param string active or inactive string - * @return mixed false if error - * @author Julio Montoya BeezNest 2010 + } + } + + + + /** + * Change domains status + * @param int session id + * @param int site id + * @param string active or inactive string + * @return mixed false if error + * @author Julio Montoya BeezNest 2010 */ - - public function sites_web_domain_set_status($session_id, $primary_id, $status) { - global $app; - if(!$this->checkPerm($session_id, 'sites_web_domain_set_status')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; - } - if(in_array($status, array('active', 'inactive'))) { - if ($status == 'active') { - $status = 'y'; - } else { - $status = 'n'; - } - $sql = "UPDATE web_domain SET active = '$status' WHERE domain_id = ".$app->functions->intval($primary_id); - $app->db->query($sql); - $result = $app->db->affectedRows(); - return $result; - } else { + public function sites_web_domain_set_status($session_id, $primary_id, $status) { + global $app; + if(!$this->checkPerm($session_id, 'sites_web_domain_set_status')) { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + if(in_array($status, array('active', 'inactive'))) { + if ($status == 'active') { + $status = 'y'; + } else { + $status = 'n'; + } + $sql = "UPDATE web_domain SET active = '$status' WHERE domain_id = ".$app->functions->intval($primary_id); + $app->db->query($sql); + $result = $app->db->affectedRows(); + return $result; + } else { $this->server->fault('status_undefined', 'The status is not available'); return false; - } + } } - + + + /** * Get sys_user information by username - * @param int session id - * @param string user's name - * @return mixed false if error - * @author Julio Montoya BeezNest 2010 + * @param int session id + * @param string user's name + * @return mixed false if error + * @author Julio Montoya BeezNest 2010 */ public function client_get_by_username($session_id, $username) { - global $app; - if(!$this->checkPerm($session_id, 'client_get_by_username')) { + global $app; + if(!$this->checkPerm($session_id, 'client_get_by_username')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; - } - $username = $app->db->quote($username); - $rec = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE username = '".$username."'"); - if (isset($rec)) { + } + $username = $app->db->quote($username); + $rec = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE username = '".$username."'"); + if (isset($rec)) { return $rec; - } else { + } else { $this->server->fault('no_client_found', 'There is no user account for this user name.'); return false; - } - } - /** - * Get All client_id's from database - * @param int session_id - * @return Array of all client_id's - */ + } + } + + /** + * Get All client_id's from database + * @param int session_id + * @return Array of all client_id's + */ public function client_get_all($session_id) { - global $app; - if(!$this->checkPerm($session_id, 'client_get_all')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; - } - $result = $app->db->queryAllRecords("SELECT client_id FROM client WHERE 1"); - if(!$result) { - return false; - } - foreach( $result as $record) { - $rarrary[] = $record['client_id']; - } - return $rarrary; - } - - /** - * Changes client password - * - * @param int session id - * @param int client id - * @param string new password - * @return bool true if success - * @author Julio Montoya BeezNest 2010 - * - */ - public function client_change_password($session_id, $client_id, $new_password) { - global $app; - - if(!$this->checkPerm($session_id, 'client_change_password')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; - } - $client_id = $app->functions->intval($client_id); - $client = $app->db->queryOneRecord("SELECT client_id FROM client WHERE client_id = ".$client_id); - if($client['client_id'] > 0) { - $new_password = $app->db->quote($new_password); - $sql = "UPDATE client SET password = md5('".($new_password)."') WHERE client_id = ".$client_id; - $app->db->query($sql); - $sql = "UPDATE sys_user SET passwort = md5('".($new_password)."') WHERE client_id = ".$client_id; - $app->db->query($sql); - return true; - } else { + global $app; + if(!$this->checkPerm($session_id, 'client_get_all')) { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $result = $app->db->queryAllRecords("SELECT client_id FROM client WHERE 1"); + if(!$result) { + return false; + } + foreach( $result as $record) { + $rarrary[] = $record['client_id']; + } + return $rarrary; + } + + /** + * Changes client password + * + * @param int session id + * @param int client id + * @param string new password + * @return bool true if success + * @author Julio Montoya BeezNest 2010 + * + */ + public function client_change_password($session_id, $client_id, $new_password) { + global $app; + + if(!$this->checkPerm($session_id, 'client_change_password')) { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + $client_id = $app->functions->intval($client_id); + $client = $app->db->queryOneRecord("SELECT client_id FROM client WHERE client_id = ".$client_id); + if($client['client_id'] > 0) { + $new_password = $app->db->quote($new_password); + $sql = "UPDATE client SET password = md5('".($new_password)."') WHERE client_id = ".$client_id; + $app->db->query($sql); + $sql = "UPDATE sys_user SET passwort = md5('".($new_password)."') WHERE client_id = ".$client_id; + $app->db->query($sql); + return true; + } else { $this->server->fault('no_client_found', 'There is no user account for this client_id'); return false; - } - } + } + } - /** - * Fetch the mail_domain record for the provided domain. - * @param int session_id - * @param string the fully qualified domain (or subdomain) - * @return array array of arrays corresponding to the mail_domain table's records - * @author till, benlake - */ + /** + * Fetch the mail_domain record for the provided domain. + * @param int session_id + * @param string the fully qualified domain (or subdomain) + * @return array array of arrays corresponding to the mail_domain table's records + * @author till, benlake + */ public function mail_domain_get_by_domain($session_id, $domain) { - global $app; - if(!$this->checkPerm($session_id, 'mail_domain_get_by_domain')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; - } - if (!empty($domain)) { - $domain = $app->db->quote($domain); - $sql = "SELECT * FROM mail_domain WHERE domain = '$domain'"; - $result = $app->db->queryAllRecords($sql); - return $result; - } - return false; - } + global $app; + if(!$this->checkPerm($session_id, 'mail_domain_get_by_domain')) { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + if (!empty($domain)) { + $domain = $app->db->quote($domain); + $sql = "SELECT * FROM mail_domain WHERE domain = '$domain'"; + $result = $app->db->queryAllRecords($sql); + return $result; + } + return false; + } /** - * Get a list of functions - * @param int session id - * @return mixed array of the available functions - * @author Julio Montoya BeezNest 2010 - */ - public function get_function_list($session_id) - { - if(!$this->checkPerm($session_id, 'get_function_list')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; - } - return get_class_methods($this); - } - - /** - * Get all databases by user - * @author Julio Montoya BeezNest 2010 - */ + * Get a list of functions + * @param int session id + * @return mixed array of the available functions + * @author Julio Montoya BeezNest 2010 + */ + public function get_function_list($session_id) + { + if(!$this->checkPerm($session_id, 'get_function_list')) { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + return get_class_methods($this); + } + + + + /** + * Get all databases by user + * @author Julio Montoya BeezNest 2010 + */ public function sites_database_get_all_by_user($session_id, $client_id) - { - global $app; + { + global $app; if(!$this->checkPerm($session_id, 'sites_database_get')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; } - $client_id = $app->functions->intval($client_id); - $sql = "SELECT d.database_id, d.database_name, d.database_user_id, d.database_ro_user_id, du.database_user, du.database_password FROM web_database d LEFT JOIN web_database_user du ON (du.database_user_id = d.database_user_id) INNER JOIN sys_user s on(d.sys_groupid = s.default_group) WHERE client_id = $client_id"; + $client_id = $app->functions->intval($client_id); + $sql = "SELECT d.database_id, d.database_name, d.database_user_id, d.database_ro_user_id, du.database_user, du.database_password FROM web_database d LEFT JOIN web_database_user du ON (du.database_user_id = d.database_user_id) INNER JOIN sys_user s on(d.sys_groupid = s.default_group) WHERE client_id = $client_id"; $all = $app->db->queryAllRecords($sql); - return $all; + return $all; } - + + + /** - * Get all client templates - * @param int session id - * @author Julio Montoya BeezNest 2010 + * Get all client templates + * @param int session id + * @author Julio Montoya BeezNest 2010 */ public function client_templates_get_all($session_id) { global $app; if(!$this->checkPerm($session_id, 'client_templates_get_all')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; } - $sql = "SELECT * FROM client_template"; + $sql = "SELECT * FROM client_template"; $result = $app->db->queryAllRecords($sql); - return $result; - } - + return $result; + } + + + /** - * Get all DNS zone by user - *@author Julio Montoya BeezNest 2010 - */ - public function dns_zone_get_by_user($session_id, $client_id, $server_id) { - global $app; - if(!$this->checkPerm($session_id, 'dns_zone_get')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; - } - if (!empty($client_id) && !empty($server_id)) { - $server_id = $app->functions->intval($server_id); - $client_id = $app->functions->intval($client_id); - $sql = "SELECT id, origin FROM dns_soa d INNER JOIN sys_user s on(d.sys_groupid = s.default_group) WHERE client_id = $client_id AND server_id = $server_id"; - $result = $app->db->queryAllRecords($sql); - return $result; - } - return false; - } - + * Get all DNS zone by user + *@author Julio Montoya BeezNest 2010 + */ + public function dns_zone_get_by_user($session_id, $client_id, $server_id) { + global $app; + if(!$this->checkPerm($session_id, 'dns_zone_get')) { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + if (!empty($client_id) && !empty($server_id)) { + $server_id = $app->functions->intval($server_id); + $client_id = $app->functions->intval($client_id); + $sql = "SELECT id, origin FROM dns_soa d INNER JOIN sys_user s on(d.sys_groupid = s.default_group) WHERE client_id = $client_id AND server_id = $server_id"; + $result = $app->db->queryAllRecords($sql); + return $result; + } + return false; + } + + + /** - * Get all dns records for a zone - * @param int session id - * @param int dns zone id - * @author Sebastian Mogilowski 2011 + * Get all dns records for a zone + * @param int session id + * @param int dns zone id + * @author Sebastian Mogilowski 2011 */ public function dns_rr_get_all_by_zone($session_id, $zone_id) { global $app; if(!$this->checkPerm($session_id, 'dns_zone_get')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; } - $sql = "SELECT * FROM dns_rr WHERE zone = ".$app->functions->intval($zone_id);; + $sql = "SELECT * FROM dns_rr WHERE zone = ".$app->functions->intval($zone_id);; $result = $app->db->queryAllRecords($sql); - return $result; - } + return $result; + } /** - * Changes DNS zone status - * @param int session id - * @param int dns soa id - * @param string status active or inactive string - * @author Julio Montoya BeezNest 2010 + * Changes DNS zone status + * @param int session id + * @param int dns soa id + * @param string status active or inactive string + * @author Julio Montoya BeezNest 2010 */ - - public function dns_zone_set_status($session_id, $primary_id, $status) { - global $app; - if(!$this->checkPerm($session_id, 'dns_zone_set_status')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; - } - if(in_array($status, array('active', 'inactive'))) { - if ($status == 'active') { - $status = 'Y'; - } else { - $status = 'N'; - } - $sql = "UPDATE dns_soa SET active = '$status' WHERE id = ".$app->functions->intval($primary_id); - $app->db->query($sql); - $result = $app->db->affectedRows(); - return $result; - } else { + public function dns_zone_set_status($session_id, $primary_id, $status) { + global $app; + if(!$this->checkPerm($session_id, 'dns_zone_set_status')) { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + if(in_array($status, array('active', 'inactive'))) { + if ($status == 'active') { + $status = 'Y'; + } else { + $status = 'N'; + } + $sql = "UPDATE dns_soa SET active = '$status' WHERE id = ".$app->functions->intval($primary_id); + $app->db->query($sql); + $result = $app->db->affectedRows(); + return $result; + } else { $this->server->fault('status_undefined', 'The status is not available'); return false; - } - } - - public function mail_domain_set_status($session_id, $primary_id, $status) { - global $app; - if(!$this->checkPerm($session_id, 'mail_domain_set_status')) { - $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); - return false; - } - if(in_array($status, array('active', 'inactive'))) { - if ($status == 'active') { - $status = 'y'; - } else { - $status = 'n'; - } - $sql = "UPDATE mail_domain SET active = '$status' WHERE domain_id = ".$app->functions->intval($primary_id); - $app->db->query($sql); - $result = $app->db->affectedRows(); - return $result; - } else { + } + } + + public function mail_domain_set_status($session_id, $primary_id, $status) { + global $app; + if(!$this->checkPerm($session_id, 'mail_domain_set_status')) { + $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); + return false; + } + if(in_array($status, array('active', 'inactive'))) { + if ($status == 'active') { + $status = 'y'; + } else { + $status = 'n'; + } + $sql = "UPDATE mail_domain SET active = '$status' WHERE domain_id = ".$app->functions->intval($primary_id); + $app->db->query($sql); + $result = $app->db->affectedRows(); + return $result; + } else { $this->server->fault('status_undefined', 'The status is not available'); return false; - } - } - + } + } + //* Functions for virtual machine management - + //* Get OpenVZ OStemplate details public function openvz_ostemplate_get($session_id, $ostemplate_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -3499,44 +3512,44 @@ class remoting { $app->remoting_lib->loadFormDef('../vm/form/openvz_ostemplate.tform.php'); return $app->remoting_lib->getDataRecord($ostemplate_id); } - + //* Add a openvz ostemplate record public function openvz_ostemplate_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../vm/form/openvz_ostemplate.tform.php',$client_id,$params); + return $this->insertQuery('../vm/form/openvz_ostemplate.tform.php', $client_id, $params); } - + //* Update openvz ostemplate record public function openvz_ostemplate_update($session_id, $client_id, $ostemplate_id, $params) - { + { if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../vm/form/openvz_ostemplate.tform.php',$client_id,$ostemplate_id,$params); + $affected_rows = $this->updateQuery('../vm/form/openvz_ostemplate.tform.php', $client_id, $ostemplate_id, $params); return $affected_rows; } - + //* Delete openvz ostemplate record public function openvz_ostemplate_delete($session_id, $ostemplate_id) - { + { if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../vm/form/openvz_ostemplate.tform.php',$ostemplate_id); + $affected_rows = $this->deleteQuery('../vm/form/openvz_ostemplate.tform.php', $ostemplate_id); return $affected_rows; } - + //* Get OpenVZ template details public function openvz_template_get($session_id, $template_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -3545,44 +3558,44 @@ class remoting { $app->remoting_lib->loadFormDef('../vm/form/openvz_template.tform.php'); return $app->remoting_lib->getDataRecord($template_id); } - + //* Add a openvz template record public function openvz_template_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../vm/form/openvz_template.tform.php',$client_id,$params); + return $this->insertQuery('../vm/form/openvz_template.tform.php', $client_id, $params); } - + //* Update openvz template record public function openvz_template_update($session_id, $client_id, $template_id, $params) - { + { if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../vm/form/openvz_template.tform.php',$client_id,$template_id,$params); + $affected_rows = $this->updateQuery('../vm/form/openvz_template.tform.php', $client_id, $template_id, $params); return $affected_rows; } - + //* Delete openvz template record public function openvz_template_delete($session_id, $template_id) - { + { if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../vm/form/openvz_template.tform.php',$template_id); + $affected_rows = $this->deleteQuery('../vm/form/openvz_template.tform.php', $template_id); return $affected_rows; } - + //* Get OpenVZ ip details public function openvz_ip_get($session_id, $ip_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -3591,68 +3604,68 @@ class remoting { $app->remoting_lib->loadFormDef('../vm/form/openvz_ip.tform.php'); return $app->remoting_lib->getDataRecord($ip_id); } - + //* Get OpenVZ a free IP address public function openvz_get_free_ip($session_id, $server_id = 0) - { + { global $app; - + if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } $server_id = $app->functions->intval($server_id); - + if($server_id > 0) { $tmp = $app->db->queryOneRecord("SELECT ip_address_id, server_id, ip_address FROM openvz_ip WHERE reserved = 'n' AND vm_id = 0 AND server_id = $server_id LIMIT 0,1"); } else { $tmp = $app->db->queryOneRecord("SELECT ip_address_id, server_id, ip_address FROM openvz_ip WHERE reserved = 'n' AND vm_id = 0 LIMIT 0,1"); } - + if(count($tmp) > 0) { return $tmp; } else { $this->server->fault('no_free_ip', 'There is no free IP available.'); } } - + //* Add a openvz ip record public function openvz_ip_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../vm/form/openvz_ip.tform.php',$client_id,$params); + return $this->insertQuery('../vm/form/openvz_ip.tform.php', $client_id, $params); } - + //* Update openvz ip record public function openvz_ip_update($session_id, $client_id, $ip_id, $params) - { + { if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../vm/form/openvz_ip.tform.php',$client_id,$ip_id,$params); + $affected_rows = $this->updateQuery('../vm/form/openvz_ip.tform.php', $client_id, $ip_id, $params); return $affected_rows; } - + //* Delete openvz ip record public function openvz_ip_delete($session_id, $ip_id) - { + { if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../vm/form/openvz_ip.tform.php',$ip_id); + $affected_rows = $this->deleteQuery('../vm/form/openvz_ip.tform.php', $ip_id); return $affected_rows; } - + //* Get OpenVZ vm details public function openvz_vm_get($session_id, $vm_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; @@ -3661,51 +3674,51 @@ class remoting { $app->remoting_lib->loadFormDef('../vm/form/openvz_vm.tform.php'); return $app->remoting_lib->getDataRecord($vm_id); } - + //* Get OpenVZ list public function openvz_vm_get_by_client($session_id, $client_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + if (!empty($client_id)) { - $client_id = $app->functions->intval($client_id); - $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = $client_id"); - $sql = "SELECT * FROM openvz_vm WHERE sys_groupid = ".$app->functions->intval($tmp['groupid']); - $result = $app->db->queryAllRecords($sql); - return $result; - } - return false; - } - + $client_id = $app->functions->intval($client_id); + $tmp = $app->db->queryOneRecord("SELECT groupid FROM sys_group WHERE client_id = $client_id"); + $sql = "SELECT * FROM openvz_vm WHERE sys_groupid = ".$app->functions->intval($tmp['groupid']); + $result = $app->db->queryAllRecords($sql); + return $result; + } + return false; + } + //* Add a openvz vm record public function openvz_vm_add($session_id, $client_id, $params) - { + { if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - return $this->insertQuery('../vm/form/openvz_vm.tform.php',$client_id,$params); + return $this->insertQuery('../vm/form/openvz_vm.tform.php', $client_id, $params); } - + //* Add a openvz vm record from template public function openvz_vm_add_from_template($session_id, $client_id, $ostemplate_id, $template_id, $override_params = array()) - { + { global $app; - + if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - - + + $template_id = $app->functions->intval($template_id); $ostemplate_id = $app->functions->intval($ostemplate_id); - + //* Verify parameters if($template_id == 0) { $this->server->fault('template_id_error', 'Template ID must be > 0.'); @@ -3715,7 +3728,7 @@ class remoting { $this->server->fault('ostemplate_id_error', 'OSTemplate ID must be > 0.'); return false; } - + // Verify if template and ostemplate exist $tmp = $app->db->queryOneRecord("SELECT template_id FROM openvz_template WHERE template_id = $template_id"); if(!is_array($tmp)) { @@ -3727,10 +3740,10 @@ class remoting { $this->server->fault('ostemplate_id_error', 'OSTemplate does not exist.'); return false; } - + //* Get the template $vtpl = $app->db->queryOneRecord("SELECT * FROM openvz_template WHERE template_id = $template_id"); - + //* Get the IP address and server_id if($override_params['server_id'] > 0) { $vmip = $app->db->queryOneRecord("SELECT ip_address_id, server_id, ip_address FROM openvz_ip WHERE reserved = 'n' AND vm_id = 0 AND server_id = ".$override_params['server_id']." LIMIT 0,1"); @@ -3741,7 +3754,7 @@ class remoting { $this->server->fault('vm_ip_error', 'Unable to get a free VM IP.'); return false; } - + //* Build the $params array $params = array(); $params['server_id'] = $vmip['server_id']; @@ -3754,8 +3767,8 @@ class remoting { $params['active'] = (isset($override_params['active']))?$override_params['active']:'y'; $params['active_until_date'] = (isset($override_params['active_until_date']))?$override_params['active_until_date']:'0000-00-00'; $params['description'] = (isset($override_params['description']))?$override_params['description']:''; - - //* The next params get filled with pseudo values, as the get replaced + + //* The next params get filled with pseudo values, as the get replaced //* by the openvz event plugin anyway with values from the template $params['veid'] = 1; $params['diskspace'] = 1; @@ -3768,181 +3781,182 @@ class remoting { $params['nameserver'] = '8.8.8.8 8.8.4.4'; $params['create_dns'] = 'n'; $params['capability'] = ''; - - return $this->insertQuery('../vm/form/openvz_vm.tform.php',$client_id,$params,'vm:openvz_vm:on_after_insert'); + + return $this->insertQuery('../vm/form/openvz_vm.tform.php', $client_id, $params, 'vm:openvz_vm:on_after_insert'); } - + //* Update openvz vm record public function openvz_vm_update($session_id, $client_id, $vm_id, $params) - { + { if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->updateQuery('../vm/form/openvz_vm.tform.php',$client_id,$vm_id,$params,'vm:openvz_vm:on_after_update'); + $affected_rows = $this->updateQuery('../vm/form/openvz_vm.tform.php', $client_id, $vm_id, $params, 'vm:openvz_vm:on_after_update'); return $affected_rows; } - + //* Delete openvz vm record public function openvz_vm_delete($session_id, $vm_id) - { + { if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - $affected_rows = $this->deleteQuery('../vm/form/openvz_vm.tform.php',$vm_id,'vm:openvz_vm:on_after_delete'); + $affected_rows = $this->deleteQuery('../vm/form/openvz_vm.tform.php', $vm_id, 'vm:openvz_vm:on_after_delete'); return $affected_rows; } - + //* Start VM public function openvz_vm_start($session_id, $vm_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + $app->uses('remoting_lib'); $app->remoting_lib->loadFormDef('../vm/form/openvz_vm.tform.php'); $vm = $app->remoting_lib->getDataRecord($vm_id); - + if(!is_array($vm)) { $this->server->fault('action_pending', 'No VM with this ID available.'); return false; } - + if($vm['active'] == 'n') { $this->server->fault('action_pending', 'VM is not in active state.'); return false; } - + $action = 'openvz_start_vm'; - - $tmp = $app->db->queryOneRecord("SELECT count(action_id) as actions FROM sys_remoteaction - WHERE server_id = '".$vm['server_id']."' + + $tmp = $app->db->queryOneRecord("SELECT count(action_id) as actions FROM sys_remoteaction + WHERE server_id = '".$vm['server_id']."' AND action_type = '$action' AND action_param = '".$vm['veid']."' AND action_state = 'pending'"); - + if($tmp['actions'] > 0) { $this->server->fault('action_pending', 'There is already a action pending for this VM.'); return false; } else { $sql = "INSERT INTO sys_remoteaction (server_id, tstamp, action_type, action_param, action_state, response) " . - "VALUES (". - (int)$vm['server_id'] . ", ". - time() . ", ". - "'".$action."', ". - $vm['veid'].", ". - "'pending', ". - "''". - ")"; + "VALUES (". + (int)$vm['server_id'] . ", ". + time() . ", ". + "'".$action."', ". + $vm['veid'].", ". + "'pending', ". + "''". + ")"; $app->db->query($sql); } } - + //* Stop VM public function openvz_vm_stop($session_id, $vm_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + $app->uses('remoting_lib'); $app->remoting_lib->loadFormDef('../vm/form/openvz_vm.tform.php'); $vm = $app->remoting_lib->getDataRecord($vm_id); - + if(!is_array($vm)) { $this->server->fault('action_pending', 'No VM with this ID available.'); return false; } - + if($vm['active'] == 'n') { $this->server->fault('action_pending', 'VM is not in active state.'); return false; } - + $action = 'openvz_stop_vm'; - - $tmp = $app->db->queryOneRecord("SELECT count(action_id) as actions FROM sys_remoteaction - WHERE server_id = '".$vm['server_id']."' + + $tmp = $app->db->queryOneRecord("SELECT count(action_id) as actions FROM sys_remoteaction + WHERE server_id = '".$vm['server_id']."' AND action_type = '$action' AND action_param = '".$vm['veid']."' AND action_state = 'pending'"); - + if($tmp['actions'] > 0) { $this->server->fault('action_pending', 'There is already a action pending for this VM.'); return false; } else { $sql = "INSERT INTO sys_remoteaction (server_id, tstamp, action_type, action_param, action_state, response) " . - "VALUES (". - (int)$vm['server_id'] . ", ". - time() . ", ". - "'".$action."', ". - $vm['veid'].", ". - "'pending', ". - "''". - ")"; + "VALUES (". + (int)$vm['server_id'] . ", ". + time() . ", ". + "'".$action."', ". + $vm['veid'].", ". + "'pending', ". + "''". + ")"; $app->db->query($sql); } } - + //* Restart VM public function openvz_vm_restart($session_id, $vm_id) - { + { global $app; - + if(!$this->checkPerm($session_id, 'vm_openvz')) { $this->server->fault('permission_denied', 'You do not have the permissions to access this function.'); return false; } - + $app->uses('remoting_lib'); $app->remoting_lib->loadFormDef('../vm/form/openvz_vm.tform.php'); $vm = $app->remoting_lib->getDataRecord($vm_id); - + if(!is_array($vm)) { $this->server->fault('action_pending', 'No VM with this ID available.'); return false; } - + if($vm['active'] == 'n') { $this->server->fault('action_pending', 'VM is not in active state.'); return false; } - + $action = 'openvz_restart_vm'; - - $tmp = $app->db->queryOneRecord("SELECT count(action_id) as actions FROM sys_remoteaction - WHERE server_id = '".$vm['server_id']."' + + $tmp = $app->db->queryOneRecord("SELECT count(action_id) as actions FROM sys_remoteaction + WHERE server_id = '".$vm['server_id']."' AND action_type = '$action' AND action_param = '".$vm['veid']."' AND action_state = 'pending'"); - + if($tmp['actions'] > 0) { $this->server->fault('action_pending', 'There is already a action pending for this VM.'); return false; } else { $sql = "INSERT INTO sys_remoteaction (server_id, tstamp, action_type, action_param, action_state, response) " . - "VALUES (". - (int)$vm['server_id'] . ", ". - time() . ", ". - "'".$action."', ". - $vm['veid'].", ". - "'pending', ". - "''". - ")"; + "VALUES (". + (int)$vm['server_id'] . ", ". + time() . ", ". + "'".$action."', ". + $vm['veid'].", ". + "'pending', ". + "''". + ")"; $app->db->query($sql); } } - - - - + + + + } + ?> diff --git a/interface/lib/classes/remoting_lib.inc.php b/interface/lib/classes/remoting_lib.inc.php index 7ecc6633620d7ae851d11cdbbf2ee2cea187d0f3..0b97498acc5e60b92c422e617adee2e42aa12750 100644 --- a/interface/lib/classes/remoting_lib.inc.php +++ b/interface/lib/classes/remoting_lib.inc.php @@ -35,882 +35,890 @@ Copyright (c) Tri-Plex technology */ /** -* Formularbehandlung -* -* Functions to validate, display and save form values -* -* Database table field definitions -* -* Datatypes: -* - INTEGER (Converts data to int automatically) -* - DOUBLE -* - CURRENCY (Formats digits in currency notation) -* - VARCHAR (No format check) -* - DATE (Date format, converts from and to UNIX timestamps automatically) -* -* Formtype: -* - TEXT (Normal text field) -* - PASSWORD (password field, the content will not be displayed again to the user) -* - SELECT (Option fiield) -* - MULTIPLE (Allows selection of multiple values) -* -* VALUE: -* - Value or array -* -* SEPARATOR -* - separator char used for fileds with multiple values -* -* Hint: The auto increment (ID) filed of the table has not be be definied separately. -* -*/ + * Formularbehandlung + * + * Functions to validate, display and save form values + * + * Database table field definitions + * + * Datatypes: + * - INTEGER (Converts data to int automatically) + * - DOUBLE + * - CURRENCY (Formats digits in currency notation) + * - VARCHAR (No format check) + * - DATE (Date format, converts from and to UNIX timestamps automatically) + * + * Formtype: + * - TEXT (Normal text field) + * - PASSWORD (password field, the content will not be displayed again to the user) + * - SELECT (Option fiield) + * - MULTIPLE (Allows selection of multiple values) + * + * VALUE: + * - Value or array + * + * SEPARATOR + * - separator char used for fileds with multiple values + * + * Hint: The auto increment (ID) filed of the table has not be be definied separately. + * + */ + class remoting_lib { - - /** - * Definition of the database table (array) - * @var tableDef - */ - private $tableDef; - - /** - * Private - * @var action - */ - private $action; - - /** - * Table name (String) - * @var table_name - */ - private $table_name; - - /** - * Debug Variable - * @var debug - */ - private $debug = 0; - - /** - * name of the primary field of the database table (string) - * @var table_index - */ - var $table_index; - - /** - * contains the error messages - * @var errorMessage - */ - var $errorMessage = ''; - - var $dateformat = "d.m.Y"; - var $formDef = array(); - var $wordbook; - var $module; - var $primary_id; - var $diffrec = array(); - - var $sys_username; - var $sys_userid; - var $sys_default_group; - var $sys_groups; - var $client_id; - var $dataRecord; - - - //* Load the form definition from file. - function loadFormDef($file) { - global $app,$conf; - - include($file); - - $this->formDef = $form; - unset($this->formDef['tabs']); - - //* Copy all fields from all tabs into one form definition - foreach($form['tabs'] as $tab) { - foreach($tab['fields'] as $key => $value) { - $this->formDef['fields'][$key] = $value; - } + + + + /** + * Definition of the database table (array) + * @var tableDef + */ + private $tableDef; + + /** + * Private + * @var action + */ + private $action; + + /** + * Table name (String) + * @var table_name + */ + private $table_name; + + /** + * Debug Variable + * @var debug + */ + private $debug = 0; + + /** + * name of the primary field of the database table (string) + * @var table_index + */ + var $table_index; + + /** + * contains the error messages + * @var errorMessage + */ + var $errorMessage = ''; + + var $dateformat = "d.m.Y"; + var $formDef = array(); + var $wordbook; + var $module; + var $primary_id; + var $diffrec = array(); + + var $sys_username; + var $sys_userid; + var $sys_default_group; + var $sys_groups; + var $client_id; + var $dataRecord; + + + //* Load the form definition from file. + function loadFormDef($file) { + global $app, $conf; + + include $file; + + $this->formDef = $form; + unset($this->formDef['tabs']); + + //* Copy all fields from all tabs into one form definition + foreach($form['tabs'] as $tab) { + foreach($tab['fields'] as $key => $value) { + $this->formDef['fields'][$key] = $value; } - unset($form); - - $this->dateformat = $app->lng('conf_format_dateshort'); - - return true; - } - - //* Load the user profile - function loadUserProfile($client_id_param = 0) { - global $app,$conf; - - $this->client_id = $app->functions->intval($client_id_param); - - if($this->client_id == 0) { - $this->sys_username = 'admin'; - $this->sys_userid = 1; - $this->sys_default_group = 1; - $this->sys_groups = 1; - $_SESSION["s"]["user"]["typ"] = 'admin'; - } else { - //* load system user - try with sysuser and before with userid (workarrond) - /* + } + unset($form); + + $this->dateformat = $app->lng('conf_format_dateshort'); + + return true; + } + + //* Load the user profile + function loadUserProfile($client_id_param = 0) { + global $app, $conf; + + $this->client_id = $app->functions->intval($client_id_param); + + if($this->client_id == 0) { + $this->sys_username = 'admin'; + $this->sys_userid = 1; + $this->sys_default_group = 1; + $this->sys_groups = 1; + $_SESSION["s"]["user"]["typ"] = 'admin'; + } else { + //* load system user - try with sysuser and before with userid (workarrond) + /* $user = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE sysuser_id = $client_id"); if(empty($user["userid"])) { - $user = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE userid = $client_id"); + $user = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE userid = $client_id"); if(empty($user["userid"])) { $this->errorMessage .= "No sysuser with the ID $client_id found."; return false; } }*/ - - $user = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE client_id = $this->client_id"); - $this->sys_username = $user['username']; - $this->sys_userid = $user['userid']; - $this->sys_default_group = $user['default_group']; - $this->sys_groups = $user['groups']; - // $_SESSION["s"]["user"]["typ"] = $user['typ']; - // we have to force admin priveliges for the remoting API as some function calls might fail otherwise. - $_SESSION["s"]["user"]["typ"] = 'admin'; - } + + $user = $app->db->queryOneRecord("SELECT * FROM sys_user WHERE client_id = $this->client_id"); + $this->sys_username = $user['username']; + $this->sys_userid = $user['userid']; + $this->sys_default_group = $user['default_group']; + $this->sys_groups = $user['groups']; + // $_SESSION["s"]["user"]["typ"] = $user['typ']; + // we have to force admin priveliges for the remoting API as some function calls might fail otherwise. + $_SESSION["s"]["user"]["typ"] = 'admin'; + } return true; - } - - - /** - * Converts the data in the array to human readable format - * Datatype conversion e.g. to show the data in lists - * - * @param record - * @return record - */ - function decode($record) { - $new_record = ''; - if(is_array($record)) { - foreach($this->formDef['fields'] as $key => $field) { - switch ($field['datatype']) { - case 'VARCHAR': - $new_record[$key] = stripslashes($record[$key]); - break; - - case 'TEXT': - $new_record[$key] = stripslashes($record[$key]); - break; - - case 'DATETSTAMP': - if($record[$key] > 0) { - $new_record[$key] = date($this->dateformat,$record[$key]); - } - break; - - case 'DATE': - if($record[$key] != '' && $record[$key] != '0000-00-00') { - $tmp = explode('-',$record[$key]); - $new_record[$key] = date($this->dateformat,mktime(0, 0, 0, $tmp[1] , $tmp[2], $tmp[0])); - } - break; - - case 'INTEGER': - $new_record[$key] = $app->functions->intval($record[$key]); - break; - - case 'DOUBLE': - $new_record[$key] = $record[$key]; - break; - - case 'CURRENCY': - $new_record[$key] = $app->functions->currency_format($record[$key]); - break; - - default: - $new_record[$key] = stripslashes($record[$key]); - } - } + } + + + /** + * Converts the data in the array to human readable format + * Datatype conversion e.g. to show the data in lists + * + * @param record + * @return record + */ + function decode($record) { + $new_record = ''; + if(is_array($record)) { + foreach($this->formDef['fields'] as $key => $field) { + switch ($field['datatype']) { + case 'VARCHAR': + $new_record[$key] = stripslashes($record[$key]); + break; + + case 'TEXT': + $new_record[$key] = stripslashes($record[$key]); + break; + + case 'DATETSTAMP': + if($record[$key] > 0) { + $new_record[$key] = date($this->dateformat, $record[$key]); + } + break; - } - - return $new_record; - } - - /** - * Get the key => value array of a form filled from a datasource definitiom - * - * @param field = array with field definition - * @param record = Dataset as array - * @return key => value array for the value field of a form - */ - - function getDatasourceData($field, $record) { - global $app; - - $values = array(); - - if($field["datasource"]["type"] == 'SQL') { - - // Preparing SQL string. We will replace some - // common placeholders - $querystring = $field["datasource"]["querystring"]; - $querystring = str_replace("{USERID}",$this->sys_userid,$querystring); - $querystring = str_replace("{GROUPID}",$this->sys_default_group,$querystring); - $querystring = str_replace("{GROUPS}",$this->sys_groups,$querystring); - $table_idx = $this->formDef['db_table_idx']; - - $tmp_recordid = (isset($record[$table_idx]))?$record[$table_idx]:0; - $querystring = str_replace("{RECORDID}",$tmp_recordid,$querystring); - unset($tmp_recordid); - - $querystring = str_replace("{AUTHSQL}",$this->getAuthSQL('r'),$querystring); - - // Getting the records - $tmp_records = $app->db->queryAllRecords($querystring); - if($app->db->errorMessage != '') die($app->db->errorMessage); - if(is_array($tmp_records)) { - $key_field = $field["datasource"]["keyfield"]; - $value_field = $field["datasource"]["valuefield"]; - foreach($tmp_records as $tmp_rec) { - $tmp_id = $tmp_rec[$key_field]; - $values[$tmp_id] = $tmp_rec[$value_field]; - } - } - } + case 'DATE': + if($record[$key] != '' && $record[$key] != '0000-00-00') { + $tmp = explode('-', $record[$key]); + $new_record[$key] = date($this->dateformat, mktime(0, 0, 0, $tmp[1] , $tmp[2], $tmp[0])); + } + break; - if($field["datasource"]["type"] == 'CUSTOM') { - // Calls a custom class to validate this record - if($field["datasource"]['class'] != '' and $field["datasource"]['function'] != '') { - $datasource_class = $field["datasource"]['class']; - $datasource_function = $field["datasource"]['function']; - $app->uses($datasource_class); - $values = $app->$datasource_class->$datasource_function($field, $record); - } else { - $this->errorMessage .= "Custom datasource class or function is empty
\r\n"; - } - } + case 'INTEGER': + $new_record[$key] = $app->functions->intval($record[$key]); + break; - return $values; + case 'DOUBLE': + $new_record[$key] = $record[$key]; + break; - } + case 'CURRENCY': + $new_record[$key] = $app->functions->currency_format($record[$key]); + break; - /** - /** - * Rewrite the record data to be stored in the database - * and check values with regular expressions. - * - * @param record = Datensatz als Array - * @return record - */ - function encode($record,$dbencode = true) { + default: + $new_record[$key] = stripslashes($record[$key]); + } + } + + } + + return $new_record; + } + + + /** + * Get the key => value array of a form filled from a datasource definitiom + * + * @param field = array with field definition + * @param record = Dataset as array + * @return key => value array for the value field of a form + */ + function getDatasourceData($field, $record) { global $app; - if(is_array($record)) { - foreach($this->formDef['fields'] as $key => $field) { - //* Apply filter to record value - if(isset($field['filters']) && is_array($field['filters'])) { - $record[$key] = $this->filterField($key, (isset($record[$key]))?$record[$key]:'', $field['filters'], 'SAVE'); - } - - //* Validate record value - if(isset($field['validators']) && is_array($field['validators'])) { - $this->validateField($key, (isset($record[$key]))?$record[$key]:'', $field['validators']); - } + $values = array(); + + if($field["datasource"]["type"] == 'SQL') { + + // Preparing SQL string. We will replace some + // common placeholders + $querystring = $field["datasource"]["querystring"]; + $querystring = str_replace("{USERID}", $this->sys_userid, $querystring); + $querystring = str_replace("{GROUPID}", $this->sys_default_group, $querystring); + $querystring = str_replace("{GROUPS}", $this->sys_groups, $querystring); + $table_idx = $this->formDef['db_table_idx']; + + $tmp_recordid = (isset($record[$table_idx]))?$record[$table_idx]:0; + $querystring = str_replace("{RECORDID}", $tmp_recordid, $querystring); + unset($tmp_recordid); + + $querystring = str_replace("{AUTHSQL}", $this->getAuthSQL('r'), $querystring); + + // Getting the records + $tmp_records = $app->db->queryAllRecords($querystring); + if($app->db->errorMessage != '') die($app->db->errorMessage); + if(is_array($tmp_records)) { + $key_field = $field["datasource"]["keyfield"]; + $value_field = $field["datasource"]["valuefield"]; + foreach($tmp_records as $tmp_rec) { + $tmp_id = $tmp_rec[$key_field]; + $values[$tmp_id] = $tmp_rec[$value_field]; + } + } + } - switch ($field['datatype']) { - case 'VARCHAR': - if(!@is_array($record[$key])) { - $new_record[$key] = (isset($record[$key]))?$record[$key]:''; - } else { - $new_record[$key] = implode($field['separator'],$record[$key]); - } - break; - case 'TEXT': - if(!is_array($record[$key])) { - $new_record[$key] = $record[$key]; - } else { - $new_record[$key] = implode($field['separator'],$record[$key]); - } - break; - case 'DATETSTAMP': - if($record[$key] > 0) { - list($tag,$monat,$jahr) = explode('.',$record[$key]); - $new_record[$key] = mktime(0,0,0,$monat,$tag,$jahr); - } else { - $new_record[$key] = 0; - } - break; - case 'DATE': - if($record[$key] != '' && $record[$key] != '0000-00-00') { - if(function_exists('date_parse_from_format')) { - $date_parts = date_parse_from_format($this->dateformat,$record[$key]); - //list($tag,$monat,$jahr) = explode('.',$record[$key]); - $new_record[$key] = $date_parts['year'].'-'.$date_parts['month'].'-'.$date_parts['day']; - //$tmp = strptime($record[$key],$this->dateformat); - //$new_record[$key] = ($tmp['tm_year']+1900).'-'.($tmp['tm_mon']+1).'-'.$tmp['tm_mday']; - } else { - //$tmp = strptime($record[$key],$this->dateformat); - //$new_record[$key] = ($tmp['tm_year']+1900).'-'.($tmp['tm_mon']+1).'-'.$tmp['tm_mday']; - $tmp = strtotime($record[$key]); - $new_record[$key] = date('Y-m-d',$tmp); - } - } else { - $new_record[$key] = '0000-00-00'; - } - break; - case 'INTEGER': - $new_record[$key] = (isset($record[$key]))?$app->functions->intval($record[$key]):0; - //if($new_record[$key] != $record[$key]) $new_record[$key] = $field['default']; - //if($key == 'refresh') die($record[$key]); - break; - case 'DOUBLE': - $new_record[$key] = $record[$key]; - break; - case 'CURRENCY': - $new_record[$key] = str_replace(",",".",$record[$key]); - break; - - case 'DATETIME': - if (is_array($record[$key])) - { - $filtered_values = array_map(create_function('$item','return (int)$item;'), $record[$key]); - extract($filtered_values, EXTR_PREFIX_ALL, '_dt'); - - if ($_dt_day != 0 && $_dt_month != 0 && $_dt_year != 0) { - $new_record[$key] = date( 'Y-m-d H:i:s', mktime($_dt_hour, $_dt_minute, $_dt_second, $_dt_month, $_dt_day, $_dt_year) ); - } - } - break; - } + if($field["datasource"]["type"] == 'CUSTOM') { + // Calls a custom class to validate this record + if($field["datasource"]['class'] != '' and $field["datasource"]['function'] != '') { + $datasource_class = $field["datasource"]['class']; + $datasource_function = $field["datasource"]['function']; + $app->uses($datasource_class); + $values = $app->$datasource_class->$datasource_function($field, $record); + } else { + $this->errorMessage .= "Custom datasource class or function is empty
\r\n"; + } + } - // The use of the field value is deprecated, use validators instead - if(isset($field['regex']) && $field['regex'] != '') { - // Enable that "." matches also newlines - $field['regex'] .= 's'; - if(!preg_match($field['regex'], $record[$key])) { - $errmsg = $field['errmsg']; - $this->errorMessage .= $errmsg."\r\n"; - } - } - - //* Add slashes to all records, when we encode data which shall be inserted into mysql. - if($dbencode == true) $new_record[$key] = $app->db->quote($new_record[$key]); - } - } - if(isset($record['_ispconfig_pw_crypted'])) $new_record['_ispconfig_pw_crypted'] = $record['_ispconfig_pw_crypted']; // this one is not in form definitions! - return $new_record; - } - - /** - * process the filters for a given field. - * - * @param field_name = Name of the field - * @param field_value = value of the field - * @param filters = Array of filters - * @param filter_event = 'SAVE'or 'SHOW' - * @return record - */ - - function filterField($field_name, $field_value, $filters, $filter_event) { - - global $app; - $returnval = $field_value; - - //* Loop trough all filters - foreach($filters as $filter) { - if($filter['event'] == $filter_event) { - switch ($filter['type']) { - case 'TOLOWER': - $returnval = strtolower($field_value); - break; - case 'TOUPPER': - $returnval = strtoupper($field_value); - break; - case 'IDNTOASCII': - $returnval = $app->functions->idn_encode($field_value); - break; - case 'IDNTOUTF8': - $returnval = $app->functions->idn_decode($field_value); - break; - default: - $this->errorMessage .= "Unknown Filter: ".$filter['type']; - break; + return $values; + + } + + + /** + /** + * Rewrite the record data to be stored in the database + * and check values with regular expressions. + * + * @param record = Datensatz als Array + * @return record + */ + function encode($record, $dbencode = true) { + global $app; + if(is_array($record)) { + foreach($this->formDef['fields'] as $key => $field) { + + //* Apply filter to record value + if(isset($field['filters']) && is_array($field['filters'])) { + $record[$key] = $this->filterField($key, (isset($record[$key]))?$record[$key]:'', $field['filters'], 'SAVE'); + } + + //* Validate record value + if(isset($field['validators']) && is_array($field['validators'])) { + $this->validateField($key, (isset($record[$key]))?$record[$key]:'', $field['validators']); + } + + switch ($field['datatype']) { + case 'VARCHAR': + if(!@is_array($record[$key])) { + $new_record[$key] = (isset($record[$key]))?$record[$key]:''; + } else { + $new_record[$key] = implode($field['separator'], $record[$key]); + } + break; + case 'TEXT': + if(!is_array($record[$key])) { + $new_record[$key] = $record[$key]; + } else { + $new_record[$key] = implode($field['separator'], $record[$key]); + } + break; + case 'DATETSTAMP': + if($record[$key] > 0) { + list($tag, $monat, $jahr) = explode('.', $record[$key]); + $new_record[$key] = mktime(0, 0, 0, $monat, $tag, $jahr); + } else { + $new_record[$key] = 0; + } + break; + case 'DATE': + if($record[$key] != '' && $record[$key] != '0000-00-00') { + if(function_exists('date_parse_from_format')) { + $date_parts = date_parse_from_format($this->dateformat, $record[$key]); + //list($tag,$monat,$jahr) = explode('.',$record[$key]); + $new_record[$key] = $date_parts['year'].'-'.$date_parts['month'].'-'.$date_parts['day']; + //$tmp = strptime($record[$key],$this->dateformat); + //$new_record[$key] = ($tmp['tm_year']+1900).'-'.($tmp['tm_mon']+1).'-'.$tmp['tm_mday']; + } else { + //$tmp = strptime($record[$key],$this->dateformat); + //$new_record[$key] = ($tmp['tm_year']+1900).'-'.($tmp['tm_mon']+1).'-'.$tmp['tm_mday']; + $tmp = strtotime($record[$key]); + $new_record[$key] = date('Y-m-d', $tmp); + } + } else { + $new_record[$key] = '0000-00-00'; + } + break; + case 'INTEGER': + $new_record[$key] = (isset($record[$key]))?$app->functions->intval($record[$key]):0; + //if($new_record[$key] != $record[$key]) $new_record[$key] = $field['default']; + //if($key == 'refresh') die($record[$key]); + break; + case 'DOUBLE': + $new_record[$key] = $record[$key]; + break; + case 'CURRENCY': + $new_record[$key] = str_replace(",", ".", $record[$key]); + break; + + case 'DATETIME': + if (is_array($record[$key])) + { + $filtered_values = array_map(create_function('$item', 'return (int)$item;'), $record[$key]); + extract($filtered_values, EXTR_PREFIX_ALL, '_dt'); + + if ($_dt_day != 0 && $_dt_month != 0 && $_dt_year != 0) { + $new_record[$key] = date( 'Y-m-d H:i:s', mktime($_dt_hour, $_dt_minute, $_dt_second, $_dt_month, $_dt_day, $_dt_year) ); + } + } + break; + } + + // The use of the field value is deprecated, use validators instead + if(isset($field['regex']) && $field['regex'] != '') { + // Enable that "." matches also newlines + $field['regex'] .= 's'; + if(!preg_match($field['regex'], $record[$key])) { + $errmsg = $field['errmsg']; + $this->errorMessage .= $errmsg."\r\n"; } } + + //* Add slashes to all records, when we encode data which shall be inserted into mysql. + if($dbencode == true) $new_record[$key] = $app->db->quote($new_record[$key]); } + } + if(isset($record['_ispconfig_pw_crypted'])) $new_record['_ispconfig_pw_crypted'] = $record['_ispconfig_pw_crypted']; // this one is not in form definitions! + return $new_record; + } - return $returnval; - } - - /** - * process the validators for a given field. - * - * @param field_name = Name of the field - * @param field_value = value of the field - * @param validatoors = Array of validators - * @return record - */ - - function validateField($field_name, $field_value, $validators) { - - global $app; - - $escape = '`'; - - // loop trough the validators - foreach($validators as $validator) { - - switch ($validator['type']) { - case 'REGEX': - $validator['regex'] .= 's'; - if(!preg_match($validator['regex'], $field_value)) { - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - break; - case 'UNIQUE': - if($validator['allowempty'] != 'y') $validator['allowempty'] = 'n'; - if($validator['allowempty'] == 'n' || ($validator['allowempty'] == 'y' && $field_value != '')){ - if($this->action == 'NEW') { - $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ".$escape.$this->formDef['db_table'].$escape. " WHERE $field_name = '".$app->db->quote($field_value)."'"); - if($num_rec["number"] > 0) { - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - } else { - $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ".$escape.$this->formDef['db_table'].$escape. " WHERE $field_name = '".$app->db->quote($field_value)."' AND ".$this->formDef['db_table_idx']." != ".$this->primary_id); - if($num_rec["number"] > 0) { - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - } - } - break; - case 'NOTEMPTY': - if(empty($field_value)) { - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - break; - case 'ISEMAIL': - if(function_exists('filter_var')) { - if(filter_var($field_value, FILTER_VALIDATE_EMAIL) === false) { - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - } else { - if(!preg_match("/^\w+[\w\.\-\+]*\w{0,}@\w+[\w.-]*\w+\.[a-zA-Z0-9\-]{2,30}$/i", $field_value)) { - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - } - break; - case 'ISINT': - if(function_exists('filter_var')) { - if($field_value != '' && filter_var($field_value, FILTER_VALIDATE_INT) === false) { - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - } else { - $tmpval = $app->functions->intval($field_value); - if($tmpval === 0 and !empty($field_value)) { - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - } - break; - case 'ISPOSITIVE': - if(!is_numeric($field_value) || $field_value <= 0){ - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - break; - case 'ISIPV4': - $vip=1; - if(preg_match("/^[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}$/", $field_value)){ - $groups=explode(".",$field_value); - foreach($groups as $group){ - if($group<0 OR $group>255) - $vip=0; - } - }else{$vip=0;} - if($vip==0) { - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - break; - case 'ISIP': - if($validator['allowempty'] != 'y') $validator['allowempty'] = 'n'; - if($validator['allowempty'] == 'y' && $field_value == '') { - //* Do nothing - } else { - //* Check if its a IPv4 or IPv6 address - if(isset($validator['separator']) && $validator['separator'] != '') { - //* When the field may contain several IP addresses, split them by the char defined as separator - $field_value_array = explode($validator['separator'],$field_value); - } else { - $field_value_array[] = $field_value; - } - foreach($field_value_array as $field_value) { - if(function_exists('filter_var')) { - if(!filter_var($field_value,FILTER_VALIDATE_IP)) { - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - } else { - //* Check content with regex, if we use php < 5.2 - $ip_ok = 0; - if(preg_match("/^(\:\:([a-f0-9]{1,4}\:){0,6}?[a-f0-9]{0,4}|[a-f0-9]{1,4}(\:[a-f0-9]{1,4}){0,6}?\:\:|[a-f0-9]{1,4}(\:[a-f0-9]{1,4}){1,6}?\:\:([a-f0-9]{1,4}\:){1,6}?[a-f0-9]{1,4})(\/\d{1,3})?$/i", $field_value)){ - $ip_ok = 1; - } - if(preg_match("/^[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}$/", $field_value)){ - $ip_ok = 1; - } - if($ip_ok == 0) { - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - } - } - } - break; - case 'RANGE': - //* Checks if the value is within the given range or above / below a value - //* Range examples: < 10 = ":10", between 2 and 10 = "2:10", above 5 = "5:". - $range_parts = explode(':',trim($validator['range'])); - $ok = true; - if($range_parts[0] != '' && $field_value < $range_parts[0]) { - $ok = false; - } - if($range_parts[1] != '' && $field_value > $range_parts[1]) { - $ok = false; - } - if($ok != true) { - $errmsg = $validator['errmsg']; - if(isset($this->wordbook[$errmsg])) { - $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; - } else { - $this->errorMessage .= $errmsg."
\r\n"; - } - } - unset($range_parts); - break; - case 'CUSTOM': - // Calls a custom class to validate this record - if($validator['class'] != '' and $validator['function'] != '') { - $validator_class = $validator['class']; - $validator_function = $validator['function']; - $app->uses($validator_class); - $this->errorMessage .= $app->$validator_class->$validator_function($field_name, $field_value, $validator); - } else { - $this->errorMessage .= "Custom validator class or function is empty
\r\n"; - } - break; - default: - $this->errorMessage .= "Unknown Validator: ".$validator['type']; - break; - } - } - return true; - } - - /** - * Create SQL statement - * - * @param record = Datensatz als Array - * @param action = INSERT oder UPDATE - * @param primary_id - * @return record - */ - function getSQL($record, $action = 'INSERT', $primary_id = 0, $sql_ext_where = '') { - - global $app; - - $this->action = $action; - $this->primary_id = $primary_id; - $this->dataRecord = $record; - - $record = $this->encode($record,true); - $sql_insert_key = ''; - $sql_insert_val = ''; - $sql_update = ''; - - if(!is_array($this->formDef)) $app->error("Form definition not found."); - - // go trough all fields of the tab - if(is_array($record)) { - foreach($this->formDef['fields'] as $key => $field) { - // Wenn es kein leeres Passwortfeld ist - if (!($field['formtype'] == 'PASSWORD' and $record[$key] == '')) { - // Erzeuge Insert oder Update Quelltext - if($action == "INSERT") { - if($field['formtype'] == 'PASSWORD') { - $sql_insert_key .= "`$key`, "; - if ((isset($field['encryption']) && $field['encryption'] == 'CLEARTEXT') || (isset($record['_ispconfig_pw_crypted']) && $record['_ispconfig_pw_crypted'] == 1)) { - $sql_insert_val .= "'".$app->db->quote($record[$key])."', "; - } elseif(isset($field['encryption']) && $field['encryption'] == 'CRYPT') { - $record[$key] = $app->auth->crypt_password(stripslashes($record[$key])); - $sql_insert_val .= "'".$app->db->quote($record[$key])."', "; - } elseif (isset($field['encryption']) && $field['encryption'] == 'MYSQL') { - $tmp = $app->db->queryOneRecord("SELECT PASSWORD('".$app->db->quote(stripslashes($record[$key]))."') as `crypted`"); - $record[$key] = $tmp['crypted']; - $sql_insert_val .= "'".$app->db->quote($record[$key])."', "; - } else { - $record[$key] = md5(stripslashes($record[$key])); - $sql_insert_val .= "'".$app->db->quote($record[$key])."', "; - } - - } elseif ($field['formtype'] == 'CHECKBOX') { - $sql_insert_key .= "`$key`, "; - if($record[$key] == '') { - // if a checkbox is not set, we set it to the unchecked value - $sql_insert_val .= "'".$field['value'][0]."', "; - $record[$key] = $field['value'][0]; - } else { - $sql_insert_val .= "'".$record[$key]."', "; - } - } else { - $sql_insert_key .= "`$key`, "; - $sql_insert_val .= "'".$record[$key]."', "; - } - } else { - if($field['formtype'] == 'PASSWORD') { - if ((isset($field['encryption']) && $field['encryption'] == 'CLEARTEXT') || (isset($record['_ispconfig_pw_crypted']) && $record['_ispconfig_pw_crypted'] == 1)) { - $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', "; - } elseif(isset($field['encryption']) && $field['encryption'] == 'CRYPT') { - $record[$key] = $app->auth->crypt_password(stripslashes($record[$key])); - $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', "; - } elseif (isset($field['encryption']) && $field['encryption'] == 'MYSQL') { - $tmp = $app->db->queryOneRecord("SELECT PASSWORD('".$app->db->quote(stripslashes($record[$key]))."') as `crypted`"); - $record[$key] = $tmp['crypted']; - $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', "; - } else { - $record[$key] = md5(stripslashes($record[$key])); - $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', "; - } - - } elseif ($field['formtype'] == 'CHECKBOX') { - if($record[$key] == '') { - // if a checkbox is not set, we set it to the unchecked value - $sql_update .= "`$key` = '".$field['value'][0]."', "; - $record[$key] = $field['value'][0]; - } else { - $sql_update .= "`$key` = '".$record[$key]."', "; - } - } else { - $sql_update .= "`$key` = '".$record[$key]."', "; - } - } - } else { - // we unset the password filed, if empty to tell the datalog function - // that the password has not been changed - unset($record[$key]); - } - } - } + /** + * process the filters for a given field. + * + * @param field_name = Name of the field + * @param field_value = value of the field + * @param filters = Array of filters + * @param filter_event = 'SAVE'or 'SHOW' + * @return record + */ + function filterField($field_name, $field_value, $filters, $filter_event) { - // Add backticks for incomplete table names - if(stristr($this->formDef['db_table'],'.')) { - $escape = ''; - } else { - $escape = '`'; - } + global $app; + $returnval = $field_value; + + //* Loop trough all filters + foreach($filters as $filter) { + if($filter['event'] == $filter_event) { + switch ($filter['type']) { + case 'TOLOWER': + $returnval = strtolower($field_value); + break; + case 'TOUPPER': + $returnval = strtoupper($field_value); + break; + case 'IDNTOASCII': + $returnval = $app->functions->idn_encode($field_value); + break; + case 'IDNTOUTF8': + $returnval = $app->functions->idn_decode($field_value); + break; + default: + $this->errorMessage .= "Unknown Filter: ".$filter['type']; + break; + } + } + } + return $returnval; + } - if($action == "INSERT") { - if($this->formDef['auth'] == 'yes') { - // Set user and group - $sql_insert_key .= "`sys_userid`, "; - $sql_insert_val .= ($this->formDef["auth_preset"]["userid"] > 0)?"'".$this->formDef["auth_preset"]["userid"]."', ":"'".$this->sys_userid."', "; - $sql_insert_key .= "`sys_groupid`, "; - $sql_insert_val .= ($this->formDef["auth_preset"]["groupid"] > 0)?"'".$this->formDef["auth_preset"]["groupid"]."', ":"'".$this->sys_default_group."', "; - $sql_insert_key .= "`sys_perm_user`, "; - $sql_insert_val .= "'".$this->formDef["auth_preset"]["perm_user"]."', "; - $sql_insert_key .= "`sys_perm_group`, "; - $sql_insert_val .= "'".$this->formDef["auth_preset"]["perm_group"]."', "; - $sql_insert_key .= "`sys_perm_other`, "; - $sql_insert_val .= "'".$this->formDef["auth_preset"]["perm_other"]."', "; - } - $sql_insert_key = substr($sql_insert_key,0,-2); - $sql_insert_val = substr($sql_insert_val,0,-2); - $sql = "INSERT INTO ".$escape.$this->formDef['db_table'].$escape." ($sql_insert_key) VALUES ($sql_insert_val)"; - } else { - if($primary_id != 0) { - // update client permissions only if client_id > 0 - if($this->formDef['auth'] == 'yes' && $this->client_id > 0) { - $sql_update .= '`sys_userid` = '.$this->sys_userid.', '; - $sql_update .= '`sys_groupid` = '.$this->sys_default_group.', '; + + /** + * process the validators for a given field. + * + * @param field_name = Name of the field + * @param field_value = value of the field + * @param validatoors = Array of validators + * @return record + */ + function validateField($field_name, $field_value, $validators) { + + global $app; + + $escape = '`'; + + // loop trough the validators + foreach($validators as $validator) { + + switch ($validator['type']) { + case 'REGEX': + $validator['regex'] .= 's'; + if(!preg_match($validator['regex'], $field_value)) { + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; + } + } + break; + case 'UNIQUE': + if($validator['allowempty'] != 'y') $validator['allowempty'] = 'n'; + if($validator['allowempty'] == 'n' || ($validator['allowempty'] == 'y' && $field_value != '')){ + if($this->action == 'NEW') { + $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ".$escape.$this->formDef['db_table'].$escape. " WHERE $field_name = '".$app->db->quote($field_value)."'"); + if($num_rec["number"] > 0) { + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; + } + } + } else { + $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ".$escape.$this->formDef['db_table'].$escape. " WHERE $field_name = '".$app->db->quote($field_value)."' AND ".$this->formDef['db_table_idx']." != ".$this->primary_id); + if($num_rec["number"] > 0) { + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; + } + } + } + } + break; + case 'NOTEMPTY': + if(empty($field_value)) { + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; + } + } + break; + case 'ISEMAIL': + if(function_exists('filter_var')) { + if(filter_var($field_value, FILTER_VALIDATE_EMAIL) === false) { + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; + } + } + } else { + if(!preg_match("/^\w+[\w\.\-\+]*\w{0,}@\w+[\w.-]*\w+\.[a-zA-Z0-9\-]{2,30}$/i", $field_value)) { + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; + } + } + } + break; + case 'ISINT': + if(function_exists('filter_var')) { + if($field_value != '' && filter_var($field_value, FILTER_VALIDATE_INT) === false) { + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; + } + } + } else { + $tmpval = $app->functions->intval($field_value); + if($tmpval === 0 and !empty($field_value)) { + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; + } + } + } + break; + case 'ISPOSITIVE': + if(!is_numeric($field_value) || $field_value <= 0){ + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; + } + } + break; + case 'ISIPV4': + $vip=1; + if(preg_match("/^[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}$/", $field_value)){ + $groups=explode(".", $field_value); + foreach($groups as $group){ + if($group<0 or $group>255) + $vip=0; + } + }else{$vip=0;} + if($vip==0) { + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; + } + } + break; + case 'ISIP': + if($validator['allowempty'] != 'y') $validator['allowempty'] = 'n'; + if($validator['allowempty'] == 'y' && $field_value == '') { + //* Do nothing + } else { + //* Check if its a IPv4 or IPv6 address + if(isset($validator['separator']) && $validator['separator'] != '') { + //* When the field may contain several IP addresses, split them by the char defined as separator + $field_value_array = explode($validator['separator'], $field_value); + } else { + $field_value_array[] = $field_value; + } + foreach($field_value_array as $field_value) { + if(function_exists('filter_var')) { + if(!filter_var($field_value, FILTER_VALIDATE_IP)) { + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; } - $sql_update = substr($sql_update,0,-2); - $sql = "UPDATE ".$escape.$this->formDef['db_table'].$escape." SET ".$sql_update." WHERE ".$this->formDef['db_table_idx']." = ".$primary_id; - if($sql_ext_where != '') $sql .= " and ".$sql_ext_where; - } else { - $app->error("Primary ID fehlt!"); - } - } - - return $sql; - } - - function getDeleteSQL($primary_id) { - - if(stristr($this->formDef['db_table'],'.')) { - $escape = ''; - } else { - $escape = '`'; + } + } else { + //* Check content with regex, if we use php < 5.2 + $ip_ok = 0; + if(preg_match("/^(\:\:([a-f0-9]{1,4}\:){0,6}?[a-f0-9]{0,4}|[a-f0-9]{1,4}(\:[a-f0-9]{1,4}){0,6}?\:\:|[a-f0-9]{1,4}(\:[a-f0-9]{1,4}){1,6}?\:\:([a-f0-9]{1,4}\:){1,6}?[a-f0-9]{1,4})(\/\d{1,3})?$/i", $field_value)){ + $ip_ok = 1; + } + if(preg_match("/^[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}$/", $field_value)){ + $ip_ok = 1; + } + if($ip_ok == 0) { + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; + } + } + } + } + } + break; + case 'RANGE': + //* Checks if the value is within the given range or above / below a value + //* Range examples: < 10 = ":10", between 2 and 10 = "2:10", above 5 = "5:". + $range_parts = explode(':', trim($validator['range'])); + $ok = true; + if($range_parts[0] != '' && $field_value < $range_parts[0]) { + $ok = false; + } + if($range_parts[1] != '' && $field_value > $range_parts[1]) { + $ok = false; + } + if($ok != true) { + $errmsg = $validator['errmsg']; + if(isset($this->wordbook[$errmsg])) { + $this->errorMessage .= $this->wordbook[$errmsg]."
\r\n"; + } else { + $this->errorMessage .= $errmsg."
\r\n"; + } + } + unset($range_parts); + break; + case 'CUSTOM': + // Calls a custom class to validate this record + if($validator['class'] != '' and $validator['function'] != '') { + $validator_class = $validator['class']; + $validator_function = $validator['function']; + $app->uses($validator_class); + $this->errorMessage .= $app->$validator_class->$validator_function($field_name, $field_value, $validator); + } else { + $this->errorMessage .= "Custom validator class or function is empty
\r\n"; + } + break; + default: + $this->errorMessage .= "Unknown Validator: ".$validator['type']; + break; } - - $sql = "DELETE FROM ".$escape.$this->formDef['db_table'].$escape." WHERE ".$this->formDef['db_table_idx']." = ".$primary_id; - return $sql; + + } + return true; + } - function getDataRecord($primary_id) { - global $app; - $escape = '`'; - if(@is_numeric($primary_id)) { - $sql = "SELECT * FROM ".$escape.$this->formDef['db_table'].$escape." WHERE ".$this->formDef['db_table_idx']." = ".$primary_id; - return $app->db->queryOneRecord($sql); - } elseif (@is_array($primary_id) || @is_object($primary_id)) { - if(@is_object($primary_id)) $primary_id = get_object_vars($primary_id); // do not use cast (array)xxx because it returns private and protected properties! - $sql_offset = 0; - $sql_limit = 0; - $sql_where = ''; - foreach($primary_id as $key => $val) { - $key = $app->db->quote($key); - $val = $app->db->quote($val); - if($key == '#OFFSE