Marius Cramer
2013-11-14 b1a6a5a3991cec5cd08873b01376e45d0b247f18
Cleaning up code to match coding guidelines
867 files modified
108511 ■■■■ changed files
helper_scripts/dns_export_to_bind.php 148 ●●●● patch | view | raw | blame | history
helper_scripts/dns_export_to_bind_retrans_daily.php 8 ●●●● patch | view | raw | blame | history
helper_scripts/mydns_to_powerdns_migration.php 86 ●●●● patch | view | raw | blame | history
helper_scripts/recreate_webalizer_stats.php 44 ●●●● patch | view | raw | blame | history
install/autoupdate.php 46 ●●●● patch | view | raw | blame | history
install/dist/conf/centos52.conf.php 4 ●●●● patch | view | raw | blame | history
install/dist/conf/centos53.conf.php 4 ●●●● patch | view | raw | blame | history
install/dist/conf/debian40.conf.php 4 ●●●● patch | view | raw | blame | history
install/dist/conf/debian60.conf.php 6 ●●●● patch | view | raw | blame | history
install/dist/conf/fedora9.conf.php 4 ●●●● patch | view | raw | blame | history
install/dist/conf/gentoo.conf.php 8 ●●●● patch | view | raw | blame | history
install/dist/conf/opensuse110.conf.php 4 ●●●● patch | view | raw | blame | history
install/dist/conf/opensuse112.conf.php 4 ●●●● patch | view | raw | blame | history
install/dist/lib/centos52.lib.php 88 ●●●● patch | view | raw | blame | history
install/dist/lib/centos53.lib.php 88 ●●●● patch | view | raw | blame | history
install/dist/lib/debian40.lib.php 2 ●●● patch | view | raw | blame | history
install/dist/lib/debian60.lib.php 79 ●●●● patch | view | raw | blame | history
install/dist/lib/fedora.lib.php 890 ●●●● patch | view | raw | blame | history
install/dist/lib/fedora9.lib.php 2 ●●● patch | view | raw | blame | history
install/dist/lib/gentoo.lib.php 625 ●●●● patch | view | raw | blame | history
install/dist/lib/opensuse.lib.php 934 ●●●● patch | view | raw | blame | history
install/dist/lib/opensuse110.lib.php 2 ●●● patch | view | raw | blame | history
install/dist/lib/opensuse112.lib.php 2 ●●● patch | view | raw | blame | history
install/install.php 206 ●●●● patch | view | raw | blame | history
install/lib/install.lib.php 263 ●●●● patch | view | raw | blame | history
install/lib/installer_base.lib.php 767 ●●●● patch | view | raw | blame | history
install/lib/mysql.lib.php 574 ●●●● patch | view | raw | blame | history
install/lib/update.lib.php 108 ●●●● patch | view | raw | blame | history
install/patches/upd_0001.php 16 ●●●●● patch | view | raw | blame | history
install/setrights.php 36 ●●●● patch | view | raw | blame | history
install/uninstall-fedora.php 8 ●●●● patch | view | raw | blame | history
install/uninstall.php 8 ●●●● patch | view | raw | blame | history
install/update.php 160 ●●●● patch | view | raw | blame | history
interface/lib/app.inc.php 48 ●●●● patch | view | raw | blame | history
interface/lib/classes/aps_base.inc.php 120 ●●●● patch | view | raw | blame | history
interface/lib/classes/aps_crawler.inc.php 992 ●●●● patch | view | raw | blame | history
interface/lib/classes/aps_guicontroller.inc.php 1402 ●●●● patch | view | raw | blame | history
interface/lib/classes/auth.inc.php 66 ●●●● patch | view | raw | blame | history
interface/lib/classes/client_templates.inc.php 427 ●●●● patch | view | raw | blame | history
interface/lib/classes/cmstree.inc.php 18 ●●●● patch | view | raw | blame | history
interface/lib/classes/custom_datasource.inc.php 68 ●●●● patch | view | raw | blame | history
interface/lib/classes/db_firebird.inc.php 385 ●●●● patch | view | raw | blame | history
interface/lib/classes/db_mysql.inc.php 936 ●●●● patch | view | raw | blame | history
interface/lib/classes/form.inc.php 551 ●●●● patch | view | raw | blame | history
interface/lib/classes/functions.inc.php 270 ●●●● patch | view | raw | blame | history
interface/lib/classes/getconf.inc.php 7 ●●●●● patch | view | raw | blame | history
interface/lib/classes/importer.inc.php 69 ●●●● patch | view | raw | blame | history
interface/lib/classes/ini_parser.inc.php 4 ●●●● patch | view | raw | blame | history
interface/lib/classes/ispcmail.inc.php 1383 ●●●● patch | view | raw | blame | history
interface/lib/classes/ispconfig_request.inc.php 445 ●●●● patch | view | raw | blame | history
interface/lib/classes/json_handler.inc.php 169 ●●●● patch | view | raw | blame | history
interface/lib/classes/listform.inc.php 826 ●●●● patch | view | raw | blame | history
interface/lib/classes/listform_actions.inc.php 251 ●●●● patch | view | raw | blame | history
interface/lib/classes/listform_tpl_generator.inc.php 90 ●●●● patch | view | raw | blame | history
interface/lib/classes/plugin.inc.php 120 ●●●● patch | view | raw | blame | history
interface/lib/classes/plugin_backuplist.inc.php 218 ●●●● patch | view | raw | blame | history
interface/lib/classes/plugin_base.inc.php 26 ●●●● patch | view | raw | blame | history
interface/lib/classes/plugin_dbhistory.inc.php 67 ●●●● patch | view | raw | blame | history
interface/lib/classes/plugin_listview.inc.php 217 ●●●● patch | view | raw | blame | history
interface/lib/classes/remote.d/client.inc.php 638 ●●●● patch | view | raw | blame | history
interface/lib/classes/remote.d/dns.inc.php 518 ●●●● patch | view | raw | blame | history
interface/lib/classes/remote.d/domains.inc.php 34 ●●●● patch | view | raw | blame | history
interface/lib/classes/remote.d/mail.inc.php 816 ●●●● patch | view | raw | blame | history
interface/lib/classes/remote.d/openvz.inc.php 273 ●●●● patch | view | raw | blame | history
interface/lib/classes/remote.d/server.inc.php 52 ●●●● patch | view | raw | blame | history
interface/lib/classes/remote.d/sites.inc.php 595 ●●●● patch | view | raw | blame | history
interface/lib/classes/remoting.inc.php 503 ●●●● patch | view | raw | blame | history
interface/lib/classes/remoting_lib.inc.php 502 ●●●● patch | view | raw | blame | history
interface/lib/classes/searchform.inc.php 548 ●●●● patch | view | raw | blame | history
interface/lib/classes/searchform_actions.inc.php 99 ●●●● patch | view | raw | blame | history
interface/lib/classes/searchform_tpl_generator.inc.php 60 ●●●● patch | view | raw | blame | history
interface/lib/classes/session.inc.php 92 ●●●● patch | view | raw | blame | history
interface/lib/classes/simplepie.inc.php 3191 ●●●● patch | view | raw | blame | history
interface/lib/classes/sites_database_plugin.inc.php 59 ●●●● patch | view | raw | blame | history
interface/lib/classes/soap_handler.inc.php 115 ●●●● patch | view | raw | blame | history
interface/lib/classes/tform.inc.php 510 ●●●● patch | view | raw | blame | history
interface/lib/classes/tform_actions.inc.php 1048 ●●●● patch | view | raw | blame | history
interface/lib/classes/tform_base.inc.php 2367 ●●●● patch | view | raw | blame | history
interface/lib/classes/tform_tpl_generator.inc.php 293 ●●●● patch | view | raw | blame | history
interface/lib/classes/tools_monitor.inc.php 714 ●●●● patch | view | raw | blame | history
interface/lib/classes/tools_sites.inc.php 275 ●●●● patch | view | raw | blame | history
interface/lib/classes/tpl.inc.php 2246 ●●●● patch | view | raw | blame | history
interface/lib/classes/tpl_cache.inc.php 287 ●●●● patch | view | raw | blame | history
interface/lib/classes/tpl_error.inc.php 113 ●●●● patch | view | raw | blame | history
interface/lib/classes/tpl_ini.inc.php 111 ●●●● patch | view | raw | blame | history
interface/lib/classes/tree.inc.php 354 ●●●● patch | view | raw | blame | history
interface/lib/classes/validate_autoresponder.inc.php 27 ●●●● patch | view | raw | blame | history
interface/lib/classes/validate_client.inc.php 72 ●●●● patch | view | raw | blame | history
interface/lib/classes/validate_cron.inc.php 304 ●●●● patch | view | raw | blame | history
interface/lib/classes/validate_database.inc.php 72 ●●●● patch | view | raw | blame | history
interface/lib/classes/validate_datetime.inc.php 78 ●●●●● patch | view | raw | blame | history
interface/lib/classes/validate_dkim.inc.php 107 ●●●● patch | view | raw | blame | history
interface/lib/classes/validate_dns.inc.php 472 ●●●● patch | view | raw | blame | history
interface/lib/classes/validate_domain.inc.php 249 ●●●● patch | view | raw | blame | history
interface/lib/classes/validate_ftpuser.inc.php 110 ●●●● patch | view | raw | blame | history
interface/lib/classes/validate_reseller.inc.php 16 ●●●● patch | view | raw | blame | history
interface/lib/config.inc.php 54 ●●●● patch | view | raw | blame | history
interface/lib/plugins/clients_template_plugin.inc.php 42 ●●●● patch | view | raw | blame | history
interface/lib/plugins/mail_user_filter_plugin.inc.php 114 ●●●● patch | view | raw | blame | history
interface/lib/plugins/sites_web_database_user_plugin.inc.php 60 ●●●● patch | view | raw | blame | history
interface/lib/plugins/sites_web_domain_plugin.inc.php 124 ●●●● patch | view | raw | blame | history
interface/lib/plugins/sites_web_vhost_subdomain_plugin.inc.php 58 ●●●● patch | view | raw | blame | history
interface/lib/plugins/vm_openvz_plugin.inc.php 217 ●●●● patch | view | raw | blame | history
interface/web/admin/directive_snippets_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/directive_snippets_edit.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/directive_snippets_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/firewall_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/firewall_edit.php 7 ●●●●● patch | view | raw | blame | history
interface/web/admin/firewall_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/form/dbsync.tform.php 330 ●●●● patch | view | raw | blame | history
interface/web/admin/form/directive_snippets.tform.php 94 ●●●● patch | view | raw | blame | history
interface/web/admin/form/filesync.tform.php 238 ●●●● patch | view | raw | blame | history
interface/web/admin/form/firewall.tform.php 114 ●●●● patch | view | raw | blame | history
interface/web/admin/form/groups.tform.php 86 ●●●● patch | view | raw | blame | history
interface/web/admin/form/iptables.tform.php 168 ●●●● patch | view | raw | blame | history
interface/web/admin/form/remote_user.tform.php 126 ●●●● patch | view | raw | blame | history
interface/web/admin/form/server.tform.php 118 ●●●● patch | view | raw | blame | history
interface/web/admin/form/server_config.tform.php 206 ●●●● patch | view | raw | blame | history
interface/web/admin/form/server_ip.tform.php 150 ●●●● patch | view | raw | blame | history
interface/web/admin/form/server_php.tform.php 118 ●●●● patch | view | raw | blame | history
interface/web/admin/form/software_package.tform.php 82 ●●●● patch | view | raw | blame | history
interface/web/admin/form/software_repo.tform.php 142 ●●●● patch | view | raw | blame | history
interface/web/admin/form/system_config.tform.php 588 ●●●● patch | view | raw | blame | history
interface/web/admin/form/tpl_default.tform.php 70 ●●●● patch | view | raw | blame | history
interface/web/admin/form/users.tform.php 348 ●●●● patch | view | raw | blame | history
interface/web/admin/groups_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/groups_edit.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/groups_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/index.php 13 ●●●● patch | view | raw | blame | history
interface/web/admin/iptables_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/iptables_edit.php 8 ●●●● patch | view | raw | blame | history
interface/web/admin/iptables_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/language_add.php 48 ●●●● patch | view | raw | blame | history
interface/web/admin/language_complete.php 94 ●●●● patch | view | raw | blame | history
interface/web/admin/language_edit.php 24 ●●●● patch | view | raw | blame | history
interface/web/admin/language_export.php 52 ●●●● patch | view | raw | blame | history
interface/web/admin/language_import.php 182 ●●●● patch | view | raw | blame | history
interface/web/admin/language_list.php 58 ●●●● patch | view | raw | blame | history
interface/web/admin/lib/module.conf.php 196 ●●●● patch | view | raw | blame | history
interface/web/admin/lib/remote.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/admin/list/directive_snippets.list.php 70 ●●●● patch | view | raw | blame | history
interface/web/admin/list/firewall.list.php 96 ●●●● patch | view | raw | blame | history
interface/web/admin/list/groups.list.php 46 ●●●● patch | view | raw | blame | history
interface/web/admin/list/iptables.list.php 182 ●●●● patch | view | raw | blame | history
interface/web/admin/list/remote_user.list.php 49 ●●●● patch | view | raw | blame | history
interface/web/admin/list/server.list.php 140 ●●●● patch | view | raw | blame | history
interface/web/admin/list/server_config.list.php 38 ●●●● patch | view | raw | blame | history
interface/web/admin/list/server_ip.list.php 130 ●●●● patch | view | raw | blame | history
interface/web/admin/list/server_php.list.php 86 ●●●● patch | view | raw | blame | history
interface/web/admin/list/software_repo.list.php 70 ●●●● patch | view | raw | blame | history
interface/web/admin/list/users.list.php 74 ●●●● patch | view | raw | blame | history
interface/web/admin/login_as.php 16 ●●●● patch | view | raw | blame | history
interface/web/admin/remote_action_ispcupdate.php 26 ●●●● patch | view | raw | blame | history
interface/web/admin/remote_action_osupdate.php 26 ●●●● patch | view | raw | blame | history
interface/web/admin/remote_user_del.php 11 ●●●● patch | view | raw | blame | history
interface/web/admin/remote_user_edit.php 16 ●●●● patch | view | raw | blame | history
interface/web/admin/remote_user_list.php 10 ●●●● patch | view | raw | blame | history
interface/web/admin/server_config_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/server_config_edit.php 44 ●●●● patch | view | raw | blame | history
interface/web/admin/server_config_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/server_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/server_edit.php 22 ●●●● patch | view | raw | blame | history
interface/web/admin/server_ip_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/server_ip_edit.php 7 ●●●●● patch | view | raw | blame | history
interface/web/admin/server_ip_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/server_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/server_php_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/server_php_edit.php 7 ●●●●● patch | view | raw | blame | history
interface/web/admin/server_php_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/software_package_del.php 8 ●●●● patch | view | raw | blame | history
interface/web/admin/software_package_edit.php 8 ●●●● patch | view | raw | blame | history
interface/web/admin/software_package_install.php 78 ●●●● patch | view | raw | blame | history
interface/web/admin/software_package_list.php 120 ●●●● patch | view | raw | blame | history
interface/web/admin/software_repo_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/software_repo_edit.php 8 ●●●● patch | view | raw | blame | history
interface/web/admin/software_repo_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/software_update_list.php 58 ●●●● patch | view | raw | blame | history
interface/web/admin/system_config_edit.php 122 ●●●● patch | view | raw | blame | history
interface/web/admin/tpl_default.php 36 ●●●● patch | view | raw | blame | history
interface/web/admin/users_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/admin/users_edit.php 34 ●●●● patch | view | raw | blame | history
interface/web/admin/users_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/capp.php 40 ●●●● patch | view | raw | blame | history
interface/web/client/client_circle_del.php 4 ●●●● patch | view | raw | blame | history
interface/web/client/client_circle_edit.php 4 ●●●● patch | view | raw | blame | history
interface/web/client/client_circle_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/client/client_del.php 137 ●●●● patch | view | raw | blame | history
interface/web/client/client_edit.php 392 ●●●● patch | view | raw | blame | history
interface/web/client/client_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/client/client_message.php 58 ●●●● patch | view | raw | blame | history
interface/web/client/client_template_del.php 17 ●●●● patch | view | raw | blame | history
interface/web/client/client_template_edit.php 17 ●●●● patch | view | raw | blame | history
interface/web/client/client_template_list.php 4 ●●●● patch | view | raw | blame | history
interface/web/client/domain_del.php 15 ●●●● patch | view | raw | blame | history
interface/web/client/domain_edit.php 11 ●●●● patch | view | raw | blame | history
interface/web/client/domain_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/client/domain_new_client.php 4 ●●●● patch | view | raw | blame | history
interface/web/client/form/client.tform.php 1690 ●●●● patch | view | raw | blame | history
interface/web/client/form/client_circle.tform.php 126 ●●●● patch | view | raw | blame | history
interface/web/client/form/client_template.tform.php 954 ●●●● patch | view | raw | blame | history
interface/web/client/form/domain.tform.php 84 ●●●● patch | view | raw | blame | history
interface/web/client/form/reseller.tform.php 1692 ●●●● patch | view | raw | blame | history
interface/web/client/lib/admin.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/client/lib/module.conf.php 100 ●●●● patch | view | raw | blame | history
interface/web/client/list/client.list.php 130 ●●●● patch | view | raw | blame | history
interface/web/client/list/client_circle.list.php 88 ●●●● patch | view | raw | blame | history
interface/web/client/list/client_template.list.php 68 ●●●● patch | view | raw | blame | history
interface/web/client/list/domain.list.php 70 ●●●● patch | view | raw | blame | history
interface/web/client/list/reseller.list.php 142 ●●●● patch | view | raw | blame | history
interface/web/client/reseller_del.php 33 ●●●● patch | view | raw | blame | history
interface/web/client/reseller_edit.php 115 ●●●● patch | view | raw | blame | history
interface/web/client/reseller_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/content.php 26 ●●●● patch | view | raw | blame | history
interface/web/dashboard/ajax_get_json.php 222 ●●●● patch | view | raw | blame | history
interface/web/dashboard/dashboard.php 50 ●●●● patch | view | raw | blame | history
interface/web/dashboard/dashlets/limits.php 188 ●●●● patch | view | raw | blame | history
interface/web/dashboard/dashlets/mailquota.php 43 ●●●● patch | view | raw | blame | history
interface/web/dashboard/dashlets/modules.php 31 ●●●● patch | view | raw | blame | history
interface/web/dashboard/dashlets/quota.php 55 ●●●● patch | view | raw | blame | history
interface/web/dashboard/lib/admin.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/dashboard/lib/custom_menu.inc.php 42 ●●●● patch | view | raw | blame | history
interface/web/dashboard/lib/module.conf.php 22 ●●●● patch | view | raw | blame | history
interface/web/designer/form_edit.php 70 ●●●● patch | view | raw | blame | history
interface/web/designer/form_list.php 44 ●●●● patch | view | raw | blame | history
interface/web/designer/form_show.php 46 ●●●● patch | view | raw | blame | history
interface/web/designer/index.php 1 ●●●● patch | view | raw | blame | history
interface/web/designer/lib/admin.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/designer/lib/module.conf.php 86 ●●●● patch | view | raw | blame | history
interface/web/designer/module_edit.php 92 ●●●● patch | view | raw | blame | history
interface/web/designer/module_list.php 34 ●●●● patch | view | raw | blame | history
interface/web/designer/module_nav_del.php 50 ●●●● patch | view | raw | blame | history
interface/web/designer/module_nav_edit.php 82 ●●●● patch | view | raw | blame | history
interface/web/designer/module_nav_flip.php 52 ●●●● patch | view | raw | blame | history
interface/web/designer/module_nav_item_del.php 52 ●●●● patch | view | raw | blame | history
interface/web/designer/module_nav_item_edit.php 82 ●●●● patch | view | raw | blame | history
interface/web/designer/module_nav_item_flip.php 54 ●●●● patch | view | raw | blame | history
interface/web/designer/module_show.php 44 ●●●● patch | view | raw | blame | history
interface/web/dns/ajax_get_json.php 76 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_a_edit.php 42 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_a_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_aaaa_edit.php 40 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_alias_edit.php 39 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_cname_edit.php 41 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_dkim_edit.php 27 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_dkim_get.php 111 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_hinfo_edit.php 39 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_import.php 406 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_mx_edit.php 55 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_ns_edit.php 39 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_ptr_edit.php 39 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_rp_edit.php 39 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_rr_del.php 9 ●●●●● patch | view | raw | blame | history
interface/web/dns/dns_slave_del.php 15 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_slave_edit.php 100 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_slave_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_soa_del.php 15 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_soa_edit.php 116 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_soa_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_srv_edit.php 7 ●●●●● patch | view | raw | blame | history
interface/web/dns/dns_template_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_template_edit.php 8 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_template_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_txt_edit.php 39 ●●●● patch | view | raw | blame | history
interface/web/dns/dns_wizard.php 116 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_a.tform.php 180 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_aaaa.tform.php 166 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_alias.tform.php 198 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_cname.tform.php 194 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_dkim.tform.php 172 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_hinfo.tform.php 178 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_mx.tform.php 210 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_ns.tform.php 194 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_ptr.tform.php 194 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_rp.tform.php 178 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_slave.tform.php 156 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_soa.tform.php 394 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_srv.tform.php 192 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_template.tform.php 96 ●●●● patch | view | raw | blame | history
interface/web/dns/form/dns_txt.tform.php 174 ●●●● patch | view | raw | blame | history
interface/web/dns/lib/admin.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/dns/lib/module.conf.php 68 ●●●● patch | view | raw | blame | history
interface/web/dns/lib/remote.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/dns/list/dns_a.list.php 176 ●●●● patch | view | raw | blame | history
interface/web/dns/list/dns_slave.list.php 104 ●●●● patch | view | raw | blame | history
interface/web/dns/list/dns_soa.list.php 128 ●●●● patch | view | raw | blame | history
interface/web/dns/list/dns_template.list.php 52 ●●●● patch | view | raw | blame | history
interface/web/help/faq_delete.php 6 ●●●● patch | view | raw | blame | history
interface/web/help/faq_edit.php 6 ●●●● patch | view | raw | blame | history
interface/web/help/faq_list.php 8 ●●●● patch | view | raw | blame | history
interface/web/help/faq_manage_questions_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/help/faq_sections_delete.php 6 ●●●● patch | view | raw | blame | history
interface/web/help/faq_sections_edit.php 6 ●●●● patch | view | raw | blame | history
interface/web/help/faq_sections_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/help/form/faq.tform.php 114 ●●●● patch | view | raw | blame | history
interface/web/help/form/faq_sections.tform.php 56 ●●●● patch | view | raw | blame | history
interface/web/help/form/support_message.tform.php 144 ●●●● patch | view | raw | blame | history
interface/web/help/index.php 2 ●●● patch | view | raw | blame | history
interface/web/help/lib/admin.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/help/lib/module.conf.php 74 ●●●● patch | view | raw | blame | history
interface/web/help/list/faq_list.php 2 ●●● patch | view | raw | blame | history
interface/web/help/list/faq_manage_questions_list.php 26 ●●●● patch | view | raw | blame | history
interface/web/help/list/faq_sections_list.php 2 ●●● patch | view | raw | blame | history
interface/web/help/list/support_message.list.php 82 ●●●● patch | view | raw | blame | history
interface/web/help/support_message_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/help/support_message_edit.php 58 ●●●● patch | view | raw | blame | history
interface/web/help/support_message_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/help/version.php 6 ●●●● patch | view | raw | blame | history
interface/web/index.php 38 ●●●● patch | view | raw | blame | history
interface/web/js/scrigo.js.php 97 ●●●● patch | view | raw | blame | history
interface/web/keepalive.php 6 ●●●● patch | view | raw | blame | history
interface/web/login/index.php 150 ●●●● patch | view | raw | blame | history
interface/web/login/lib/module.conf.php 10 ●●●● patch | view | raw | blame | history
interface/web/login/logout.php 12 ●●●● patch | view | raw | blame | history
interface/web/login/password_reset.php 34 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_alias.tform.php 142 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_aliasdomain.tform.php 140 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_blacklist.tform.php 106 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_content_filter.tform.php 114 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_domain.tform.php 166 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_domain_catchall.tform.php 142 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_forward.tform.php 130 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_get.tform.php 206 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_mailinglist.tform.php 166 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_relay_recipient.tform.php 98 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_spamfilter.tform.php 162 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_transport.tform.php 116 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_user.tform.php 424 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_user_filter.tform.php 142 ●●●● patch | view | raw | blame | history
interface/web/mail/form/mail_whitelist.tform.php 106 ●●●● patch | view | raw | blame | history
interface/web/mail/form/spamfilter_blacklist.tform.php 120 ●●●● patch | view | raw | blame | history
interface/web/mail/form/spamfilter_config.tform.php 380 ●●●● patch | view | raw | blame | history
interface/web/mail/form/spamfilter_policy.tform.php 500 ●●●● patch | view | raw | blame | history
interface/web/mail/form/spamfilter_users.tform.php 144 ●●●● patch | view | raw | blame | history
interface/web/mail/form/spamfilter_whitelist.tform.php 134 ●●●● patch | view | raw | blame | history
interface/web/mail/lib/admin.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/mail/lib/module.conf.php 232 ●●●● patch | view | raw | blame | history
interface/web/mail/lib/remote.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/mail/list/mail_alias.list.php 82 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_aliasdomain.list.php 82 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_blacklist.list.php 96 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_content_filter.list.php 96 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_domain.list.php 114 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_domain_catchall.list.php 82 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_forward.list.php 82 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_get.list.php 118 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_mailinglist.list.php 62 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_relay_recipient.list.php 80 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_spamfilter.list.php 80 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_transport.list.php 118 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_user.list.php 92 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_user_filter.list.php 38 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_user_stats.list.php 44 ●●●● patch | view | raw | blame | history
interface/web/mail/list/mail_whitelist.list.php 94 ●●●● patch | view | raw | blame | history
interface/web/mail/list/spamfilter_blacklist.list.php 122 ●●●● patch | view | raw | blame | history
interface/web/mail/list/spamfilter_config.list.php 38 ●●●● patch | view | raw | blame | history
interface/web/mail/list/spamfilter_policy.list.php 102 ●●●● patch | view | raw | blame | history
interface/web/mail/list/spamfilter_users.list.php 122 ●●●● patch | view | raw | blame | history
interface/web/mail/list/spamfilter_whitelist.list.php 122 ●●●● patch | view | raw | blame | history
interface/web/mail/list/user_quota_stats.list.php 70 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_alias_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_alias_edit.php 64 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_alias_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_aliasdomain_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_aliasdomain_edit.php 64 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_aliasdomain_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_blacklist_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_blacklist_edit.php 18 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_blacklist_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_content_filter_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_content_filter_edit.php 7 ●●●●● patch | view | raw | blame | history
interface/web/mail/mail_content_filter_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_domain_catchall_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_domain_catchall_edit.php 52 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_domain_catchall_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_domain_del.php 33 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_domain_dkim_create.php 146 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_domain_edit.php 58 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_domain_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_forward_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_forward_edit.php 54 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_forward_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_get_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_get_edit.php 34 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_get_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_mailinglist_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_mailinglist_edit.php 62 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_mailinglist_list.php 22 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_relay_recipient_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_relay_recipient_edit.php 8 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_relay_recipient_list.php 8 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_spamfilter_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_spamfilter_edit.php 52 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_spamfilter_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_transport_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_transport_edit.php 46 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_transport_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_user_del.php 27 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_user_edit.php 144 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_user_filter_del.php 18 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_user_filter_edit.php 92 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_user_list.php 32 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_user_stats.php 103 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_whitelist_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_whitelist_edit.php 18 ●●●● patch | view | raw | blame | history
interface/web/mail/mail_whitelist_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/mailinglist.php 12 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_blacklist_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_blacklist_edit.php 21 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_blacklist_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_config_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_config_edit.php 38 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_config_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_policy_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_policy_edit.php 17 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_policy_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_users_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_users_edit.php 19 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_users_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_whitelist_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_whitelist_edit.php 21 ●●●● patch | view | raw | blame | history
interface/web/mail/spamfilter_whitelist_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/mail/user_quota_stats.php 41 ●●●● patch | view | raw | blame | history
interface/web/mail/webmailer.php 12 ●●●● patch | view | raw | blame | history
interface/web/mailuser/form/mail_user_autoresponder.tform.php 86 ●●●● patch | view | raw | blame | history
interface/web/mailuser/form/mail_user_cc.tform.php 68 ●●●● patch | view | raw | blame | history
interface/web/mailuser/form/mail_user_filter.tform.php 134 ●●●● patch | view | raw | blame | history
interface/web/mailuser/form/mail_user_password.tform.php 46 ●●●● patch | view | raw | blame | history
interface/web/mailuser/form/mail_user_spamfilter.tform.php 44 ●●●● patch | view | raw | blame | history
interface/web/mailuser/index.php 20 ●●●● patch | view | raw | blame | history
interface/web/mailuser/lib/admin.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/mailuser/lib/module.conf.php 58 ●●●● patch | view | raw | blame | history
interface/web/mailuser/lib/remote.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/mailuser/list/mail_user_filter.list.php 38 ●●●● patch | view | raw | blame | history
interface/web/mailuser/mail_user_autoresponder_edit.php 36 ●●●● patch | view | raw | blame | history
interface/web/mailuser/mail_user_cc_edit.php 32 ●●●● patch | view | raw | blame | history
interface/web/mailuser/mail_user_filter_del.php 8 ●●●● patch | view | raw | blame | history
interface/web/mailuser/mail_user_filter_edit.php 32 ●●●● patch | view | raw | blame | history
interface/web/mailuser/mail_user_filter_list.php 8 ●●●● patch | view | raw | blame | history
interface/web/mailuser/mail_user_password_edit.php 20 ●●●● patch | view | raw | blame | history
interface/web/mailuser/mail_user_spamfilter_edit.php 44 ●●●● patch | view | raw | blame | history
interface/web/monitor/datalog_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/monitor/datalog_list.php 8 ●●●● patch | view | raw | blame | history
interface/web/monitor/lib/admin.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/monitor/lib/module.conf.php 266 ●●●● patch | view | raw | blame | history
interface/web/monitor/list/datalog.list.php 98 ●●●● patch | view | raw | blame | history
interface/web/monitor/list/log.list.php 98 ●●●● patch | view | raw | blame | history
interface/web/monitor/log_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/monitor/log_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/monitor/show_data.php 206 ●●●● patch | view | raw | blame | history
interface/web/monitor/show_log.php 130 ●●●● patch | view | raw | blame | history
interface/web/monitor/show_monit.php 14 ●●●● patch | view | raw | blame | history
interface/web/monitor/show_munin.php 14 ●●●● patch | view | raw | blame | history
interface/web/monitor/show_sys_state.php 468 ●●●● patch | view | raw | blame | history
interface/web/nav.php 30 ●●●● patch | view | raw | blame | history
interface/web/remote/index.php 6 ●●●● patch | view | raw | blame | history
interface/web/remote/json.php 6 ●●●● patch | view | raw | blame | history
interface/web/remote/monitor.php 140 ●●●● patch | view | raw | blame | history
interface/web/sites/ajax_get_ip.php 10 ●●●● patch | view | raw | blame | history
interface/web/sites/ajax_get_json.php 286 ●●●● patch | view | raw | blame | history
interface/web/sites/aps_availablepackages_list.php 8 ●●●● patch | view | raw | blame | history
interface/web/sites/aps_cron_apscrawler_if.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/aps_do_operation.php 126 ●●●● patch | view | raw | blame | history
interface/web/sites/aps_install_package.php 188 ●●●● patch | view | raw | blame | history
interface/web/sites/aps_installedpackages_list.php 106 ●●●● patch | view | raw | blame | history
interface/web/sites/aps_packagedetails_show.php 46 ●●●● patch | view | raw | blame | history
interface/web/sites/aps_update_packagelist.php 12 ●●●● patch | view | raw | blame | history
interface/web/sites/cron_del.php 11 ●●●● patch | view | raw | blame | history
interface/web/sites/cron_edit.php 200 ●●●● patch | view | raw | blame | history
interface/web/sites/cron_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/database_del.php 15 ●●●● patch | view | raw | blame | history
interface/web/sites/database_edit.php 236 ●●●● patch | view | raw | blame | history
interface/web/sites/database_list.php 22 ●●●● patch | view | raw | blame | history
interface/web/sites/database_phpmyadmin.php 22 ●●●● patch | view | raw | blame | history
interface/web/sites/database_user_del.php 55 ●●●● patch | view | raw | blame | history
interface/web/sites/database_user_edit.php 76 ●●●● patch | view | raw | blame | history
interface/web/sites/database_user_list.php 14 ●●●● patch | view | raw | blame | history
interface/web/sites/form/cron.tform.php 270 ●●●● patch | view | raw | blame | history
interface/web/sites/form/database.tform.php 214 ●●●● patch | view | raw | blame | history
interface/web/sites/form/database_user.tform.php 124 ●●●● patch | view | raw | blame | history
interface/web/sites/form/ftp_user.tform.php 388 ●●●● patch | view | raw | blame | history
interface/web/sites/form/shell_user.tform.php 278 ●●●● patch | view | raw | blame | history
interface/web/sites/form/web_aliasdomain.tform.php 228 ●●●● patch | view | raw | blame | history
interface/web/sites/form/web_domain.tform.php 1080 ●●●● patch | view | raw | blame | history
interface/web/sites/form/web_folder.tform.php 106 ●●●● patch | view | raw | blame | history
interface/web/sites/form/web_folder_user.tform.php 124 ●●●● patch | view | raw | blame | history
interface/web/sites/form/web_subdomain.tform.php 202 ●●●● patch | view | raw | blame | history
interface/web/sites/form/web_vhost_subdomain.tform.php 1072 ●●●● patch | view | raw | blame | history
interface/web/sites/form/webdav_user.tform.php 152 ●●●● patch | view | raw | blame | history
interface/web/sites/ftp_user_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/ftp_user_edit.php 81 ●●●● patch | view | raw | blame | history
interface/web/sites/ftp_user_list.php 24 ●●●● patch | view | raw | blame | history
interface/web/sites/lib/admin.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/sites/lib/module.conf.php 232 ●●●● patch | view | raw | blame | history
interface/web/sites/lib/remote.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/sites/list/aps_availablepackages.list.php 74 ●●●● patch | view | raw | blame | history
interface/web/sites/list/aps_installedpackages.list.php 64 ●●●● patch | view | raw | blame | history
interface/web/sites/list/cron.list.php 174 ●●●● patch | view | raw | blame | history
interface/web/sites/list/database.list.php 204 ●●●● patch | view | raw | blame | history
interface/web/sites/list/database_user.list.php 66 ●●●● patch | view | raw | blame | history
interface/web/sites/list/ftp_user.list.php 112 ●●●● patch | view | raw | blame | history
interface/web/sites/list/shell_user.list.php 112 ●●●● patch | view | raw | blame | history
interface/web/sites/list/user_quota_stats.list.php 60 ●●●● patch | view | raw | blame | history
interface/web/sites/list/web_aliasdomain.list.php 118 ●●●● patch | view | raw | blame | history
interface/web/sites/list/web_domain.list.php 132 ●●●● patch | view | raw | blame | history
interface/web/sites/list/web_folder.list.php 112 ●●●● patch | view | raw | blame | history
interface/web/sites/list/web_folder_user.list.php 86 ●●●● patch | view | raw | blame | history
interface/web/sites/list/web_sites_stats.list.php 44 ●●●● patch | view | raw | blame | history
interface/web/sites/list/web_subdomain.list.php 118 ●●●● patch | view | raw | blame | history
interface/web/sites/list/web_vhost_subdomain.list.php 118 ●●●● patch | view | raw | blame | history
interface/web/sites/list/webdav_user.list.php 106 ●●●● patch | view | raw | blame | history
interface/web/sites/shell_user_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/shell_user_edit.php 85 ●●●● patch | view | raw | blame | history
interface/web/sites/shell_user_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/user_quota_stats.php 43 ●●●● patch | view | raw | blame | history
interface/web/sites/web_aliasdomain_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/web_aliasdomain_edit.php 90 ●●●● patch | view | raw | blame | history
interface/web/sites/web_aliasdomain_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/web_domain_del.php 77 ●●●● patch | view | raw | blame | history
interface/web/sites/web_domain_edit.php 462 ●●●● patch | view | raw | blame | history
interface/web/sites/web_domain_list.php 8 ●●●● patch | view | raw | blame | history
interface/web/sites/web_folder_del.php 15 ●●●● patch | view | raw | blame | history
interface/web/sites/web_folder_edit.php 16 ●●●● patch | view | raw | blame | history
interface/web/sites/web_folder_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/web_folder_user_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/web_folder_user_edit.php 17 ●●●● patch | view | raw | blame | history
interface/web/sites/web_folder_user_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/web_sites_stats.php 141 ●●●● patch | view | raw | blame | history
interface/web/sites/web_subdomain_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/web_subdomain_edit.php 118 ●●●● patch | view | raw | blame | history
interface/web/sites/web_subdomain_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/web_vhost_subdomain_del.php 23 ●●●● patch | view | raw | blame | history
interface/web/sites/web_vhost_subdomain_edit.php 414 ●●●● patch | view | raw | blame | history
interface/web/sites/web_vhost_subdomain_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/webdav_user_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/sites/webdav_user_edit.php 25 ●●●● patch | view | raw | blame | history
interface/web/sites/webdav_user_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/tools/dns_import_tupa.php 66 ●●●● patch | view | raw | blame | history
interface/web/tools/form/interface_settings.tform.php 126 ●●●● patch | view | raw | blame | history
interface/web/tools/form/tpl_default.tform.php 166 ●●●● patch | view | raw | blame | history
interface/web/tools/form/user_settings.tform.php 112 ●●●● patch | view | raw | blame | history
interface/web/tools/import_ispconfig.php 134 ●●●● patch | view | raw | blame | history
interface/web/tools/import_plesk.php 2153 ●●●● patch | view | raw | blame | history
interface/web/tools/import_vpopmail.php 122 ●●●● patch | view | raw | blame | history
interface/web/tools/index.php 8 ●●●● patch | view | raw | blame | history
interface/web/tools/interface_settings.php 123 ●●●● patch | view | raw | blame | history
interface/web/tools/lib/interface.d/tpl_default.menu.php 4 ●●●● patch | view | raw | blame | history
interface/web/tools/lib/menu.d/import.menu.php 28 ●●●● patch | view | raw | blame | history
interface/web/tools/lib/menu.d/resync.menu.php 18 ●●●● patch | view | raw | blame | history
interface/web/tools/lib/menu.d/statistics.menu.php 2 ●●● patch | view | raw | blame | history
interface/web/tools/lib/module.conf.php 38 ●●●● patch | view | raw | blame | history
interface/web/tools/resync.php 40 ●●●● patch | view | raw | blame | history
interface/web/tools/tpl_default.php 6 ●●●● patch | view | raw | blame | history
interface/web/tools/user_settings.php 54 ●●●● patch | view | raw | blame | history
interface/web/vm/ajax_get_ip.php 10 ●●●● patch | view | raw | blame | history
interface/web/vm/form/openvz_ip.tform.php 116 ●●●● patch | view | raw | blame | history
interface/web/vm/form/openvz_ostemplate.tform.php 132 ●●●● patch | view | raw | blame | history
interface/web/vm/form/openvz_template.tform.php 680 ●●●● patch | view | raw | blame | history
interface/web/vm/form/openvz_vm.tform.php 454 ●●●● patch | view | raw | blame | history
interface/web/vm/lib/admin.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/vm/lib/module.conf.php 52 ●●●● patch | view | raw | blame | history
interface/web/vm/lib/remote.conf.php 2 ●●● patch | view | raw | blame | history
interface/web/vm/list/openvz_ip.list.php 110 ●●●● patch | view | raw | blame | history
interface/web/vm/list/openvz_ostemplate.list.php 112 ●●●● patch | view | raw | blame | history
interface/web/vm/list/openvz_template.list.php 54 ●●●● patch | view | raw | blame | history
interface/web/vm/list/openvz_vm.list.php 176 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_action.php 134 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_ip_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_ip_edit.php 8 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_ip_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_ostemplate_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_ostemplate_edit.php 8 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_ostemplate_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_template_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_template_edit.php 20 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_template_list.php 6 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_vm_del.php 6 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_vm_edit.php 58 ●●●● patch | view | raw | blame | history
interface/web/vm/openvz_vm_list.php 6 ●●●● patch | view | raw | blame | history
remoting_client/examples/client_add.php 144 ●●●● patch | view | raw | blame | history
remoting_client/examples/client_change_password.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/client_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/client_delete_everything.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/client_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/client_get_by_username.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/client_get_id.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/client_get_sites_by_user.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/client_templates_get_all.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/client_update.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_a_add.php 42 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_a_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_a_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_a_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_aaaa_add.php 42 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_aaaa_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_aaaa_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_aaaa_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_alias_add.php 42 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_alias_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_alias_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_alias_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_cname_add.php 42 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_cname_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_cname_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_cname_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_hinfo_add.php 42 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_hinfo_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_hinfo_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_hinfo_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_mx_add.php 42 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_mx_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_mx_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_mx_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_ns_add.php 42 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_ns_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_ns_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_ns_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_ptr_add.php 42 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_ptr_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_ptr_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_ptr_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_rp_add.php 42 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_rp_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_rp_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_rp_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_rr_get_all_by_zone.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_srv_add.php 42 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_srv_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_srv_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_srv_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_txt_add.php 42 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_txt_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_txt_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_txt_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_zone_add.php 50 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_zone_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_zone_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_zone_get_by_user.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_zone_set_status.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/dns_zone_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/domains_domain_add.php 24 ●●●● patch | view | raw | blame | history
remoting_client/examples/domains_domain_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/domains_domain_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/domains_get_all_by_user.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/get_function_list.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/login.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/logout.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_alias_add.php 32 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_alias_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_alias_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_alias_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_blacklist_add.php 32 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_blacklist_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_blacklist_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_blacklist_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_catchall_add.php 32 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_catchall_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_catchall_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_catchall_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_domain_add.php 28 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_domain_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_domain_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_domain_get_by_domain.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_domain_set_status.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_domain_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_fetchmail_add.php 40 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_fetchmail_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_fetchmail_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_fetchmail_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_filter_add.php 34 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_filter_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_filter_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_filter_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_forward_add.php 32 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_forward_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_forward_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_forward_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_mailinglist_add.php 32 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_mailinglist_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_mailinglist_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_mailinglist_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_policy_add.php 100 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_policy_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_policy_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_policy_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_spamfilter_blacklist_add.php 34 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_spamfilter_blacklist_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_spamfilter_blacklist_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_spamfilter_blacklist_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_spamfilter_user_add.php 34 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_spamfilter_user_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_spamfilter_user_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_spamfilter_user_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_spamfilter_whitelist_add.php 34 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_spamfilter_whitelist_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_spamfilter_whitelist_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_spamfilter_whitelist_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_transport_add.php 32 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_transport_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_transport_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_transport_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_user_add.php 68 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_user_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_user_filter_add.php 38 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_user_filter_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_user_filter_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_user_filter_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_user_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_user_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_whitelist_add.php 32 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_whitelist_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_whitelist_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/mail_whitelist_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_get_free_ip.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_ip_add.php 30 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_ip_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_ip_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_ip_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_ostemplate_add.php 34 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_ostemplate_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_ostemplate_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_ostemplate_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_template_add.php 98 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_template_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_template_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_template_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_vm_add.php 70 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_vm_add_from_template.php 22 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_vm_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_vm_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_vm_get_by_client.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/openvz_vm_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/server_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/server_get_serverid_by_ip.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_cron_add.php 46 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_cron_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_cron_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_cron_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_database_add.php 44 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_database_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_database_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_database_get_all_by_user.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_database_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_database_user_add.php 28 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_database_user_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_database_user_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_database_user_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_ftp_user_add.php 54 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_ftp_user_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_ftp_user_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_ftp_user_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_shell_user_add.php 48 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_shell_user_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_shell_user_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_shell_user_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_aliasdomain_add.php 106 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_aliasdomain_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_aliasdomain_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_aliasdomain_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_domain_add.php 104 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_domain_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_domain_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_domain_set_status.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_domain_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_subdomain_add.php 106 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_subdomain_delete.php 16 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_subdomain_get.php 20 ●●●● patch | view | raw | blame | history
remoting_client/examples/sites_web_subdomain_update.php 18 ●●●● patch | view | raw | blame | history
remoting_client/examples/soap-database-add.php 55 ●●●● patch | view | raw | blame | history
server/cron.php 56 ●●●● patch | view | raw | blame | history
server/cron_daily.php 2 ●●● patch | view | raw | blame | history
server/lib/app.inc.php 200 ●●●● patch | view | raw | blame | history
server/lib/classes/aps_base.inc.php 120 ●●●● patch | view | raw | blame | history
server/lib/classes/aps_installer.inc.php 1177 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-mailbox_stats.inc.php 406 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_clamav_log.inc.php 108 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_cpu.inc.php 94 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_database_size.inc.php 153 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_disk_usage.inc.php 136 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_email_quota.inc.php 114 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_fail2ban.inc.php 104 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_hd_quota.inc.php 92 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_iptables.inc.php 156 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_ispconfig_log.inc.php 115 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_ispconfig_version.inc.php 94 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_mail_log.inc.php 124 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_mail_queue.inc.php 96 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_mem_usage.inc.php 94 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_mongodb.inc.php 104 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_openvz.inc.php 110 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_os_version.inc.php 96 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_raid.inc.php 176 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_rkhunter.inc.php 94 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_server.inc.php 94 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_services.inc.php 92 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_syslog.inc.php 108 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/100-monitor_system_update.inc.php 96 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/150-awstats.inc.php 248 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/150-webalizer.inc.php 188 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/200-logfiles.inc.php 368 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/300-quota_notify.inc.php 718 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/400-openvz.inc.php 92 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.d/500-backup.inc.php 498 ●●●● patch | view | raw | blame | history
server/lib/classes/cron.inc.php 475 ●●●● patch | view | raw | blame | history
server/lib/classes/cronjob.inc.php 246 ●●●● patch | view | raw | blame | history
server/lib/classes/db_mysql.inc.php 964 ●●●● patch | view | raw | blame | history
server/lib/classes/file.inc.php 483 ●●●● patch | view | raw | blame | history
server/lib/classes/functions.inc.php 244 ●●●● patch | view | raw | blame | history
server/lib/classes/getconf.inc.php 9 ●●●●● patch | view | raw | blame | history
server/lib/classes/ini_parser.inc.php 10 ●●●● patch | view | raw | blame | history
server/lib/classes/libdatetime.inc.php 882 ●●●● patch | view | raw | blame | history
server/lib/classes/mod_mail_base.inc.php 44 ●●●● patch | view | raw | blame | history
server/lib/classes/modules.inc.php 152 ●●●● patch | view | raw | blame | history
server/lib/classes/monitor_tools.inc.php 340 ●●●● patch | view | raw | blame | history
server/lib/classes/openvz_tools.inc.php 8 ●●●● patch | view | raw | blame | history
server/lib/classes/plugins.inc.php 92 ●●●● patch | view | raw | blame | history
server/lib/classes/services.inc.php 35 ●●●● patch | view | raw | blame | history
server/lib/classes/system.inc.php 2085 ●●●● patch | view | raw | blame | history
server/lib/classes/tpl.inc.php 2506 ●●●● patch | view | raw | blame | history
server/lib/classes/tpl_cache.inc.php 287 ●●●● patch | view | raw | blame | history
server/lib/classes/tpl_error.inc.php 113 ●●●● patch | view | raw | blame | history
server/lib/classes/tpl_ini.inc.php 117 ●●●● patch | view | raw | blame | history
server/mods-available/client_module.inc.php 56 ●●●● patch | view | raw | blame | history
server/mods-available/cron_module.inc.php 56 ●●●● patch | view | raw | blame | history
server/mods-available/database_module.inc.php 78 ●●●● patch | view | raw | blame | history
server/mods-available/dns_module.inc.php 166 ●●●● patch | view | raw | blame | history
server/mods-available/mail_module.inc.php 166 ●●●● patch | view | raw | blame | history
server/mods-available/monitor_core_module.inc.php 10 ●●●●● patch | view | raw | blame | history
server/mods-available/remoteaction_core_module.inc.php 40 ●●●●● patch | view | raw | blame | history
server/mods-available/rescue_core_module.inc.php 20 ●●●● patch | view | raw | blame | history
server/mods-available/server_module.inc.php 106 ●●●● patch | view | raw | blame | history
server/mods-available/vm_module.inc.php 86 ●●●● patch | view | raw | blame | history
server/mods-available/web_module.inc.php 260 ●●●● patch | view | raw | blame | history
server/plugins-available/apache2_plugin.inc.php 2304 ●●●● patch | view | raw | blame | history
server/plugins-available/apps_vhost_plugin.inc.php 88 ●●●● patch | view | raw | blame | history
server/plugins-available/aps_plugin.inc.php 116 ●●●● patch | view | raw | blame | history
server/plugins-available/backup_plugin.inc.php 78 ●●●● patch | view | raw | blame | history
server/plugins-available/bind_dlz_plugin.inc.php 265 ●●●● patch | view | raw | blame | history
server/plugins-available/bind_plugin.inc.php 424 ●●●● patch | view | raw | blame | history
server/plugins-available/cron_jailkit_plugin.inc.php 390 ●●●● patch | view | raw | blame | history
server/plugins-available/cron_plugin.inc.php 305 ●●●● patch | view | raw | blame | history
server/plugins-available/firewall_plugin.inc.php 228 ●●●● patch | view | raw | blame | history
server/plugins-available/ftpuser_base_plugin.inc.php 146 ●●●● patch | view | raw | blame | history
server/plugins-available/getmail_plugin.inc.php 112 ●●●● patch | view | raw | blame | history
server/plugins-available/iptables_plugin.inc.php 68 ●●●● patch | view | raw | blame | history
server/plugins-available/mail_plugin.inc.php 206 ●●●● patch | view | raw | blame | history
server/plugins-available/mail_plugin_dkim.inc.php 318 ●●●● patch | view | raw | blame | history
server/plugins-available/maildeliver_plugin.inc.php 192 ●●●● patch | view | raw | blame | history
server/plugins-available/maildrop_plugin.inc.php 240 ●●●● patch | view | raw | blame | history
server/plugins-available/mailman_plugin.inc.php 82 ●●●● patch | view | raw | blame | history
server/plugins-available/mongo_clientdb_plugin.inc.php 139 ●●●● patch | view | raw | blame | history
server/plugins-available/mysql_clientdb_plugin.inc.php 783 ●●●● patch | view | raw | blame | history
server/plugins-available/network_settings_plugin.inc.php 204 ●●●● patch | view | raw | blame | history
server/plugins-available/nginx_plugin.inc.php 2094 ●●●● patch | view | raw | blame | history
server/plugins-available/nginx_reverseproxy_plugin.inc.php 214 ●●●● patch | view | raw | blame | history
server/plugins-available/openvz_plugin.inc.php 136 ●●●● patch | view | raw | blame | history
server/plugins-available/pma_symlink_plugin.inc.php 88 ●●●● patch | view | raw | blame | history
server/plugins-available/postfix_filter_plugin.inc.php 110 ●●●● patch | view | raw | blame | history
server/plugins-available/postfix_server_plugin.inc.php 60 ●●●● patch | view | raw | blame | history
server/plugins-available/powerdns_plugin.inc.php 310 ●●●● patch | view | raw | blame | history
server/plugins-available/shelluser_base_plugin.inc.php 176 ●●●● patch | view | raw | blame | history
server/plugins-available/shelluser_jailkit_plugin.inc.php 423 ●●●● patch | view | raw | blame | history
server/plugins-available/software_update_plugin.inc.php 218 ●●●● patch | view | raw | blame | history
server/plugins-available/squid_plugin.inc.php 132 ●●●● patch | view | raw | blame | history
server/plugins-available/webmail_symlink_plugin.inc.php 88 ●●●● patch | view | raw | blame | history
server/plugins-available/webserver_plugin.inc.php 191 ●●●● patch | view | raw | blame | history
server/scripts/ispconfig_update.php 76 ●●●● patch | view | raw | blame | history
server/server.php 42 ●●●● patch | view | raw | blame | history
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 ######################################################################################################
?>
//## ENDE Primärer NamerserverTEIL 2 ######################################################################################################
?>
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);
}
?>
?>
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 @@
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 @@
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]';");
}
?>
?>
helper_scripts/recreate_webalizer_stats.php
@@ -1,39 +1,39 @@
<?php
#######################################################################################################
//######################################################################################################
// Re-Create webalizer statistics
#######################################################################################################
//######################################################################################################
$sql = "SELECT domain_id, domain, document_root FROM web_domain WHERE server_id = ".$conf["server_id"];
$records = $app->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';
    $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");
    $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');
}
        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");
?>
?>
install/autoupdate.php
@@ -41,7 +41,7 @@
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 @@
 \___/\____/\_|      \____/\___/|_| |_|_| |_|\__, | \____/
                                              __/ |
                                             |___/ ";
    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 @@
//** 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->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 @@
}
//** 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 @@
checkDbHealth();
/*
 *  Prepare the dump of the database
 *  Prepare the dump of the database
*/
prepareDBDump();
@@ -196,7 +196,7 @@
    //** Configure postfix
    swriteln('Configuring Postfix');
    $inst->configure_postfix('dont-create-certs');
    //** Configure mailman
    swriteln('Configuring Mailman');
    $inst->configure_mailman('update');
@@ -217,7 +217,7 @@
        //** Configure PAM
        swriteln('Configuring PAM');
        $inst->configure_pam();
        //* Configure courier
        swriteln('Configuring Courier');
        $inst->configure_courier();
@@ -261,7 +261,7 @@
        //** Configure Apache
        swriteln('Configuring Apache');
        $inst->configure_apache();
        //** Configure vlogger
        swriteln('Configuring vlogger');
        $inst->configure_vlogger();
@@ -270,7 +270,7 @@
        swriteln('Configuring nginx');
        $inst->configure_nginx();
    }
    //** Configure apps vhost
    swriteln('Configuring Apps vhost');
    $inst->configure_apps_vhost();
install/dist/conf/centos52.conf.php
@@ -63,14 +63,14 @@
$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
install/dist/conf/centos53.conf.php
@@ -63,14 +63,14 @@
$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
install/dist/conf/debian40.conf.php
@@ -65,14 +65,14 @@
$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
install/dist/conf/debian60.conf.php
@@ -65,14 +65,14 @@
$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']['wget'] = '/usr/bin/wget';
?>
?>
install/dist/conf/fedora9.conf.php
@@ -63,14 +63,14 @@
$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
install/dist/conf/gentoo.conf.php
@@ -63,14 +63,14 @@
$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_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 @@
//* 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
install/dist/conf/opensuse110.conf.php
@@ -63,14 +63,14 @@
$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
install/dist/conf/opensuse112.conf.php
@@ -63,14 +63,14 @@
$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
install/dist/lib/centos52.lib.php
@@ -58,26 +58,26 @@
                }
            }
        }
        $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 @@
            $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 @@
    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);
    }
}
?>
?>
install/dist/lib/centos53.lib.php
@@ -58,26 +58,26 @@
                }
            }
        }
        $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 @@
            $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 @@
    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);
    }
}
?>
?>
install/dist/lib/debian40.lib.php
@@ -33,4 +33,4 @@
}
?>
?>
install/dist/lib/debian60.lib.php
@@ -29,13 +29,13 @@
*/
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 @@
        }
        $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 @@
            '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 @@
            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');
    */
    }
    }
}
?>
install/dist/lib/fedora.lib.php
@@ -58,7 +58,7 @@
                }
            }
        }
        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 @@
            $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,90 +87,90 @@
        $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');
    //* postfix-dkim
    $full_file_name=$config_dir.'/tag_as_originating.re';
    if(is_file($full_file_name)) {
        copy($full_file_name, $config_dir.$configfile.'~');
    }
    wf($full_file_name,'/^/ FILTER amavis:[127.0.0.1]:10026');
        //* postfix-dkim
        $full_file_name=$config_dir.'/tag_as_originating.re';
        if(is_file($full_file_name)) {
            copy($full_file_name, $config_dir.$configfile.'~');
        }
        wf($full_file_name, '/^/ FILTER amavis:[127.0.0.1]:10026');
    $full_file_name=$config_dir.'/tag_as_foreign.re';
    if(is_file($full_file_name)) {
        copy($full_file_name, $config_dir.$configfile.'~');
    }
    wf($full_file_name,'/^/ FILTER amavis:[127.0.0.1]:10024');
        $full_file_name=$config_dir.'/tag_as_foreign.re';
        if(is_file($full_file_name)) {
            copy($full_file_name, $config_dir.$configfile.'~');
        }
        wf($full_file_name, '/^/ FILTER amavis:[127.0.0.1]:10024');
        //* 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");
@@ -186,7 +186,7 @@
        //* 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;
            }
@@ -195,130 +195,130 @@
        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
@@ -336,68 +336,68 @@
        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 (
@@ -407,119 +407,119 @@
            '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';
@@ -531,40 +531,40 @@
        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);
@@ -574,45 +574,45 @@
        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 .= '/';
        }
@@ -624,37 +624,37 @@
        //* 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'");
@@ -666,7 +666,7 @@
                } 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,138 +677,138 @@
                }
            }
        }
        $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);
          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__);
        wf("/etc/Bastille/bastille-firewall.cfg", $content);
          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($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-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-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_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
@@ -816,68 +816,68 @@
            $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);
@@ -886,24 +886,24 @@
        $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 = '<?php' . "\n" . '$maxid_remote_action = 0;' . "\n" . '?>';
            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);
@@ -917,16 +917,16 @@
                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);
@@ -940,7 +940,7 @@
                closedir($dh);
            }
        }
        // Update the server config
        $mail_server_enabled = ($conf['services']['mail'])?1:0;
        $web_server_enabled = ($conf['services']['web'])?1:0;
@@ -949,14 +949,14 @@
        $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");
@@ -964,48 +964,48 @@
        //* 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!
@@ -1021,38 +1021,38 @@
            $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 {
@@ -1063,39 +1063,39 @@
            } 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'];
@@ -1104,7 +1104,7 @@
            // 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);
@@ -1114,19 +1114,19 @@
                $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');
@@ -1142,18 +1142,18 @@
            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');
@@ -1164,98 +1164,98 @@
        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";
@@ -1264,22 +1264,22 @@
        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";
@@ -1289,7 +1289,7 @@
            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');
    }
install/dist/lib/fedora9.lib.php
@@ -33,4 +33,4 @@
}
?>
?>
install/dist/lib/gentoo.lib.php
@@ -28,47 +28,47 @@
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,81 +77,81 @@
        $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");
@@ -161,127 +161,127 @@
        $full_file_name=$config_dir.'/tag_as_originating.re';
        if(is_file($full_file_name)) {
            copy($full_file_name, $config_dir.$configfile.'~');
            }
            $this->write_config_file($full_file_name,'/^/ FILTER amavis:[127.0.0.1]:10026');
        }
        $this->write_config_file($full_file_name, '/^/ FILTER amavis:[127.0.0.1]:10026');
            $full_file_name=$config_dir.'/tag_as_foreign.re';
            if(is_file($full_file_name)) {
                    copy($full_file_name, $config_dir.$configfile.'~');
            }
        $this->write_config_file($full_file_name,'/^/ FILTER amavis:[127.0.0.1]:10024');
        $full_file_name=$config_dir.'/tag_as_foreign.re';
        if(is_file($full_file_name)) {
            copy($full_file_name, $config_dir.$configfile.'~');
        }
        $this->write_config_file($full_file_name, '/^/ FILTER amavis:[127.0.0.1]:10024');
        //* 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));
        }
@@ -290,86 +290,86 @@
        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
@@ -377,45 +377,47 @@
         * -E noanonymous
         * -O altlog <format>:<log file>
         * -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
@@ -423,26 +425,26 @@
            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 {
@@ -450,48 +452,48 @@
            }
        }
    }
    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('/<VirtualHost[^>]+>/', '<VirtualHost *:80>', $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");
@@ -502,76 +504,76 @@
                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 {
@@ -579,41 +581,41 @@
            }
            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){
@@ -646,15 +648,15 @@
            // 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']);
@@ -668,7 +670,7 @@
            $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');
@@ -683,84 +685,84 @@
            //* 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 = '<?php' . "\n" . '$maxid_remote_action = 0;' . "\n" . '?>';
            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)) {
@@ -787,11 +789,11 @@
                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);
                            }
@@ -807,7 +809,7 @@
                closedir($dh);
            }
        }
        //* Update the server config
        $mail_server_enabled = ($conf['services']['mail'])?1:0;
        $web_server_enabled = ($conf['services']['web'])?1:0;
@@ -815,16 +817,16 @@
        $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");
@@ -832,40 +834,40 @@
        //* 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');
@@ -880,12 +882,12 @@
            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!
@@ -905,23 +907,23 @@
                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 {
@@ -932,10 +934,10 @@
            } 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);
@@ -944,7 +946,7 @@
                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');
            }
        }
@@ -957,7 +959,7 @@
            // 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);
@@ -967,19 +969,19 @@
                $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');
@@ -995,31 +997,31 @@
            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');
@@ -1033,7 +1035,7 @@
        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']);
@@ -1041,25 +1043,26 @@
        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');
    }
    }
}
?>
install/dist/lib/opensuse.lib.php
@@ -58,7 +58,7 @@
                }
            }
        }
        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 @@
            $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,91 +87,91 @@
        $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');
    //* postfix-dkim
    $full_file_name=$config_dir.'/tag_as_originating.re';
    if(is_file($full_file_name)) {
        copy($full_file_name, $config_dir.$configfile.'~');
    }
    wf($full_file_name,'/^/ FILTER amavis:[127.0.0.1]:10026');
        //* postfix-dkim
        $full_file_name=$config_dir.'/tag_as_originating.re';
        if(is_file($full_file_name)) {
            copy($full_file_name, $config_dir.$configfile.'~');
        }
        wf($full_file_name, '/^/ FILTER amavis:[127.0.0.1]:10026');
    $full_file_name=$config_dir.'/tag_as_foreign.re';
    if(is_file($full_file_name)) {
        copy($full_file_name, $config_dir.$configfile.'~');
    }
    wf($full_file_name,'/^/ FILTER amavis:[127.0.0.1]:10024');
        $full_file_name=$config_dir.'/tag_as_foreign.re';
        if(is_file($full_file_name)) {
            copy($full_file_name, $config_dir.$configfile.'~');
        }
        wf($full_file_name, '/^/ FILTER amavis:[127.0.0.1]:10024');
        //* 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'];
@@ -180,7 +180,7 @@
            $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");
@@ -188,9 +188,9 @@
            $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']));
@@ -199,40 +199,40 @@
        //* 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');
@@ -241,78 +241,78 @@
        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
        //* 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~');
@@ -324,14 +324,14 @@
        $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.'~');
@@ -341,22 +341,22 @@
        $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
@@ -374,65 +374,65 @@
        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 (
@@ -442,115 +442,115 @@
            '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';
@@ -562,40 +562,40 @@
        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);
@@ -605,69 +605,69 @@
        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<Directory /srv/www>\n    Options FollowSymlinks\n</Directory>\n\nInclude /etc/apache2/sites-enabled/\n\n");
        if(!stristr($content, 'Include /etc/apache2/sites-enabled/')) {
            af('/etc/apache2/httpd.conf', "\n<Directory /srv/www>\n    Options FollowSymlinks\n</Directory>\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'");
@@ -679,7 +679,7 @@
                } 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);
@@ -690,37 +690,37 @@
                }
            }
        }
        $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'])){
@@ -732,34 +732,34 @@
                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'])){
@@ -775,95 +775,95 @@
        //* 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);
          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__);
        wf("/etc/Bastille/bastille-firewall.cfg", $content);
          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($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-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-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_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
@@ -871,93 +871,93 @@
            $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~");
        }
        $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/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/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_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~");
        }
        $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 = '<?php' . "\n" . '$maxid_remote_action = 0;' . "\n" . '?>';
            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);
@@ -971,16 +971,16 @@
                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);
@@ -994,7 +994,7 @@
                closedir($dh);
            }
        }
        // Update the server config
        $mail_server_enabled = ($conf['services']['mail'])?1:0;
        $web_server_enabled = ($conf['services']['web'])?1:0;
@@ -1003,14 +1003,14 @@
        $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");
@@ -1018,48 +1018,48 @@
        //* 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!
@@ -1079,31 +1079,31 @@
                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 {
@@ -1114,23 +1114,23 @@
            } 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) {
@@ -1138,11 +1138,11 @@
                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 <tmpl_var name='system_user'> <tmpl_var name='system_group'>",0);
            replaceLine('/usr/local/ispconfig/server/conf/vhost.conf.master', "suPHP_UserGroup", "        suPHP_UserGroup <tmpl_var name='system_user'> <tmpl_var name='system_group'>", 0);
        }
        if($conf['nginx']['installed'] == true && $this->install_ispconfig_interface == true){
@@ -1153,7 +1153,7 @@
            // 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);
@@ -1163,19 +1163,19 @@
                $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');
@@ -1191,20 +1191,20 @@
            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');
@@ -1215,96 +1215,96 @@
        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";
@@ -1313,22 +1313,22 @@
        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";
@@ -1338,7 +1338,7 @@
            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');
    }
install/dist/lib/opensuse110.lib.php
@@ -33,4 +33,4 @@
}
?>
?>
install/dist/lib/opensuse112.lib.php
@@ -33,4 +33,4 @@
}
?>
?>
install/install.php
@@ -37,7 +37,7 @@
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 "\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 @@
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 @@
//** 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 @@
$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['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 @@
    $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 @@
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 @@
        //* Configure PAM
        swriteln('Configuring PAM');
        $inst->configure_pam();
        //* Configure Courier
        swriteln('Configuring Courier');
        $inst->configure_courier();
@@ -222,7 +222,7 @@
    //* Configure Getmail
    swriteln('Configuring Getmail');
    $inst->configure_getmail();
    //* Configure Pureftpd
    swriteln('Configuring Pureftpd');
    $inst->configure_pureftpd();
@@ -238,29 +238,29 @@
        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
    if($conf['ufw']['installed'] == true) {
    if($conf['ufw']['installed'] == true) {
        //* Configure Ubuntu Firewall
        $conf['services']['firewall'] = true;
        swriteln('Configuring Ubuntu Firewall');
@@ -272,12 +272,12 @@
        $inst->configure_bastille_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;
@@ -289,22 +289,22 @@
        $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();
@@ -312,7 +312,7 @@
    //* 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'));
@@ -338,10 +338,10 @@
    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'] != '') system($inst->getinitcommand($conf['ufw']['init_script'], 'restart').' &> /dev/null');
    //* In expert mode, we select the services in the following steps, only db is always available
    $conf['services']['mail'] = false;
    $conf['services']['web'] = false;
@@ -349,23 +349,23 @@
    $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;
@@ -378,7 +378,7 @@
            }
        } while ($finished == false);
        unset($finished);
        // initialize the connection to the master database
        $inst->dbmaster = new db();
        if($inst->dbmaster->linkId) $inst->dbmaster->closeConn();
@@ -386,39 +386,39 @@
        $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();
@@ -428,15 +428,15 @@
            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();
@@ -453,7 +453,7 @@
        //* 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'));
@@ -468,22 +468,22 @@
        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) {
@@ -499,12 +499,12 @@
            $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');
@@ -518,45 +518,45 @@
        }
    }
    */
    //** 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['ufw']['installed'] == true) {
            //* Configure Ubuntu Firewall
            $conf['services']['firewall'] = true;
@@ -569,18 +569,18 @@
            $inst->configure_bastille_firewall();
        }
    }
    //** 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 ?
        /*
@@ -600,23 +600,23 @@
        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();
@@ -626,9 +626,9 @@
        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
install/lib/install.lib.php
@@ -79,66 +79,66 @@
            $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 @@
            $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 @@
    //** 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 @@
        $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 @@
        $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 sread() {
        $input = fgets(STDIN);
        return rtrim($input);
    $input = fgets(STDIN);
    return rtrim($input);
}
function swrite($text = '') {
@@ -288,7 +288,7 @@
}
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 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 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 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 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 @@
            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 @@
    }
    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 @@
    $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 @@
        $content .= "[$section]\n";
        foreach($data as $item => $value) {
            if($item != ''){
                                $content .= "$item=$value\n";
                        }
                $content .= "$item=$value\n";
            }
        }
        $content .= "\n";
    }
@@ -617,13 +617,13 @@
    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 @@
        }
        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 @@
                }
            }
        }
        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 @@
 * 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 @@
    $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 @@
    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 @@
    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 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;
    $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 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');
    }
    $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) {
        exec('date +%Z', $tzinfo);
        $timezone = $tzinfo[0];
    }
    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');
    }
    return $timezone;
    if(!$timezone) {
        exec('date +%Z', $tzinfo);
        $timezone = $tzinfo[0];
    }
    return $timezone;
}
install/lib/installer_base.lib.php
@@ -53,7 +53,7 @@
    }
    public function warning($msg) {
        echo('WARNING: '.$msg."\n");
        echo 'WARNING: '.$msg."\n";
    }
    public function simple_query($query, $answers, $default) {
@@ -86,7 +86,7 @@
        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 @@
    }
    /** Create the database for ISPConfig */
    public function configure_database() {
        global $conf;
@@ -159,10 +161,10 @@
        } 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 @@
        //* 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 @@
        }
        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 ($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
                }
                /*
             *  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){
                    echo "\n\n" . $query ."\n";
                }
                $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);
                }
                $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`) 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 (`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, 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, 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, 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);
                }
            }
            /*
             *  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){
                    echo "\n\n" . $query ."\n";
            }
            $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);
            }
            $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`) 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 (`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, 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, 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, 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 @@
        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 @@
            $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 @@
        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,18 +669,18 @@
        //* postfix-dkim
        $full_file_name=$config_dir.'/tag_as_originating.re';
                if(is_file($full_file_name)) copy($full_file_name, $config_dir.$configfile.'~');
        wf($full_file_name,'/^/ FILTER amavis:[127.0.0.1]:10026');
        if(is_file($full_file_name)) copy($full_file_name, $config_dir.$configfile.'~');
        wf($full_file_name, '/^/ FILTER amavis:[127.0.0.1]:10026');
        $full_file_name=$config_dir.'/tag_as_foreign.re';
                if(is_file($full_file_name)) copy($full_file_name, $config_dir.$configfile.'~');
        wf($full_file_name,'/^/ FILTER amavis:[127.0.0.1]:10024');
        if(is_file($full_file_name)) copy($full_file_name, $config_dir.$configfile.'~');
        wf($full_file_name, '/^/ FILTER amavis:[127.0.0.1]:10024');
        //* 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'];
@@ -695,31 +697,31 @@
        //* 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
@@ -746,10 +748,10 @@
            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';
@@ -770,8 +772,8 @@
        $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
@@ -802,8 +804,8 @@
        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);
@@ -816,14 +818,14 @@
            $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
@@ -833,21 +835,21 @@
        // 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');
@@ -887,10 +889,10 @@
        }
        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);
@@ -924,9 +926,9 @@
        }
        $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);
@@ -935,14 +937,14 @@
        //* 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) {
@@ -957,25 +959,25 @@
        }
        //* 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
@@ -985,10 +987,10 @@
        }
        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);
@@ -1002,15 +1004,15 @@
        // 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
@@ -1026,7 +1028,7 @@
        }
        // 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) {
@@ -1035,13 +1037,13 @@
        }
        // 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);
@@ -1049,17 +1051,17 @@
        exec('adduser clamav amavis');
        // Create the director for DKIM-Keys
        mkdir("/var/lib/amavis/dkim",0750);
        mkdir("/var/lib/amavis/dkim", 0750);
        // get shell-user for amavis
        $amavis_user=exec('grep -o "^amavis:\|^vscan:" /etc/passwd');
        if(!empty($amavis_user)) {
            $amavis_user=rtrim($amavis_user,":");
            $amavis_user=rtrim($amavis_user, ":");
            exec('chown '.$amavis_user.'/var/lib/amavis/dkim');
        }
        // get shell-group for amavis
        $amavis_group=exec('grep -o "^amavis:\|^vscan:" /etc/group');
        if(!empty($amavis_group)) {
            $amavis_group=rtrim($amavis_group,":");
            $amavis_group=rtrim($amavis_group, ":");
            exec('chgrp '.$amavis_group.'/var/lib/amavis/dkim');
        }
    }
@@ -1125,12 +1127,12 @@
        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');
        }
@@ -1143,15 +1145,15 @@
        // 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');
@@ -1178,22 +1180,22 @@
        //* 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');
@@ -1204,19 +1206,19 @@
    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']);
    }
@@ -1230,19 +1232,19 @@
        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','<VirtualHost *>','<VirtualHost *:80>',1,0);
            replaceLine('/etc/apache2/sites-available/000-default', 'NameVirtualHost *', 'NameVirtualHost *:80', 1, 0);
            replaceLine('/etc/apache2/sites-available/000-default', '<VirtualHost *>', '<VirtualHost *:80>', 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);
        }
@@ -1262,7 +1264,7 @@
                } 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);
@@ -1275,29 +1277,29 @@
        }
        $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';
@@ -1315,20 +1317,20 @@
        //* 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';
@@ -1366,8 +1368,8 @@
    }
    public function configure_fail2ban() {
        // To Do
    }
        // To Do
    }
    public function configure_squid()
    {
@@ -1377,13 +1379,13 @@
        $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);
    }
@@ -1391,9 +1393,9 @@
    public function configure_ufw_firewall()
    {
        $configfile = 'ufw.conf';
        if(is_file('/etc/ufw/ufw.conf')) copy('/etc/ufw/ufw.conf','/etc/ufw/ufw.conf~');
        if(is_file('/etc/ufw/ufw.conf')) copy('/etc/ufw/ufw.conf', '/etc/ufw/ufw.conf~');
        $content = rf("tpl/".$configfile.".master");
        wf('/etc/ufw/ufw.conf',$content);
        wf('/etc/ufw/ufw.conf', $content);
        exec('chmod 600 /etc/ufw/ufw.conf');
        exec('chown root:root /etc/ufw/ufw.conf');
    }
@@ -1408,10 +1410,10 @@
        @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);
@@ -1422,8 +1424,8 @@
        $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';
@@ -1467,21 +1469,21 @@
        //** 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');
@@ -1543,7 +1545,7 @@
            //* 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')) {
@@ -1556,7 +1558,7 @@
                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']);
@@ -1596,7 +1598,7 @@
            }
            $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']);
@@ -1608,7 +1610,7 @@
            //$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 = '';
@@ -1635,7 +1637,7 @@
            //* 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');
            }
        }
@@ -1652,13 +1654,13 @@
        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);
    }
@@ -1700,7 +1702,7 @@
        }
        $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);
@@ -1756,9 +1758,9 @@
        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)) {
@@ -1785,11 +1787,11 @@
                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);
@@ -1844,14 +1846,14 @@
        //* 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);
                        }
                    }
                }
@@ -1866,7 +1868,7 @@
        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');
@@ -1945,18 +1947,18 @@
            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');
            //}
        }
@@ -1980,7 +1982,7 @@
            }
            $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';
@@ -2006,7 +2008,7 @@
            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');
                }
            }
        }
@@ -2019,8 +2021,8 @@
        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');
@@ -2044,7 +2046,7 @@
        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);
        }
@@ -2072,11 +2074,11 @@
            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() {
@@ -2094,10 +2096,10 @@
        }
        $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');
@@ -2115,12 +2117,12 @@
        // 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) {
@@ -2143,12 +2145,12 @@
            $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) {
@@ -2165,7 +2167,7 @@
        chmod($conf['ispconfig_log_dir'].'/cron.log', 0660);
    }
    public function getinitcommand($servicename, $action, $init_script_directory = ''){
        global $conf;
        // systemd
@@ -2202,17 +2204,17 @@
        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;
@@ -2250,21 +2252,21 @@
        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;
            }
        }
@@ -2293,11 +2295,12 @@
        $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;
    }
}
?>
install/lib/mysql.lib.php
@@ -30,25 +30,25 @@
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 @@
        $this->errorLocation = $location;
        if($this->errorNumber && $this->show_error_messages)
        {
            echo('<br /><b>'.$this->errorLocation.'</b><br />'.$this->errorMessage);
            echo '<br /><b>'.$this->errorLocation.'</b><br />'.$this->errorMessage;
            flush();
        }
    }
@@ -138,7 +138,7 @@
    // 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()<br />mysqli_fetch_array');
        if(!$this->record || !is_array($this->record))
        {
@@ -153,37 +153,37 @@
    {
        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,116 +191,64 @@
                $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."<br><br>";
           $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."<br><br>";
           $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
                    type =>     42go-Meta-Type: int16, int32, int64, double, char, varchar, text, blob
                    typeValue => Wert z.B. bei Varchar
                    defaultValue =>  Default Wert
                    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 insert($tablename, $form, $debug = 0)
    {
        if(is_array($form)){
            foreach($form as $key => $value)
            {
                $sql_key .= "$key, ";
                $sql_value .= "'".$this->check($value)."', ";
            }
        } elseif($col["defaultValue"] != false) {
            $sql .= "DEFAULT '' ";
            $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."<br><br>";
            $this->query($sql);
            if($debug == 1) echo "mySQL Error Message: ".$this->errorMessage;
        }
        if($col["defaultValue"] != "NULL" && $col["defaultValue"] != "NOT NULL") {
            if($col["notNull"] == true) {
                $sql .= "NOT NULL ";
            } else {
                $sql .= "NULL ";
            }
    }
    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."<br><br>";
            $this->query($sql);
            if($debug == 1) echo "mySQL Error Message: ".$this->errorMessage;
        }
        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 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
@@ -310,56 +258,108 @@
                    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 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 '' ";
            }
            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"]."),";
        }
        $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
                    type =>     42go-Meta-Type: int16, int32, int64, double, char, varchar, text, blob
                    typeValue => Wert z.B. bei Varchar
                    defaultValue =>  Default Wert
                    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 = '') {
        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 @@
                $tb_names[$i] = $tables[$i]['Tables_in_'.$database_name];
            }
        }
        /*
        $result = mysqli_query("SHOW TABLES FROM `$database_name`");
        $tb_names = array();
@@ -375,11 +375,11 @@
            $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 @@
                    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;
        }
    }
}
?>
install/lib/update.lib.php
@@ -29,10 +29,12 @@
//* 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 @@
    } 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 @@
        sread();
    }
    else
      echo "OK\n";
        echo "OK\n";
}
function updateDbAndIni() {
@@ -136,9 +138,9 @@
    $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 @@
        $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 @@
                    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 @@
        } 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 @@
                $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 @@
    $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 @@
    $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 @@
    $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 @@
    $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);
install/patches/upd_0001.php
@@ -1,6 +1,6 @@
<?php
if(!defined('INSTALLER_RUN')) die('Patch update file access violation.');
if(!defined('INSTALLER_RUN')) die('Patch update file access violation.');
/*
    Example installer patch update class. the classname must match
@@ -10,12 +10,14 @@
class upd_0001 extends installer_patch_update {
   public function onBeforeSQL() {
     // Do something
   }
   public function onAfterSQL() {
     // Do something
   }
    public function onBeforeSQL() {
        // Do something
    }
    public function onAfterSQL() {
        // Do something
    }
}
?>
install/setrights.php
@@ -34,7 +34,7 @@
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 "\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 @@
//** 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 @@
/*
 * 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 @@
$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();
install/uninstall-fedora.php
@@ -35,7 +35,7 @@
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 "\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"]."'");
install/uninstall.php
@@ -35,7 +35,7 @@
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 "\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"]."'");
install/update.php
@@ -37,7 +37,7 @@
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 "\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 @@
//** 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 @@
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 @@
unset($finished);
/*
 *  Prepare the dump of the database
 *  Prepare the dump of the database
 */
prepareDBDump();
@@ -192,34 +192,34 @@
//* 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 @@
 * 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 @@
            //** 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 @@
        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 @@
            $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 @@
            swriteln('Configuring nginx');
            $inst->configure_nginx();
        }
        //** Configure apps vhost
        swriteln('Configuring Apps vhost');
        $inst->configure_apps_vhost();
@@ -342,7 +342,7 @@
    swriteln('Configuring Database');
    $inst->configure_dbserver();
    if($conf['services']['firewall']) {
        if($conf['ufw']['installed'] == true) {
            //* Configure Ubuntu Firewall
@@ -355,7 +355,7 @@
            $inst->configure_bastille_firewall();
        }
    }
    /*
    if($conf['squid']['installed'] == true) {
        swriteln('Configuring Squid');
@@ -384,10 +384,10 @@
    } 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();
    }
}
@@ -395,7 +395,7 @@
$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();
@@ -434,14 +434,14 @@
        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');
    }
}
interface/lib/app.inc.php
@@ -64,15 +64,15 @@
        //* 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 @@
            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 @@
                $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 @@
        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 @@
    //** 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 @@
        $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 @@
            $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'));
interface/lib/classes/aps_base.inc.php
@@ -43,61 +43,69 @@
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
    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;
    }
    /**
     * 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;
    }
}
?>
?>
interface/lib/classes/aps_crawler.inc.php
@@ -27,264 +27,277 @@
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();
    //public $app_download_url_list = 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);
    /**
     * Constructor
     *
     * @param $app the application instance (db handle + log method)
     * @param $interface_mode act in interface (true) or server mode (false)
     */
        // 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);
    public function __construct($app, $interface_mode = false)
    {
        parent::__construct($app, 'APS crawler: ', $interface_mode);
    }
        // 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("/\<a href=\"(.+)\/\" class=\"vendor\"/i", $vendor_page, $matches);
            $vendors = array_map('urldecode', $matches[1]);
            if(!$vendors) throw new Exception('Unable to fetch vendors. Aborting');
    /**
     * 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;
            // Format all vendors for further processing (i.e. typo3.org -> /1.atom?vendor=typo3.org&pageSize=100
            //array_walk($vendors, array($this, 'formatVendorCallback'));
        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("/\<a href=\"(.+)\/\" class=\"vendor\"/i", $vendor_page, $matches);
            $vendors = array_map('urldecode', $matches[1]);
            if(!$vendors) throw new Exception('Unable to fetch vendors. Aborting');
            // Format all vendors for further processing (i.e. typo3.org -> /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], '<opensearch:totalResults>0</opensearch:totalResults>');
                    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], '<opensearch:totalResults>0</opensearch:totalResults>');
                    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 @@
                                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++;
                        $new_ver = $app_version.'-'.$app_release;
                        $local_intf_folder = $this->interface_pkg_dir.'/'.$app_name.'-'.$new_ver.'.app.zip/';
                            $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");
                        // 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;
                            // 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);
                            // 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 @@
                    }
                }
            }
        }
        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;
        }
    }
}
?>
?>
interface/lib/classes/aps_guicontroller.inc.php
@@ -27,199 +27,215 @@
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);
    /**
     * Constructor
     *
     * @param $app the application instance (db handle)
     */
        // 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
    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).")
            ORDER BY REPLACE(version, '.', '')+0 DESC, `release` DESC");
        if(!empty($result) && ($id != $result['id'])) return $result['id'];
        return 0;
    }
        // 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'];
    /**
     * 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';
        return $webserver_id;
    }
         $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)
    {
    /**
     * 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)
    {
        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 @@
                $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 @@
                $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 @@
                $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);
            }
        }
    /**
     * Read the settings to be filled when installing
     *
     * @param $id the internal ID of the package
     * @return array
     */
    public function getPackageSettings($id)
    {
        global $app;
        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
        $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']);
                        // The location might be empty but the DB return must not be false!
                        if($location_for_domain) $used_path .= $location_for_domain['value'];
                    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);
                        if($new_path == $used_path)
                        {
                            $temp_errstr = $app->lng('error_used_location');
                            break;
                        }
                    }
                }
            }
            else $temp_errstr = $app->lng('error_main_domain');
        $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);
            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['Screenshots'][] = array('ScreenPath' => $path,
                    'ScreenDescription' => htmlspecialchars(trim((string)$screen->description)));
            }
        }
        else $pkg['Screenshots'] = ''; // if no screenshots are available, set the variable though
                $pkg['Changelog'][] = array('ChangelogVersion' => (string)$change['version'],
                                            'ChangelogDescription' => implode('<br />', $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));
        // 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));
        $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['Changelog'][] = array('ChangelogVersion' => (string)$change['version'],
                    'ChangelogDescription' => implode('<br />', $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;
    }
}
?>
interface/lib/classes/auth.inc.php
@@ -35,18 +35,18 @@
    {
        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 @@
            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 @@
    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 @@
            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);
    }
}
?>
?>
interface/lib/classes/client_templates.inc.php
@@ -1,236 +1,239 @@
<?php
/**
 * client_templates
 *
 *
 * @author Marius Cramer <m.cramer@pixcept.de> 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);
        $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;
                        /* 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();
                                }
                            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;
                            }
                        }
                    }
                }
            }
        }
                                $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);
    }
}
        $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);
    }
}
interface/lib/classes/cmstree.inc.php
@@ -48,13 +48,13 @@
    // - 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 @@
                $$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 @@
        if(is_array($myobj->childs) and ($_SESSION['s']['cat_open'][$id] == 1 or $tiefe <= 1)) {
            foreach($myobj->childs as $val) {
                // kategorie         => str_repeat('- &nbsp;',$tiefe) . $val->btext,
                // Ergebnisse Formatieren
                /*
                if($tiefe == 0) {
@@ -104,7 +104,7 @@
                } else {
                    $kategorie = "<div class='mnuLevel".$tiefe."'>&nbsp; <a href='treenavi.php?kat=".$val->id."' class='navtext' onclick=\"parent.content.location='media_list.php?search_media_cat_id=".$val->id."'\" style=\"text-decoration: none;\"><img src='../themes/default/icons/folder_closed.png' border='0'> ".$val->btext."</a></div>";
                }
                $optionlist[] = array(     media_cat         => $kategorie,
                                           media_cat_id     => $val->id,
                                        depth            => $tiefe);
@@ -114,4 +114,4 @@
    }
}
?>
?>
interface/lib/classes/custom_datasource.inc.php
@@ -29,7 +29,7 @@
*/
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 @@
        }
        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 @@
        }
        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 @@
        }
        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 @@
        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 @@
        }
        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 @@
                $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 @@
        }
        return $records_new;
    }
}
?>
?>
interface/lib/classes/db_firebird.inc.php
@@ -29,17 +29,17 @@
*/
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 @@
    // constructor
    function __construct()
    {
        global $conf;
        $this->dbHost = $conf["db_host"];
        $this->dbName = $conf["db_database"];
@@ -55,9 +55,10 @@
        $this->dbPass = $conf["db_password"];
        $this->connect();
    }
    function __destruct() {
        $this->closeConn();
        }
    }
    // error handler
    function updateError($location)
@@ -67,7 +68,7 @@
        $this->errorLocation = $location;
        if($this->errorNumber && $this->show_error_messages)
        {
            echo('<br /><b>'.$this->errorLocation.'</b><br />'.$this->errorMessage);
            echo '<br /><b>'.$this->errorLocation.'</b><br />'.$this->errorMessage;
            flush();
        }
    }
@@ -76,7 +77,7 @@
    {
        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()<br />ibase_pconnect');
@@ -91,16 +92,16 @@
        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.')<br />ibase_query');
        if(!$this->queryId) {
            return false;
@@ -141,7 +142,7 @@
    // 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()<br />ibase_fetch_assoc');
        if(!$this->record || !is_array($this->record))
        {
@@ -156,32 +157,32 @@
    {
        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 @@
                $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."<br><br>";
           $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."<br><br>";
           $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 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."<br><br>";
            $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."<br><br>";
            $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);
            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 @@
                    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 @@
                    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 @@
                    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;
        }
    }
}
?>
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
    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();
  }
    // 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);
  public function __destruct() {
    $this->close(); // helps avoid memory leaks, and persitent connections that don't go away.
  }
            $try++;
            $this->updateError('DB::__construct');
  // error handler
  public function updateError($location) {
    global $app, $conf;
            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 @@
      $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;
    }
    //** 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 one record in an array
    public function queryOneRecord($queryString) {
        if(!$this->query($queryString) || $this->numRows() == 0)
        {
            return false;
        }
        return $this->nextRecord();
    }
      // Insert backticks only for incomplete table names.
      if(stristr($db_table,'.')) {
    $escape = '';
      } else {
    $escape = '`';
      }
    // 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;
                }
            }
        } 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 @@
            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;
    }
    //* 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;
    }
    public function freeResult($query)
    {
      if(is_object($query) && (get_class($query) == "mysqli_result")) {
    $query->free();
    return true;
      } else {
    return false;
      }
    }
    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 delete() {
    }
    }
    /* TODO: Does anything use this? */
    public function Transaction($action) {
      //action = begin, commit oder rollback
    /* 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 createTable($table_name,$columns) {
      $index = '';
      $sql = "CREATE TABLE $table_name (";
      foreach($columns as $col){
    $sql .= $col['name'].' '.$this->mapType($col['type'],$col['typeValue']).' ';
    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['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 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'].' ';
    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;
    }
    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'].'),';
    public function dropTable($table_name) {
        $this->check($table_name);
        $sql = "DROP TABLE '". $table_name."'";
        return $this->query($sql);
    }
      }
      $sql .= $index;
      $sql = substr($sql,0,-1);
      //die($sql);
      $this->query($sql);
      return true;
    }
    // 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;
    }
    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 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 @@
     */
    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 @@
      $isnull = $row[2];
      $type = $row[1];
      */
      $name = $row['Field'];
      $default = $row['Default'];
      $key = $row['Key'];
      $extra = $row['Extra'];
      $isnull = $row['Null'];
      $type = $row['Type'];
                $name = $row['Field'];
                $default = $row['Default'];
                $key = $row['Key'];
                $extra = $row['Extra'];
                $isnull = $row['Null'];
                $type = $row['Type'];
      $column = array();
                $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;
                $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
                // 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';
                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;
                $column['type'] = $metaType;
          $columns[] = $column;
          }
    return $columns;
      } else {
    return false;
      }
                $columns[] = $column;
            }
            return $columns;
        } else {
            return false;
        }
      //$this->createTable('tester',$columns);
        //$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 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;
        }
    }
          }
}
          ?>
?>
interface/lib/classes/form.inc.php
@@ -29,165 +29,192 @@
*/
/**
* 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 @@
                            }
                        }
                        $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 .= "<option value='$k'$selected>$v</option>\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 @@
                        }
                    }
                    $new_record[$key] = $out;
                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 .= "<option value='$k'>$v</option>\r\n";
                            }
                        }
                        $new_record[$key] = $out;
                    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 .= "<option value='$k'>$v</option>\r\n";
                        }
                    }
                    $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 @@
                    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 @@
                    }
                }
            }
        }
        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', ";
            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_insert_key .= "`$key`, ";
                                $sql_insert_val .= "'$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', ";
                                }
                            }
                        } 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', ";
                            } 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 "<pre>";
        print_r($array_data);
        echo "</pre>";
    }
    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;
        }
        // setze Loop
        $app->tpl->setLoop("formTab", $frmTab);
        // 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);
        // Formular action setzen
        $app->tpl->setVar('form_action',$this->formDef["action"]);
    }
        $app->tpl->setVar('form_action', $this->formDef["action"]);
    }
}
?>
interface/lib/classes/functions.inc.php
@@ -33,14 +33,14 @@
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,58 +49,58 @@
        $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();
        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) {
@@ -108,7 +108,7 @@
            }
        } 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'];
@@ -116,53 +116,53 @@
        }
        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;
@@ -173,25 +173,25 @@
                    }
                }
            } 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");
@@ -200,7 +200,7 @@
                $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)){
@@ -229,7 +229,7 @@
                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){
@@ -274,117 +274,119 @@
        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] != ''? ' &gt; '.$server_by_ip[$ip] : ''),
                                                    'onclick' => '',
                                                    'fill_text' => $ip
                                                );
                $result_array['cdata'][] = array( 'title' => $ip,
                    'description' => $type.($server_by_ip[$ip] != ''? ' &gt; '.$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);
        }
    }
    /**
    * Function to change bytes to kB, MB, GB or TB
    * @param int $size - size in bytes
    * @param int precicion - after-comma-numbers (default: 2)
    * @return string - formated bytes
    */
    public function formatBytes($size, $precision = 2) {
        $base=log($size)/log(1024);
        $suffixes=array('','k','M','G','T');
        return round(pow(1024,$base-floor($base)),$precision).$suffixes[floor($base)];
    }
    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:
    /**
     * Function to change bytes to kB, MB, GB or TB
     * @param int $size - size in bytes
     * @param int precicion - after-comma-numbers (default: 2)
     * @return string - formated bytes
     */
    public function formatBytes($size, $precision = 2) {
        $base=log($size)/log(1024);
        $suffixes=array('', 'k', 'M', 'G', 'T');
        return round(pow(1024, $base-floor($base)), $precision).$suffixes[floor($base)];
    }
    /** 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 <mso@phlylabs.de>
                 * @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 <mso@phlylabs.de>
                 * @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);
    }
}
?>
interface/lib/classes/getconf.inc.php
@@ -31,7 +31,7 @@
class getconf {
    private $config;
    public function get_server_config($server_id, $section = '') {
        global $app;
@@ -43,10 +43,10 @@
        }
        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 @@
        }
        return ($section == '') ? $this->config['global'] : $this->config['global'][$section];
    }
}
?>
interface/lib/classes/importer.inc.php
@@ -30,56 +30,59 @@
*/
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();
    }
    protected function checkPerm($session_id, $function_name)
    {
        // always return true as this is used from inside the application not through remote calls
        return true;
        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;
    }
    protected function getSession($session_id)
    {
    {
        return array(); // we have no sessions here
    }
}
?>
interface/lib/classes/ini_parser.inc.php
@@ -59,8 +59,8 @@
            $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";
                }
            }
interface/lib/classes/ispcmail.inc.php
@@ -30,498 +30,544 @@
/**
 * 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;
    }
        return $input;
    }
    /**
    * Function to encode the subject if necessary
    * according to RFC2047
    * @access private
    */
    private function _encodeSubject($input, $charset = 'ISO-8859-1') {
        /*
     * 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 @@
            }
        }*/
        $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);
            $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));
        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));
            $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;
    }
}
?>
interface/lib/classes/ispconfig_request.inc.php
@@ -32,229 +32,232 @@
//* This class is loaded automatically by the ispconfig framework.
abstract class ISPConfigRequest {
    /**
     * Get header data and contents from an url
     *
     * Calls an url and returns an array containing the http header and the page content
     *
     * @access public
     * @param string $url the url to call
     * @param string $store_in the file to store the data in instead of returning them
     * @return array The array with header data at index 0 and page content at index 1, returns boolean false on error. If $store_in is set only the headers are returned
     */
    public static function get_with_headers($url, $store_in = null, $follow_redirects = false, $user_agent = false) {
        if($follow_redirects === true) $follow_redirects = 5;
        elseif($follow_redirects !== false) $follow_redirects--;
        if(!$user_agent) $user_agent = 'pxFW GET proxy';
        $url_info = parse_url($url);
        if(isset($url_info['scheme']) && $url_info['scheme'] == 'https') {
            $port = isset($url_info['port']) ? $url_info['port'] : 443;
            //@$fp = stream_socket_client('ssl://' . $url_info['host'] . ':' . $port, $errno, $errstr, 10, STREAM_CLIENT_CONNECT, stream_context_create(array('ssl' => array('ciphers' => 'ALL:!AES:!3DES:!RC4:@STRENGTH'))));
            @$fp = fsockopen('sslv3://' . $url_info['host'], $port, $errno, $errstr, 10);
        } else {
            $port = isset($url_info['port']) ? $url_info['port'] : 80;
            @$fp = fsockopen($url_info['host'], $port, $errno, $errstr, 10);
        }
        if($store_in) {
            $outfp = fopen($store_in, 'w');
            if(!$outfp) return false;
        }
        if($fp) {
            stream_set_timeout($fp, 10);
            $head = 'GET ' . (isset($url_info['path']) ? $url_info['path'] : '/') . (isset($url_info['query']) ? '?' . $url_info['query'] : '');
            $head .= " HTTP/1.0\r\nHost: " . (isset($url_info['host']) ? $url_info['host'] : '') . "\r\n";
            $head .= "User-Agent: " . $user_agent . "\r\n";
            if(isset($url_info['user'])) {
                if(!array_key_exists('pass', $url_info)) $url_info['pass'] = '';
                $head .= "Authorization: basic " . base64_encode($url_info['user'] . ':' . $url_info['pass']) . "\r\n";
            }
            $head .= "Connection: Close\r\n";
            $head .= "Accept: */*\r\n\r\n";
            $data = '';
            $eoheader = false;
            fputs($fp, $head);
            while(!feof($fp)) {
                if($header = fgets($fp, 1024)) {
                    if($eoheader == true) {
                        if($store_in) fputs($outfp, $header);
                        else $data .= $header;
                        continue;
                    }
                    if ($header == "\r\n") {
                        $eoheader = true;
                        continue;
                    } else {
                        $header = trim($header);
                    }
                    $sc_pos = strpos($header, ':');
                    if($sc_pos === false) {
                        $headers['status'] = $header;
                        $headers['http_code'] = intval(preg_replace('/^HTTP\/\d+\.\d+\s+(\d+)\s+.*$/', '$1', $header));
                    } else {
                        $label = substr($header, 0, $sc_pos);
                        $value = substr($header, $sc_pos + 1);
                        $headers[strtolower($label)] = trim($value);
                    }
                }
            }
            fclose($fp);
            if(isset($headers['http_code']) && isset($headers['location']) && ($headers['http_code'] == 301 || $headers['http_code'] == 302) && $follow_redirects > 0) {
                if($store_in) fclose($outfp);
                return $self::get_with_headers($headers['location'], $store_in, $follow_redirects);
            }
            if($store_in) {
                fclose($outfp);
                $code = intval(preg_replace('/^HTTP\/\d+\.\d+\s+(\d+)\s+.*$/', '$1', $headers['status']));
                if($code != 200) {
                    return false;
                }
                return $headers;
            } else {
                return array($headers, $data);
            }
        } else {
            if($store_in) {
                fclose($outfp);
                @unlink($store_in);
            }
            return false;
        }
    }
    /**
     * Gets the content of an url
     *
     * Checks for the php function file_get_contents and uses an alternative if not found
     *
     * @access public
     * @param string $url url to get
     * @return string url data including headers
     * @see file_get_contents
     */
    public static function get($url) {
        if(function_exists('file_get_contents')) return file_get_contents($url);
        $fp = fopen($url, 'r');
        $data = '';
        while(!feof($fp)) {
            $data .= fgets($fp, 8192);
        }
        fclose($fp);
        return $data;
    }
    /**
     * Get header data and contents from an url
     *
     * Calls an url and returns an array containing the http header and the page content
     *
     * @access public
     * @param string $url the url to call
     * @param string $store_in the file to store the data in instead of returning them
     * @return array The array with header data at index 0 and page content at index 1, returns boolean false on error. If $store_in is set only the headers are returned
     */
    /**
     * Make a post request and get data
     *
     * Calls an url with a post request and returns the data - and optionally the header content
     *
     * @access public
     * @param string $url the url to call
     * @param string $data the post data to send
     * @param bool $get_headers if true, the function will return an array like PXUrl::get_with_headers(), otherwise the content is returned as a string
     * @return mixed Content data as string or - if get_headers is true - the array with header data at index 0 and page content at index 1
     * @see get_url_and_headers
     */
    public static function post($url, $data, $get_headers = false, $user_agent = false) {
        $url_info = parse_url($url);
        if((isset($url_info['scheme']) && $url_info['scheme'] == 'https') || $url_info['port'] == 443) {
            $port = (!isset($url_info['port']) || !$url_info['port'] || $url_info['port'] == 443 || $url_info['port'] == 80) ? 443 : $url_info['port'];
            //@$fp = stream_socket_client('ssl://' . $url_info['host'] . ':' . $port, $errno, $errstr, 10, STREAM_CLIENT_CONNECT, stream_context_create(array('ssl' => array('ciphers' => 'ALL:!AES:!3DES:!RC4:@STRENGTH'))));
            @$fp = fsockopen('sslv3://' . $url_info['host'], $port, $errno, $errstr, 10);
        } else {
            $port = isset($url_info['port']) ? $url_info['port'] : 80;
            @$fp = fsockopen($url_info['host'], $port, $errno, $errstr, 10);
        }
        if(!$fp) return '';
        if(!$user_agent) $user_agent = 'pxFW GET proxy';
        $header = 'POST ' . (isset($url_info['path']) ? $url_info['path'] : '/') . (isset($url_info['query']) ? '?' . @$url_info['query'] : '') . " HTTP/1.1\r\n";
        $header .= "Host: " . @$url_info['host'] . "\r\n";
        $header .= "User-Agent: " . $user_agent . "\r\n";
        if(isset($url_info['user'])) {
            if(!array_key_exists('pass', $url_info)) $url_info['pass'] = '';
            $header .= "Authorization: basic " . base64_encode($url_info['user'] . ':' . $url_info['pass']) . "\r\n";
        }
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($data) . "\r\n";
        $header .= "Connection: close\r\n\r\n";
        $header .= $data . "\r\n\r\n";
        fwrite($fp, $header);
        $response = '';
        $eoheader = false;
        $header = '';
        $tmpdata = '';
        $chunked = false;
        $chunklen = 0;
        while(!feof($fp)) {
            if($header = @fgets($fp, 1024)) {
                if($eoheader == true) {
                    $response .= $header;
                    continue;
                }
                if ($header == "\r\n") {
                    $eoheader = true;
                    continue;
                } else {
                    $tmpdata .= $header;
                    if(preg_match('/Transfer-Encoding:\s+chunked/i', $tmpdata)) $chunked = true;
                }
            }
        }
        //var_dump($response, $chunked, $header);
        if($chunked == true) {
            $lines = explode("\n", $response);
            $response = '';
            $chunklen = 0;
            foreach($lines as $line) {
                $line .= "\n";
                if($chunklen <= 0) {
                    if(preg_match('/^([0-9a-f]+)\s*$/is', $line, $matches)) {
                        $chunklen = hexdec($matches[1]);
                    }
                    continue;
                }
                if(strlen($line) > $chunklen) {
                    //echo "Warnung: " . strlen($line) . " > " . $chunklen . "\n";
                    $line = substr($line, 0, $chunklen);
                }
                $response .= $line;
                $chunklen -= strlen($line);
            }
            $start = strpos($response,'<?xml');
            $end = strrpos($response,'>');
            if($start !== false && $end !== false) $response = substr($response, $start, $end - $start + 1);
        }
        fclose($fp);
        if($get_headers == true) {
            $tmpheaders = explode("\n", $tmpdata);
            $headers = array();
            foreach($tmpheaders as $cur) {
                if(preg_match('/^(\w+)\:\s*(.*)$/is', $cur, $matches)) {
                    $headers["$matches[1]"] = trim($matches[2]);
                }
            }
            return array($headers, $response);
        } else return $response;
    }
    public static function get_with_headers($url, $store_in = null, $follow_redirects = false, $user_agent = false) {
        if($follow_redirects === true) $follow_redirects = 5;
        elseif($follow_redirects !== false) $follow_redirects--;
        if(!$user_agent) $user_agent = 'pxFW GET proxy';
        $url_info = parse_url($url);
        if(isset($url_info['scheme']) && $url_info['scheme'] == 'https') {
            $port = isset($url_info['port']) ? $url_info['port'] : 443;
            //@$fp = stream_socket_client('ssl://' . $url_info['host'] . ':' . $port, $errno, $errstr, 10, STREAM_CLIENT_CONNECT, stream_context_create(array('ssl' => array('ciphers' => 'ALL:!AES:!3DES:!RC4:@STRENGTH'))));
            @$fp = fsockopen('sslv3://' . $url_info['host'], $port, $errno, $errstr, 10);
        } else {
            $port = isset($url_info['port']) ? $url_info['port'] : 80;
            @$fp = fsockopen($url_info['host'], $port, $errno, $errstr, 10);
        }
        if($store_in) {
            $outfp = fopen($store_in, 'w');
            if(!$outfp) return false;
        }
        if($fp) {
            stream_set_timeout($fp, 10);
            $head = 'GET ' . (isset($url_info['path']) ? $url_info['path'] : '/') . (isset($url_info['query']) ? '?' . $url_info['query'] : '');
            $head .= " HTTP/1.0\r\nHost: " . (isset($url_info['host']) ? $url_info['host'] : '') . "\r\n";
            $head .= "User-Agent: " . $user_agent . "\r\n";
            if(isset($url_info['user'])) {
                if(!array_key_exists('pass', $url_info)) $url_info['pass'] = '';
                $head .= "Authorization: basic " . base64_encode($url_info['user'] . ':' . $url_info['pass']) . "\r\n";
            }
            $head .= "Connection: Close\r\n";
            $head .= "Accept: */*\r\n\r\n";
            $data = '';
            $eoheader = false;
            fputs($fp, $head);
            while(!feof($fp)) {
                if($header = fgets($fp, 1024)) {
                    if($eoheader == true) {
                        if($store_in) fputs($outfp, $header);
                        else $data .= $header;
                        continue;
                    }
                    if ($header == "\r\n") {
                        $eoheader = true;
                        continue;
                    } else {
                        $header = trim($header);
                    }
                    $sc_pos = strpos($header, ':');
                    if($sc_pos === false) {
                        $headers['status'] = $header;
                        $headers['http_code'] = intval(preg_replace('/^HTTP\/\d+\.\d+\s+(\d+)\s+.*$/', '$1', $header));
                    } else {
                        $label = substr($header, 0, $sc_pos);
                        $value = substr($header, $sc_pos + 1);
                        $headers[strtolower($label)] = trim($value);
                    }
                }
            }
            fclose($fp);
            if(isset($headers['http_code']) && isset($headers['location']) && ($headers['http_code'] == 301 || $headers['http_code'] == 302) && $follow_redirects > 0) {
                if($store_in) fclose($outfp);
                return $self::get_with_headers($headers['location'], $store_in, $follow_redirects);
            }
            if($store_in) {
                fclose($outfp);
                $code = intval(preg_replace('/^HTTP\/\d+\.\d+\s+(\d+)\s+.*$/', '$1', $headers['status']));
                if($code != 200) {
                    return false;
                }
                return $headers;
            } else {
                return array($headers, $data);
            }
        } else {
            if($store_in) {
                fclose($outfp);
                @unlink($store_in);
            }
            return false;
        }
    }
    /**
     * Gets the content of an url
     *
     * Checks for the php function file_get_contents and uses an alternative if not found
     *
     * @access public
     * @param string $url url to get
     * @return string url data including headers
     * @see file_get_contents
     */
    public static function get($url) {
        if(function_exists('file_get_contents')) return file_get_contents($url);
        $fp = fopen($url, 'r');
        $data = '';
        while(!feof($fp)) {
            $data .= fgets($fp, 8192);
        }
        fclose($fp);
        return $data;
    }
    /**
     * Make a post request and get data
     *
     * Calls an url with a post request and returns the data - and optionally the header content
     *
     * @access public
     * @param string $url the url to call
     * @param string $data the post data to send
     * @param bool $get_headers if true, the function will return an array like PXUrl::get_with_headers(), otherwise the content is returned as a string
     * @return mixed Content data as string or - if get_headers is true - the array with header data at index 0 and page content at index 1
     * @see get_url_and_headers
     */
    public static function post($url, $data, $get_headers = false, $user_agent = false) {
        $url_info = parse_url($url);
        if((isset($url_info['scheme']) && $url_info['scheme'] == 'https') || $url_info['port'] == 443) {
            $port = (!isset($url_info['port']) || !$url_info['port'] || $url_info['port'] == 443 || $url_info['port'] == 80) ? 443 : $url_info['port'];
            //@$fp = stream_socket_client('ssl://' . $url_info['host'] . ':' . $port, $errno, $errstr, 10, STREAM_CLIENT_CONNECT, stream_context_create(array('ssl' => array('ciphers' => 'ALL:!AES:!3DES:!RC4:@STRENGTH'))));
            @$fp = fsockopen('sslv3://' . $url_info['host'], $port, $errno, $errstr, 10);
        } else {
            $port = isset($url_info['port']) ? $url_info['port'] : 80;
            @$fp = fsockopen($url_info['host'], $port, $errno, $errstr, 10);
        }
        if(!$fp) return '';
        if(!$user_agent) $user_agent = 'pxFW GET proxy';
        $header = 'POST ' . (isset($url_info['path']) ? $url_info['path'] : '/') . (isset($url_info['query']) ? '?' . @$url_info['query'] : '') . " HTTP/1.1\r\n";
        $header .= "Host: " . @$url_info['host'] . "\r\n";
        $header .= "User-Agent: " . $user_agent . "\r\n";
        if(isset($url_info['user'])) {
            if(!array_key_exists('pass', $url_info)) $url_info['pass'] = '';
            $header .= "Authorization: basic " . base64_encode($url_info['user'] . ':' . $url_info['pass']) . "\r\n";
        }
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($data) . "\r\n";
        $header .= "Connection: close\r\n\r\n";
        $header .= $data . "\r\n\r\n";
        fwrite($fp, $header);
        $response = '';
        $eoheader = false;
        $header = '';
        $tmpdata = '';
        $chunked = false;
        $chunklen = 0;
        while(!feof($fp)) {
            if($header = @fgets($fp, 1024)) {
                if($eoheader == true) {
                    $response .= $header;
                    continue;
                }
                if ($header == "\r\n") {
                    $eoheader = true;
                    continue;
                } else {
                    $tmpdata .= $header;
                    if(preg_match('/Transfer-Encoding:\s+chunked/i', $tmpdata)) $chunked = true;
                }
            }
        }
        //var_dump($response, $chunked, $header);
        if($chunked == true) {
            $lines = explode("\n", $response);
            $response = '';
            $chunklen = 0;
            foreach($lines as $line) {
                $line .= "\n";
                if($chunklen <= 0) {
                    if(preg_match('/^([0-9a-f]+)\s*$/is', $line, $matches)) {
                        $chunklen = hexdec($matches[1]);
                    }
                    continue;
                }
                if(strlen($line) > $chunklen) {
                    //echo "Warnung: " . strlen($line) . " > " . $chunklen . "\n";
                    $line = substr($line, 0, $chunklen);
                }
                $response .= $line;
                $chunklen -= strlen($line);
            }
            $start = strpos($response, '<?xml');
            $end = strrpos($response, '>');
            if($start !== false && $end !== false) $response = substr($response, $start, $end - $start + 1);
        }
        fclose($fp);
        if($get_headers == true) {
            $tmpheaders = explode("\n", $tmpdata);
            $headers = array();
            foreach($tmpheaders as $cur) {
                if(preg_match('/^(\w+)\:\s*(.*)$/is', $cur, $matches)) {
                    $headers["$matches[1]"] = trim($matches[2]);
                }
            }
            return array($headers, $response);
        } else return $response;
    }
}
?>
interface/lib/classes/json_handler.inc.php
@@ -31,91 +31,92 @@
class ISPConfigJSONHandler {
    private $methods = array();
    private $classes = array();
    private $methods = array();
    private $classes = array();
    public function __construct() {
        global $app;
        // load main remoting file
        $app->load('remoting');
        // load all remote classes and get their methods
        $dir = dirname(realpath(__FILE__)) . '/remote.d';
        $d = opendir($dir);
        while($f = readdir($d)) {
            if($f == '.' || $f == '..') continue;
            if(!is_file($dir . '/' . $f) || substr($f, strrpos($f, '.')) != '.php') continue;
            $name = substr($f, 0, strpos($f, '.'));
            include($dir . '/' . $f);
            $class_name = 'remoting_' . $name;
            if(class_exists($class_name, false)) {
                $this->classes[$class_name] = new $class_name();
                foreach(get_class_methods($this->classes[$class_name]) as $method) {
                    $this->methods[$method] = $class_name;
                }
            }
        }
        closedir($d);
        // add main methods
        $this->methods['login'] = 'remoting';
        $this->methods['logout'] = 'remoting';
        $this->methods['get_function_list'] = 'remoting';
        // create main class
        $this->classes['remoting'] = new remoting(array_keys($this->methods));
    }
    private function _return_json($code, $message, $data = false) {
        $ret = new stdClass;
        $ret->code = $code;
        $ret->message = $message;
        $ret->response = $data;
        header('Content-Type: application/json; charset="utf-8"');
        print json_encode($ret);
        exit;
    }
    public function run() {
        if(!isset($_GET) || !is_array($_GET) || count($_GET) < 1) {
            $this->_return_json('invalid_method', 'Method not provided in json call');
        }
        $keys = array_keys($_GET);
        $method = reset($keys);
        $params = array();
    public function __construct() {
        global $app;
        if(is_array($_POST)) {
            foreach($_POST as $key => $val) {
                $tmp = json_decode($val);
                if(!$tmp) $params[] = $val;
                else $params[] = (array)$tmp;
            }
        }
        if(array_key_exists($method, $this->methods) == false) {
            $this->_return_json('invalid_method', 'Method ' . $method . ' does not exist');
        }
        $class_name = $this->methods[$method];
        if(array_key_exists($class_name, $this->classes) == false) {
            $this->_return_json('invalid_class', 'Class ' . $class_name . ' does not exist');
        }
        if(method_exists($this->classes[$class_name], $method) == false) {
            $this->_return_json('invalid_method', 'Method ' . $method . ' does not exist in the class it was expected (' . $class_name . ')');
        }
        try {
            $this->_return_json('ok', '', call_user_func_array(array($this->classes[$class_name], $method), $params));
        } catch(SoapFault $e) {
            $this->_return_json('remote_fault', $e->getMessage());
        }
    }
        // load main remoting file
        $app->load('remoting');
        // load all remote classes and get their methods
        $dir = dirname(realpath(__FILE__)) . '/remote.d';
        $d = opendir($dir);
        while($f = readdir($d)) {
            if($f == '.' || $f == '..') continue;
            if(!is_file($dir . '/' . $f) || substr($f, strrpos($f, '.')) != '.php') continue;
            $name = substr($f, 0, strpos($f, '.'));
            include $dir . '/' . $f;
            $class_name = 'remoting_' . $name;
            if(class_exists($class_name, false)) {
                $this->classes[$class_name] = new $class_name();
                foreach(get_class_methods($this->classes[$class_name]) as $method) {
                    $this->methods[$method] = $class_name;
                }
            }
        }
        closedir($d);
        // add main methods
        $this->methods['login'] = 'remoting';
        $this->methods['logout'] = 'remoting';
        $this->methods['get_function_list'] = 'remoting';
        // create main class
        $this->classes['remoting'] = new remoting(array_keys($this->methods));
    }
    private function _return_json($code, $message, $data = false) {
        $ret = new stdClass;
        $ret->code = $code;
        $ret->message = $message;
        $ret->response = $data;
        header('Content-Type: application/json; charset="utf-8"');
        print json_encode($ret);
        exit;
    }
    public function run() {
        if(!isset($_GET) || !is_array($_GET) || count($_GET) < 1) {
            $this->_return_json('invalid_method', 'Method not provided in json call');
        }
        $keys = array_keys($_GET);
        $method = reset($keys);
        $params = array();
        if(is_array($_POST)) {
            foreach($_POST as $key => $val) {
                $tmp = json_decode($val);
                if(!$tmp) $params[] = $val;
                else $params[] = (array)$tmp;
            }
        }
        if(array_key_exists($method, $this->methods) == false) {
            $this->_return_json('invalid_method', 'Method ' . $method . ' does not exist');
        }
        $class_name = $this->methods[$method];
        if(array_key_exists($class_name, $this->classes) == false) {
            $this->_return_json('invalid_class', 'Class ' . $class_name . ' does not exist');
        }
        if(method_exists($this->classes[$class_name], $method) == false) {
            $this->_return_json('invalid_method', 'Method ' . $method . ' does not exist in the class it was expected (' . $class_name . ')');
        }
        try {
            $this->_return_json('ok', '', call_user_func_array(array($this->classes[$class_name], $method), $params));
        } catch(SoapFault $e) {
            $this->_return_json('remote_fault', $e->getMessage());
        }
    }
}
?>
?>
interface/lib/classes/listform.inc.php
@@ -30,158 +30,160 @@
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;
        //* 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);
                }
            }
    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);
                }
            }
        }
        //* 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();
     * 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
     */
        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);
    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);
            $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];
                }
            }
        }
            //* 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);
        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<br />\r\n";
            }
        }
        return $values;
    }
                $values = $app->$datasource_class->$datasource_function($field, $record);
            } else {
                $this->errorMessage .= "Custom datasource class or function is empty<br />\r\n";
            }
        }
        return $values;
    }
    public function getSearchSQL($sql_where = '')
    {
        global $app, $db;
    public function getSearchSQL($sql_where = '')
    {
        global $app, $db;
        //* Get config variable
        $list_name = $this->listDef['name'];
        $search_prefix = $this->listDef['search_prefix'];
        //* 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'];
        //* 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;
                }
                //* 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;
                //* 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];
                    //* 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 = '<option value=""></option>';
                        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 .= "<option value='$k'$selected>$v</option>\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 = '<option value=""></option>';
                        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 .= "<option value='$k'$selected>$v</option>\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 @@
                    $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 @@
                        $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 @@
                        $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'];
        //* 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 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"]);
        //* 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;
        //* 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);
        $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'];
        $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;
        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);
        $this->pagingValues = $vars;
        $this->pagingHTML = $this->getPagingHTML($vars);
        //* Return limit sql
        return "LIMIT $sql_von, $records_per_page";
    }
        //* 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 = '<a class="btn-page first-page" href="'."javascript:loadContent('".$vars['list_file'].'?page=0'.$vars['page_params']."');".'">'
                    .'<img src="themes/'.$_SESSION['s']['theme'].'/icons/x16/arrow_stop_180.png"></a> &nbsp; ';
            $content .= '<a class="btn-page previous-page" href="'."javascript:loadContent('".$vars['list_file'].'?page='.$vars['last_page'].$vars['page_params']."');".'">'
                        .'<img src="themes/'.$_SESSION['s']['theme'].'/icons/x16/arrow_180.png"></a> &nbsp; ';
        }
        $content .= ' '.$this->lng('page_txt').' ';
        $prev = -1;
        foreach($show_pages as $p) {
            if($prev != -1 && $p > $prev + 1) $content .= '<span class="page-spacer">...</span>';
            $content .= '<a class="link-page' . ($p == $vars['page'] ? ' current-page' : '') . '" href="'."javascript:loadContent('".$vars['list_file'].'?page='.$p.$vars['page_params']."');".'">'. ($p+1) .'</a>';
            $prev = $p;
        }
        //.$vars['next_page'].' '.$this->lng('page_of_txt').' '.$vars['max_pages'].' &nbsp; ';
        //* Show Next
        if(isset($vars['show_page_next']) && $vars['show_page_next'] == 1){
            $content .= '<a class="btn-page next-page" href="'."javascript:loadContent('".$vars['list_file'].'?page='.$vars['next_page'].$vars['page_params']."');".'">'
                        .'<img src="themes/'.$_SESSION['s']['theme'].'/icons/x16/arrow.png"></a> &nbsp; ';
        $content .= '<a class="btn-page last-page" href="'."javascript:loadContent('".$vars['list_file'].'?page='.$vars['pages'].$vars['page_params']."');".'">'
                    .'<img src="themes/'.$_SESSION['s']['theme'].'/icons/x16/arrow_stop.png"></a>';
        }
        return $content;
    }
    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 = '<a class="btn-page first-page" href="'."javascript:loadContent('".$vars['list_file'].'?page=0'.$vars['page_params']."');".'">'
                .'<img src="themes/'.$_SESSION['s']['theme'].'/icons/x16/arrow_stop_180.png"></a> &nbsp; ';
            $content .= '<a class="btn-page previous-page" href="'."javascript:loadContent('".$vars['list_file'].'?page='.$vars['last_page'].$vars['page_params']."');".'">'
                .'<img src="themes/'.$_SESSION['s']['theme'].'/icons/x16/arrow_180.png"></a> &nbsp; ';
        }
        $content .= ' '.$this->lng('page_txt').' ';
        $prev = -1;
        foreach($show_pages as $p) {
            if($prev != -1 && $p > $prev + 1) $content .= '<span class="page-spacer">...</span>';
            $content .= '<a class="link-page' . ($p == $vars['page'] ? ' current-page' : '') . '" href="'."javascript:loadContent('".$vars['list_file'].'?page='.$p.$vars['page_params']."');".'">'. ($p+1) .'</a>';
            $prev = $p;
        }
        //.$vars['next_page'].' '.$this->lng('page_of_txt').' '.$vars['max_pages'].' &nbsp; ';
        //* Show Next
        if(isset($vars['show_page_next']) && $vars['show_page_next'] == 1){
            $content .= '<a class="btn-page next-page" href="'."javascript:loadContent('".$vars['list_file'].'?page='.$vars['next_page'].$vars['page_params']."');".'">'
                .'<img src="themes/'.$_SESSION['s']['theme'].'/icons/x16/arrow.png"></a> &nbsp; ';
            $content .= '<a class="btn-page last-page" href="'."javascript:loadContent('".$vars['list_file'].'?page='.$vars['pages'].$vars['page_params']."');".'">'
                .'<img src="themes/'.$_SESSION['s']['theme'].'/icons/x16/arrow_stop.png"></a>';
        }
        return $content;
    }
    public function getPagingHTMLasTXT($vars)
    {
        global $app;
        $content = '[<a href="'.$vars['list_file'].'?page=0'.$vars['page_params'].'">|&lt;&lt; </a>]';
        if($vars['show_page_back'] == 1){
            $content .= '[<< <a href="'.$vars['list_file'].'?page='.$vars['last_page'].$vars['page_params'].'">'.$app->lng('page_back_txt').'</a>] ';
        }
        $content .= ' '.$this->lng('page_txt').' '.$vars['next_page'].' '.$this->lng('page_of_txt').' '.$vars['max_pages'].' ';
        if($vars['show_page_next'] == 1){
            $content .= '[<a href="'.$vars['list_file'].'?page='.$vars['next_page'].$vars['page_params'].'">'.$app->lng('page_next_txt').' >></a>] ';
        }
        $content .= '[<a href="'.$vars['list_file'].'?page='.$vars['pages'].$vars['page_params'].'"> &gt;&gt;|</a>]';
        return $content;
    }
    {
        global $app;
        $content = '[<a href="'.$vars['list_file'].'?page=0'.$vars['page_params'].'">|&lt;&lt; </a>]';
        if($vars['show_page_back'] == 1){
            $content .= '[<< <a href="'.$vars['list_file'].'?page='.$vars['last_page'].$vars['page_params'].'">'.$app->lng('page_back_txt').'</a>] ';
        }
        $content .= ' '.$this->lng('page_txt').' '.$vars['next_page'].' '.$this->lng('page_of_txt').' '.$vars['max_pages'].' ';
        if($vars['show_page_next'] == 1){
            $content .= '[<a href="'.$vars['list_file'].'?page='.$vars['next_page'].$vars['page_params'].'">'.$app->lng('page_next_txt').' >></a>] ';
        }
        $content .= '[<a href="'.$vars['list_file'].'?page='.$vars['pages'].$vars['page_params'].'"> &gt;&gt;|</a>]';
        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 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) {
                            // is value int?
                            if (preg_match("/^[0-9]+[\.]?[0-9]*$/", $record[$key], $p)) {
                                $record[$key] = date($this->lng('conf_format_dateshort'), $record[$key]);
                            } else {
                                $record[$key] = date($this->lng('conf_format_dateshort'), strtotime($record[$key]));
                            }
                        }
                        break;
                    case 'DATETIMETSTAMP':
                        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]);
                            } else {
                                $record[$key] = date($this->lng('conf_format_datetime'), strtotime($record[$key]));
                            }
                        }
                        break;
                    case 'DATE':
                        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]);
                            } else {
                                $record[$key] = date($this->lng('conf_format_dateshort'), strtotime($record[$key]));
                            }
                        }
                        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]);
                            } else {
                                $record[$key] = date($this->lng('conf_format_datetime'), strtotime($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 'CURRENCY':
                        $record[$key] = $app->functions->currency_format($record[$key]);
                        break;
                    default:
                        $record[$key] = htmlentities(stripslashes($record[$key]),ENT_QUOTES,$conf["html_content_encoding"]);
                    }
    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');
                }
            }
        }
        return $record;
    }
                if(isset($record[$key])) {
                    switch ($field['datatype']){
                    case 'VARCHAR':
                        case 'TEXT':
                        $record[$key] = htmlentities(stripslashes($record[$key]), ENT_QUOTES, $conf["html_content_encoding"]);
                        break;
    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;
                        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]);
                            } else {
                                $record[$key] = date($this->lng('conf_format_dateshort'), 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;
                        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]);
                            } else {
                                $record[$key] = date($this->lng('conf_format_datetime'), strtotime($record[$key]));
                            }
                        }
                        break;
                    case 'DATE':
                        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]);
                            } else {
                                $record[$key] = date($this->lng('conf_format_dateshort'), strtotime($record[$key]));
                            }
                        }
                        break;
                    case 'DATETIME':
                        if($record[$key] > 0) {
                            $record[$key] = date('Y-m-d H:i:s',strtotime($record[$key]));
                        }
                        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]);
                            } else {
                                $record[$key] = date($this->lng('conf_format_datetime'), strtotime($record[$key]));
                            }
                        }
                        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] = $app->db->quote($record[$key]);
                        break;
                    case 'DOUBLE':
                        $record[$key] = htmlentities($record[$key], ENT_QUOTES, $conf["html_content_encoding"]);
                        break;
                    case 'CURRENCY':
                        $record[$key] = str_replace(',', '.', $record[$key]);
                        break;
                }
            }
        }
        return $record;
    }
                    case 'CURRENCY':
                        $record[$key] = $app->functions->currency_format($record[$key]);
                        break;
                    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;
    }
    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;
    }
}
?>
?>
interface/lib/classes/listform_actions.inc.php
@@ -29,7 +29,7 @@
*/
class listform_actions {
    private $id;
    public $idx_key;
    public $DataRowColor;
@@ -37,139 +37,139 @@
    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 @@
                }
            }
        }
        //* 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 @@
            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 @@
        //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 .= '<option value="'.$key.'" '.(isset($_SESSION['search']['limit']) &&  $_SESSION['search']['limit'] == $key ? 'selected="selected"':'' ).(!isset($_SESSION['search']['limit']) && $key == '15' ? 'selected="selected"':'').'>'.$val.'</option>';
            $options .= '<option value="'.$key.'" '.(isset($_SESSION['search']['limit']) &&  $_SESSION['search']['limit'] == $key ? 'selected="selected"':'' ).(!isset($_SESSION['search']['limit']) && $key == '15' ? 'selected="selected"':'').'>'.$val.'</option>';
        }
        $app->tpl->setVar('search_limit','<select name="search_limit" class="search_limit">'.$options.'</select>');
        $app->tpl->setVar('toolsarea_head_txt',$app->lng('toolsarea_head_txt'));
        $app->tpl->setVar('search_limit', '<select name="search_limit" class="search_limit">'.$options.'</select>');
        $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();
    }
}
?>
?>
interface/lib/classes/listform_tpl_generator.inc.php
@@ -29,11 +29,11 @@
*/
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 @@
        <thead>
          <tr>
';
        $lang["list_head_txt"] = $listDef["name"];
      $colcount = 0;
        $colcount = 0;
        foreach($listDef["item"] as $field) {
            $key = $field["field"];
            $html .= "            <th class=\"tbl_col_".$key."\" scope=\"col\"><tmpl_var name=\"".$key."_txt\"></th>\n";
            $lang[$key."_txt"] = $key;
         $colcount++;
            $colcount++;
        }
        $html .= '            <th class="tbl_col_buttons" scope="col">&nbsp;</th>
          </tr>
          <tr>
';
          foreach($listDef["item"] as $field) {
        foreach($listDef["item"] as $field) {
            $key = $field["field"];
            if($field["formtype"] == 'SELECT') {
                $html .= "            <td class=\"tbl_col_".$key."\"><select name=\"".$listDef["search_prefix"].$key."\" onChange=\"submitForm('pageForm','".$module."/".$listDef["file"]."');\">{tmpl_var name='".$listDef["search_prefix"].$key."'}</select></td>\n";
@@ -80,7 +80,7 @@
                $html .= "            <td class=\"tbl_col_".$key."\"><input type=\"text\" name=\"".$listDef["search_prefix"].$key."\" value=\"{tmpl_var name='".$listDef["search_prefix"].$key."'}\" /></td>\n";
            }
        }
        $html .= '            <td class="tbl_col_buttons"><div class="buttons"><button type="button" class="icons16 icoFilter" name="Filter" id="Filter" value="{tmpl_var name="filter_txt"}" onclick="'."submitForm('pageForm','".$module."/".$listDef["file"]."');".'"><span>{tmpl_var name="filter_txt"}</span></button></div></td>
          </tr>
        </thead>
@@ -88,14 +88,14 @@
          <tmpl_loop name="records">
          <tr class="tbl_row_<tmpl_if name=\'__EVEN__\'}even<tmpl_else>uneven</tmpl_if>">
';
        foreach($listDef["item"] as $field) {
            $key = $field["field"];
            $html .= "            <td class=\"tbl_col_".$key."\"><a href=\"#\" onclick=\"loadContent('".$module."/".$listDef["edit_file"]."?id={tmpl_var name='id'}');\">{tmpl_var name=\"".$key."\"}</a></td>\n";
        }
        $html .= "            <td class=\"tbl_col_buttons\">
              <div class=\"buttons icons16\">
              <div class=\"buttons icons16\">
                <a class=\"button icons16 icoDelete\" href=\"javascript: del_record('".$module."/".$listDef["delete_file"]."?id={tmpl_var name='id'}&phpsessid={tmpl_var name='phpsessid'}','{tmpl_var name='delete_confirmation'}');\"><span>{tmpl_var name='delete_txt'}</span></a>
              </div>
            </td>
@@ -107,7 +107,7 @@
              </tr>
          </tmpl_unless>
        </tbody>";
  $html .= '
        $html .= '
        <tfoot>
          <tr>
            <td class="tbl_footer tbl_paging" colspan="'.(count($listDef["item"])+1).'"><tmpl_var name="paging"></td>
@@ -119,26 +119,26 @@
</div>
';
        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 @@
        $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,"<?php\n");
            $fp = fopen($lng_file, "w");
            fwrite($fp, "<?php\n");
            foreach($wb_out as $key => $val) {
                $new_line = '$wb["'.$key.'"] = '."'$val';\n";
                fwrite($fp,$new_line);
                fwrite($fp, $new_line);
            }
            fwrite($fp,"?>");
            fwrite($fp, "?>");
            fclose($fp);
        }
    }
}
?>
?>
interface/lib/classes/plugin.inc.php
@@ -29,92 +29,92 @@
*/
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 @@
                }
                */
            } 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
}
?>
interface/lib/classes/plugin_backuplist.inc.php
@@ -30,121 +30,121 @@
class plugin_backuplist 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() {
    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'];
                        }
                    }
        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'];
                }
                //* 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);
            }
            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'];
                }
            }
                $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'])];
        //* 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);
                                $records_new[] = $rec;
                        }
                }
        $bgcolor = "#FFFFFF";
        if(is_array($records)) {
            foreach($records as $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();
        }
                // 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();
    }
}
?>
?>
interface/lib/classes/plugin_base.inc.php
@@ -29,31 +29,31 @@
*/
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 @@
}
?>
?>
Diff truncated after the above file
interface/lib/classes/plugin_dbhistory.inc.php interface/lib/classes/plugin_listview.inc.php interface/lib/classes/remote.d/client.inc.php interface/lib/classes/remote.d/dns.inc.php interface/lib/classes/remote.d/domains.inc.php interface/lib/classes/remote.d/mail.inc.php interface/lib/classes/remote.d/openvz.inc.php interface/lib/classes/remote.d/server.inc.php interface/lib/classes/remote.d/sites.inc.php interface/lib/classes/remoting.inc.php interface/lib/classes/remoting_lib.inc.php interface/lib/classes/searchform.inc.php interface/lib/classes/searchform_actions.inc.php interface/lib/classes/searchform_tpl_generator.inc.php interface/lib/classes/session.inc.php interface/lib/classes/simplepie.inc.php interface/lib/classes/sites_database_plugin.inc.php interface/lib/classes/soap_handler.inc.php interface/lib/classes/tform.inc.php interface/lib/classes/tform_actions.inc.php interface/lib/classes/tform_base.inc.php interface/lib/classes/tform_tpl_generator.inc.php interface/lib/classes/tools_monitor.inc.php interface/lib/classes/tools_sites.inc.php interface/lib/classes/tpl.inc.php interface/lib/classes/tpl_cache.inc.php interface/lib/classes/tpl_error.inc.php interface/lib/classes/tpl_ini.inc.php interface/lib/classes/tree.inc.php interface/lib/classes/validate_autoresponder.inc.php interface/lib/classes/validate_client.inc.php interface/lib/classes/validate_cron.inc.php interface/lib/classes/validate_database.inc.php interface/lib/classes/validate_datetime.inc.php interface/lib/classes/validate_dkim.inc.php interface/lib/classes/validate_dns.inc.php interface/lib/classes/validate_domain.inc.php interface/lib/classes/validate_ftpuser.inc.php interface/lib/classes/validate_reseller.inc.php interface/lib/config.inc.php interface/lib/plugins/clients_template_plugin.inc.php interface/lib/plugins/mail_user_filter_plugin.inc.php interface/lib/plugins/sites_web_database_user_plugin.inc.php interface/lib/plugins/sites_web_domain_plugin.inc.php interface/lib/plugins/sites_web_vhost_subdomain_plugin.inc.php interface/lib/plugins/vm_openvz_plugin.inc.php interface/web/admin/directive_snippets_del.php interface/web/admin/directive_snippets_edit.php interface/web/admin/directive_snippets_list.php interface/web/admin/firewall_del.php interface/web/admin/firewall_edit.php interface/web/admin/firewall_list.php interface/web/admin/form/dbsync.tform.php interface/web/admin/form/directive_snippets.tform.php interface/web/admin/form/filesync.tform.php interface/web/admin/form/firewall.tform.php interface/web/admin/form/groups.tform.php interface/web/admin/form/iptables.tform.php interface/web/admin/form/remote_user.tform.php interface/web/admin/form/server.tform.php interface/web/admin/form/server_config.tform.php interface/web/admin/form/server_ip.tform.php interface/web/admin/form/server_php.tform.php interface/web/admin/form/software_package.tform.php interface/web/admin/form/software_repo.tform.php interface/web/admin/form/system_config.tform.php interface/web/admin/form/tpl_default.tform.php interface/web/admin/form/users.tform.php interface/web/admin/groups_del.php interface/web/admin/groups_edit.php interface/web/admin/groups_list.php interface/web/admin/index.php interface/web/admin/iptables_del.php interface/web/admin/iptables_edit.php interface/web/admin/iptables_list.php interface/web/admin/language_add.php interface/web/admin/language_complete.php interface/web/admin/language_edit.php interface/web/admin/language_export.php interface/web/admin/language_import.php interface/web/admin/language_list.php interface/web/admin/lib/module.conf.php interface/web/admin/lib/remote.conf.php interface/web/admin/list/directive_snippets.list.php interface/web/admin/list/firewall.list.php interface/web/admin/list/groups.list.php interface/web/admin/list/iptables.list.php interface/web/admin/list/remote_user.list.php interface/web/admin/list/server.list.php interface/web/admin/list/server_config.list.php interface/web/admin/list/server_ip.list.php interface/web/admin/list/server_php.list.php interface/web/admin/list/software_repo.list.php interface/web/admin/list/users.list.php interface/web/admin/login_as.php interface/web/admin/remote_action_ispcupdate.php interface/web/admin/remote_action_osupdate.php interface/web/admin/remote_user_del.php interface/web/admin/remote_user_edit.php interface/web/admin/remote_user_list.php interface/web/admin/server_config_del.php interface/web/admin/server_config_edit.php interface/web/admin/server_config_list.php interface/web/admin/server_del.php interface/web/admin/server_edit.php interface/web/admin/server_ip_del.php interface/web/admin/server_ip_edit.php interface/web/admin/server_ip_list.php interface/web/admin/server_list.php interface/web/admin/server_php_del.php interface/web/admin/server_php_edit.php interface/web/admin/server_php_list.php interface/web/admin/software_package_del.php interface/web/admin/software_package_edit.php interface/web/admin/software_package_install.php interface/web/admin/software_package_list.php interface/web/admin/software_repo_del.php interface/web/admin/software_repo_edit.php interface/web/admin/software_repo_list.php interface/web/admin/software_update_list.php interface/web/admin/system_config_edit.php interface/web/admin/tpl_default.php interface/web/admin/users_del.php interface/web/admin/users_edit.php interface/web/admin/users_list.php interface/web/capp.php interface/web/client/client_circle_del.php interface/web/client/client_circle_edit.php interface/web/client/client_circle_list.php interface/web/client/client_del.php interface/web/client/client_edit.php interface/web/client/client_list.php interface/web/client/client_message.php interface/web/client/client_template_del.php interface/web/client/client_template_edit.php interface/web/client/client_template_list.php interface/web/client/domain_del.php interface/web/client/domain_edit.php interface/web/client/domain_list.php interface/web/client/domain_new_client.php interface/web/client/form/client.tform.php interface/web/client/form/client_circle.tform.php interface/web/client/form/client_template.tform.php interface/web/client/form/domain.tform.php interface/web/client/form/reseller.tform.php interface/web/client/lib/admin.conf.php interface/web/client/lib/module.conf.php interface/web/client/list/client.list.php interface/web/client/list/client_circle.list.php interface/web/client/list/client_template.list.php interface/web/client/list/domain.list.php interface/web/client/list/reseller.list.php interface/web/client/reseller_del.php interface/web/client/reseller_edit.php interface/web/client/reseller_list.php interface/web/content.php interface/web/dashboard/ajax_get_json.php interface/web/dashboard/dashboard.php interface/web/dashboard/dashlets/limits.php interface/web/dashboard/dashlets/mailquota.php interface/web/dashboard/dashlets/modules.php interface/web/dashboard/dashlets/quota.php interface/web/dashboard/lib/admin.conf.php interface/web/dashboard/lib/custom_menu.inc.php interface/web/dashboard/lib/module.conf.php interface/web/designer/form_edit.php interface/web/designer/form_list.php interface/web/designer/form_show.php interface/web/designer/index.php interface/web/designer/lib/admin.conf.php interface/web/designer/lib/module.conf.php interface/web/designer/module_edit.php interface/web/designer/module_list.php interface/web/designer/module_nav_del.php interface/web/designer/module_nav_edit.php interface/web/designer/module_nav_flip.php interface/web/designer/module_nav_item_del.php interface/web/designer/module_nav_item_edit.php interface/web/designer/module_nav_item_flip.php interface/web/designer/module_show.php interface/web/dns/ajax_get_json.php interface/web/dns/dns_a_edit.php interface/web/dns/dns_a_list.php interface/web/dns/dns_aaaa_edit.php interface/web/dns/dns_alias_edit.php interface/web/dns/dns_cname_edit.php interface/web/dns/dns_dkim_edit.php interface/web/dns/dns_dkim_get.php interface/web/dns/dns_hinfo_edit.php interface/web/dns/dns_import.php interface/web/dns/dns_mx_edit.php interface/web/dns/dns_ns_edit.php interface/web/dns/dns_ptr_edit.php interface/web/dns/dns_rp_edit.php interface/web/dns/dns_rr_del.php interface/web/dns/dns_slave_del.php interface/web/dns/dns_slave_edit.php interface/web/dns/dns_slave_list.php interface/web/dns/dns_soa_del.php interface/web/dns/dns_soa_edit.php interface/web/dns/dns_soa_list.php interface/web/dns/dns_srv_edit.php interface/web/dns/dns_template_del.php interface/web/dns/dns_template_edit.php interface/web/dns/dns_template_list.php interface/web/dns/dns_txt_edit.php interface/web/dns/dns_wizard.php interface/web/dns/form/dns_a.tform.php interface/web/dns/form/dns_aaaa.tform.php interface/web/dns/form/dns_alias.tform.php interface/web/dns/form/dns_cname.tform.php interface/web/dns/form/dns_dkim.tform.php interface/web/dns/form/dns_hinfo.tform.php interface/web/dns/form/dns_mx.tform.php interface/web/dns/form/dns_ns.tform.php interface/web/dns/form/dns_ptr.tform.php interface/web/dns/form/dns_rp.tform.php interface/web/dns/form/dns_slave.tform.php interface/web/dns/form/dns_soa.tform.php interface/web/dns/form/dns_srv.tform.php interface/web/dns/form/dns_template.tform.php interface/web/dns/form/dns_txt.tform.php interface/web/dns/lib/admin.conf.php interface/web/dns/lib/module.conf.php interface/web/dns/lib/remote.conf.php interface/web/dns/list/dns_a.list.php interface/web/dns/list/dns_slave.list.php interface/web/dns/list/dns_soa.list.php interface/web/dns/list/dns_template.list.php interface/web/help/faq_delete.php interface/web/help/faq_edit.php interface/web/help/faq_list.php interface/web/help/faq_manage_questions_list.php interface/web/help/faq_sections_delete.php interface/web/help/faq_sections_edit.php interface/web/help/faq_sections_list.php interface/web/help/form/faq.tform.php interface/web/help/form/faq_sections.tform.php interface/web/help/form/support_message.tform.php interface/web/help/index.php interface/web/help/lib/admin.conf.php interface/web/help/lib/module.conf.php interface/web/help/list/faq_list.php interface/web/help/list/faq_manage_questions_list.php interface/web/help/list/faq_sections_list.php interface/web/help/list/support_message.list.php interface/web/help/support_message_del.php interface/web/help/support_message_edit.php interface/web/help/support_message_list.php interface/web/help/version.php interface/web/index.php interface/web/js/scrigo.js.php interface/web/keepalive.php interface/web/login/index.php interface/web/login/lib/module.conf.php interface/web/login/logout.php interface/web/login/password_reset.php interface/web/mail/form/mail_alias.tform.php interface/web/mail/form/mail_aliasdomain.tform.php interface/web/mail/form/mail_blacklist.tform.php interface/web/mail/form/mail_content_filter.tform.php interface/web/mail/form/mail_domain.tform.php interface/web/mail/form/mail_domain_catchall.tform.php interface/web/mail/form/mail_forward.tform.php interface/web/mail/form/mail_get.tform.php interface/web/mail/form/mail_mailinglist.tform.php interface/web/mail/form/mail_relay_recipient.tform.php interface/web/mail/form/mail_spamfilter.tform.php interface/web/mail/form/mail_transport.tform.php interface/web/mail/form/mail_user.tform.php interface/web/mail/form/mail_user_filter.tform.php interface/web/mail/form/mail_whitelist.tform.php interface/web/mail/form/spamfilter_blacklist.tform.php interface/web/mail/form/spamfilter_config.tform.php interface/web/mail/form/spamfilter_policy.tform.php interface/web/mail/form/spamfilter_users.tform.php interface/web/mail/form/spamfilter_whitelist.tform.php interface/web/mail/lib/admin.conf.php interface/web/mail/lib/module.conf.php interface/web/mail/lib/remote.conf.php interface/web/mail/list/mail_alias.list.php interface/web/mail/list/mail_aliasdomain.list.php interface/web/mail/list/mail_blacklist.list.php interface/web/mail/list/mail_content_filter.list.php interface/web/mail/list/mail_domain.list.php interface/web/mail/list/mail_domain_catchall.list.php interface/web/mail/list/mail_forward.list.php interface/web/mail/list/mail_get.list.php interface/web/mail/list/mail_mailinglist.list.php interface/web/mail/list/mail_relay_recipient.list.php interface/web/mail/list/mail_spamfilter.list.php interface/web/mail/list/mail_transport.list.php interface/web/mail/list/mail_user.list.php interface/web/mail/list/mail_user_filter.list.php interface/web/mail/list/mail_user_stats.list.php interface/web/mail/list/mail_whitelist.list.php interface/web/mail/list/spamfilter_blacklist.list.php interface/web/mail/list/spamfilter_config.list.php interface/web/mail/list/spamfilter_policy.list.php interface/web/mail/list/spamfilter_users.list.php interface/web/mail/list/spamfilter_whitelist.list.php interface/web/mail/list/user_quota_stats.list.php interface/web/mail/mail_alias_del.php interface/web/mail/mail_alias_edit.php interface/web/mail/mail_alias_list.php interface/web/mail/mail_aliasdomain_del.php interface/web/mail/mail_aliasdomain_edit.php interface/web/mail/mail_aliasdomain_list.php interface/web/mail/mail_blacklist_del.php interface/web/mail/mail_blacklist_edit.php interface/web/mail/mail_blacklist_list.php interface/web/mail/mail_content_filter_del.php interface/web/mail/mail_content_filter_edit.php interface/web/mail/mail_content_filter_list.php interface/web/mail/mail_domain_catchall_del.php interface/web/mail/mail_domain_catchall_edit.php interface/web/mail/mail_domain_catchall_list.php interface/web/mail/mail_domain_del.php interface/web/mail/mail_domain_dkim_create.php interface/web/mail/mail_domain_edit.php interface/web/mail/mail_domain_list.php interface/web/mail/mail_forward_del.php interface/web/mail/mail_forward_edit.php interface/web/mail/mail_forward_list.php interface/web/mail/mail_get_del.php interface/web/mail/mail_get_edit.php interface/web/mail/mail_get_list.php interface/web/mail/mail_mailinglist_del.php interface/web/mail/mail_mailinglist_edit.php interface/web/mail/mail_mailinglist_list.php interface/web/mail/mail_relay_recipient_del.php interface/web/mail/mail_relay_recipient_edit.php interface/web/mail/mail_relay_recipient_list.php interface/web/mail/mail_spamfilter_del.php interface/web/mail/mail_spamfilter_edit.php interface/web/mail/mail_spamfilter_list.php interface/web/mail/mail_transport_del.php interface/web/mail/mail_transport_edit.php interface/web/mail/mail_transport_list.php interface/web/mail/mail_user_del.php interface/web/mail/mail_user_edit.php interface/web/mail/mail_user_filter_del.php interface/web/mail/mail_user_filter_edit.php interface/web/mail/mail_user_list.php interface/web/mail/mail_user_stats.php interface/web/mail/mail_whitelist_del.php interface/web/mail/mail_whitelist_edit.php interface/web/mail/mail_whitelist_list.php interface/web/mail/mailinglist.php interface/web/mail/spamfilter_blacklist_del.php interface/web/mail/spamfilter_blacklist_edit.php interface/web/mail/spamfilter_blacklist_list.php interface/web/mail/spamfilter_config_del.php interface/web/mail/spamfilter_config_edit.php interface/web/mail/spamfilter_config_list.php interface/web/mail/spamfilter_policy_del.php interface/web/mail/spamfilter_policy_edit.php interface/web/mail/spamfilter_policy_list.php interface/web/mail/spamfilter_users_del.php interface/web/mail/spamfilter_users_edit.php interface/web/mail/spamfilter_users_list.php interface/web/mail/spamfilter_whitelist_del.php interface/web/mail/spamfilter_whitelist_edit.php interface/web/mail/spamfilter_whitelist_list.php interface/web/mail/user_quota_stats.php interface/web/mail/webmailer.php interface/web/mailuser/form/mail_user_autoresponder.tform.php interface/web/mailuser/form/mail_user_cc.tform.php interface/web/mailuser/form/mail_user_filter.tform.php interface/web/mailuser/form/mail_user_password.tform.php interface/web/mailuser/form/mail_user_spamfilter.tform.php interface/web/mailuser/index.php interface/web/mailuser/lib/admin.conf.php interface/web/mailuser/lib/module.conf.php interface/web/mailuser/lib/remote.conf.php interface/web/mailuser/list/mail_user_filter.list.php interface/web/mailuser/mail_user_autoresponder_edit.php interface/web/mailuser/mail_user_cc_edit.php interface/web/mailuser/mail_user_filter_del.php interface/web/mailuser/mail_user_filter_edit.php interface/web/mailuser/mail_user_filter_list.php interface/web/mailuser/mail_user_password_edit.php interface/web/mailuser/mail_user_spamfilter_edit.php interface/web/monitor/datalog_del.php interface/web/monitor/datalog_list.php interface/web/monitor/lib/admin.conf.php interface/web/monitor/lib/module.conf.php interface/web/monitor/list/datalog.list.php interface/web/monitor/list/log.list.php interface/web/monitor/log_del.php interface/web/monitor/log_list.php interface/web/monitor/show_data.php interface/web/monitor/show_log.php interface/web/monitor/show_monit.php interface/web/monitor/show_munin.php interface/web/monitor/show_sys_state.php interface/web/nav.php interface/web/remote/index.php interface/web/remote/json.php interface/web/remote/monitor.php interface/web/sites/ajax_get_ip.php interface/web/sites/ajax_get_json.php interface/web/sites/aps_availablepackages_list.php interface/web/sites/aps_cron_apscrawler_if.php interface/web/sites/aps_do_operation.php interface/web/sites/aps_install_package.php interface/web/sites/aps_installedpackages_list.php interface/web/sites/aps_packagedetails_show.php interface/web/sites/aps_update_packagelist.php interface/web/sites/cron_del.php interface/web/sites/cron_edit.php interface/web/sites/cron_list.php interface/web/sites/database_del.php interface/web/sites/database_edit.php interface/web/sites/database_list.php interface/web/sites/database_phpmyadmin.php interface/web/sites/database_user_del.php interface/web/sites/database_user_edit.php interface/web/sites/database_user_list.php interface/web/sites/form/cron.tform.php interface/web/sites/form/database.tform.php interface/web/sites/form/database_user.tform.php interface/web/sites/form/ftp_user.tform.php interface/web/sites/form/shell_user.tform.php interface/web/sites/form/web_aliasdomain.tform.php interface/web/sites/form/web_domain.tform.php interface/web/sites/form/web_folder.tform.php interface/web/sites/form/web_folder_user.tform.php interface/web/sites/form/web_subdomain.tform.php interface/web/sites/form/web_vhost_subdomain.tform.php interface/web/sites/form/webdav_user.tform.php interface/web/sites/ftp_user_del.php interface/web/sites/ftp_user_edit.php interface/web/sites/ftp_user_list.php interface/web/sites/lib/admin.conf.php interface/web/sites/lib/module.conf.php interface/web/sites/lib/remote.conf.php interface/web/sites/list/aps_availablepackages.list.php interface/web/sites/list/aps_installedpackages.list.php interface/web/sites/list/cron.list.php interface/web/sites/list/database.list.php interface/web/sites/list/database_user.list.php interface/web/sites/list/ftp_user.list.php interface/web/sites/list/shell_user.list.php interface/web/sites/list/user_quota_stats.list.php interface/web/sites/list/web_aliasdomain.list.php interface/web/sites/list/web_domain.list.php interface/web/sites/list/web_folder.list.php interface/web/sites/list/web_folder_user.list.php interface/web/sites/list/web_sites_stats.list.php interface/web/sites/list/web_subdomain.list.php interface/web/sites/list/web_vhost_subdomain.list.php interface/web/sites/list/webdav_user.list.php interface/web/sites/shell_user_del.php interface/web/sites/shell_user_edit.php interface/web/sites/shell_user_list.php interface/web/sites/user_quota_stats.php interface/web/sites/web_aliasdomain_del.php interface/web/sites/web_aliasdomain_edit.php interface/web/sites/web_aliasdomain_list.php interface/web/sites/web_domain_del.php interface/web/sites/web_domain_edit.php interface/web/sites/web_domain_list.php interface/web/sites/web_folder_del.php interface/web/sites/web_folder_edit.php interface/web/sites/web_folder_list.php interface/web/sites/web_folder_user_del.php interface/web/sites/web_folder_user_edit.php interface/web/sites/web_folder_user_list.php interface/web/sites/web_sites_stats.php interface/web/sites/web_subdomain_del.php interface/web/sites/web_subdomain_edit.php interface/web/sites/web_subdomain_list.php interface/web/sites/web_vhost_subdomain_del.php interface/web/sites/web_vhost_subdomain_edit.php interface/web/sites/web_vhost_subdomain_list.php interface/web/sites/webdav_user_del.php interface/web/sites/webdav_user_edit.php interface/web/sites/webdav_user_list.php interface/web/tools/dns_import_tupa.php interface/web/tools/form/interface_settings.tform.php interface/web/tools/form/tpl_default.tform.php interface/web/tools/form/user_settings.tform.php interface/web/tools/import_ispconfig.php interface/web/tools/import_plesk.php interface/web/tools/import_vpopmail.php interface/web/tools/index.php interface/web/tools/interface_settings.php interface/web/tools/lib/interface.d/tpl_default.menu.php interface/web/tools/lib/menu.d/import.menu.php interface/web/tools/lib/menu.d/resync.menu.php interface/web/tools/lib/menu.d/statistics.menu.php interface/web/tools/lib/module.conf.php interface/web/tools/resync.php interface/web/tools/tpl_default.php interface/web/tools/user_settings.php interface/web/vm/ajax_get_ip.php interface/web/vm/form/openvz_ip.tform.php interface/web/vm/form/openvz_ostemplate.tform.php interface/web/vm/form/openvz_template.tform.php interface/web/vm/form/openvz_vm.tform.php interface/web/vm/lib/admin.conf.php interface/web/vm/lib/module.conf.php interface/web/vm/lib/remote.conf.php interface/web/vm/list/openvz_ip.list.php interface/web/vm/list/openvz_ostemplate.list.php interface/web/vm/list/openvz_template.list.php interface/web/vm/list/openvz_vm.list.php interface/web/vm/openvz_action.php interface/web/vm/openvz_ip_del.php interface/web/vm/openvz_ip_edit.php interface/web/vm/openvz_ip_list.php interface/web/vm/openvz_ostemplate_del.php interface/web/vm/openvz_ostemplate_edit.php interface/web/vm/openvz_ostemplate_list.php interface/web/vm/openvz_template_del.php interface/web/vm/openvz_template_edit.php interface/web/vm/openvz_template_list.php interface/web/vm/openvz_vm_del.php interface/web/vm/openvz_vm_edit.php interface/web/vm/openvz_vm_list.php remoting_client/examples/client_add.php remoting_client/examples/client_change_password.php remoting_client/examples/client_delete.php remoting_client/examples/client_delete_everything.php remoting_client/examples/client_get.php remoting_client/examples/client_get_by_username.php remoting_client/examples/client_get_id.php remoting_client/examples/client_get_sites_by_user.php remoting_client/examples/client_templates_get_all.php remoting_client/examples/client_update.php remoting_client/examples/dns_a_add.php remoting_client/examples/dns_a_delete.php remoting_client/examples/dns_a_get.php remoting_client/examples/dns_a_update.php remoting_client/examples/dns_aaaa_add.php remoting_client/examples/dns_aaaa_delete.php remoting_client/examples/dns_aaaa_get.php remoting_client/examples/dns_aaaa_update.php remoting_client/examples/dns_alias_add.php remoting_client/examples/dns_alias_delete.php remoting_client/examples/dns_alias_get.php remoting_client/examples/dns_alias_update.php remoting_client/examples/dns_cname_add.php remoting_client/examples/dns_cname_delete.php remoting_client/examples/dns_cname_get.php remoting_client/examples/dns_cname_update.php remoting_client/examples/dns_hinfo_add.php remoting_client/examples/dns_hinfo_delete.php remoting_client/examples/dns_hinfo_get.php remoting_client/examples/dns_hinfo_update.php remoting_client/examples/dns_mx_add.php remoting_client/examples/dns_mx_delete.php remoting_client/examples/dns_mx_get.php remoting_client/examples/dns_mx_update.php remoting_client/examples/dns_ns_add.php remoting_client/examples/dns_ns_delete.php remoting_client/examples/dns_ns_get.php remoting_client/examples/dns_ns_update.php remoting_client/examples/dns_ptr_add.php remoting_client/examples/dns_ptr_delete.php remoting_client/examples/dns_ptr_get.php remoting_client/examples/dns_ptr_update.php remoting_client/examples/dns_rp_add.php remoting_client/examples/dns_rp_delete.php remoting_client/examples/dns_rp_get.php remoting_client/examples/dns_rp_update.php remoting_client/examples/dns_rr_get_all_by_zone.php remoting_client/examples/dns_srv_add.php remoting_client/examples/dns_srv_delete.php remoting_client/examples/dns_srv_get.php remoting_client/examples/dns_srv_update.php remoting_client/examples/dns_txt_add.php remoting_client/examples/dns_txt_delete.php remoting_client/examples/dns_txt_get.php remoting_client/examples/dns_txt_update.php remoting_client/examples/dns_zone_add.php remoting_client/examples/dns_zone_delete.php remoting_client/examples/dns_zone_get.php remoting_client/examples/dns_zone_get_by_user.php remoting_client/examples/dns_zone_set_status.php remoting_client/examples/dns_zone_update.php remoting_client/examples/domains_domain_add.php remoting_client/examples/domains_domain_delete.php remoting_client/examples/domains_domain_get.php remoting_client/examples/domains_get_all_by_user.php remoting_client/examples/get_function_list.php remoting_client/examples/login.php remoting_client/examples/logout.php remoting_client/examples/mail_alias_add.php remoting_client/examples/mail_alias_delete.php remoting_client/examples/mail_alias_get.php remoting_client/examples/mail_alias_update.php remoting_client/examples/mail_blacklist_add.php remoting_client/examples/mail_blacklist_delete.php remoting_client/examples/mail_blacklist_get.php remoting_client/examples/mail_blacklist_update.php remoting_client/examples/mail_catchall_add.php remoting_client/examples/mail_catchall_delete.php remoting_client/examples/mail_catchall_get.php remoting_client/examples/mail_catchall_update.php remoting_client/examples/mail_domain_add.php remoting_client/examples/mail_domain_delete.php remoting_client/examples/mail_domain_get.php remoting_client/examples/mail_domain_get_by_domain.php remoting_client/examples/mail_domain_set_status.php remoting_client/examples/mail_domain_update.php remoting_client/examples/mail_fetchmail_add.php remoting_client/examples/mail_fetchmail_delete.php remoting_client/examples/mail_fetchmail_get.php remoting_client/examples/mail_fetchmail_update.php remoting_client/examples/mail_filter_add.php remoting_client/examples/mail_filter_delete.php remoting_client/examples/mail_filter_get.php remoting_client/examples/mail_filter_update.php remoting_client/examples/mail_forward_add.php remoting_client/examples/mail_forward_delete.php remoting_client/examples/mail_forward_get.php remoting_client/examples/mail_forward_update.php remoting_client/examples/mail_mailinglist_add.php remoting_client/examples/mail_mailinglist_delete.php remoting_client/examples/mail_mailinglist_get.php remoting_client/examples/mail_mailinglist_update.php remoting_client/examples/mail_policy_add.php remoting_client/examples/mail_policy_delete.php remoting_client/examples/mail_policy_get.php remoting_client/examples/mail_policy_update.php remoting_client/examples/mail_spamfilter_blacklist_add.php remoting_client/examples/mail_spamfilter_blacklist_delete.php remoting_client/examples/mail_spamfilter_blacklist_get.php remoting_client/examples/mail_spamfilter_blacklist_update.php remoting_client/examples/mail_spamfilter_user_add.php remoting_client/examples/mail_spamfilter_user_delete.php remoting_client/examples/mail_spamfilter_user_get.php remoting_client/examples/mail_spamfilter_user_update.php remoting_client/examples/mail_spamfilter_whitelist_add.php remoting_client/examples/mail_spamfilter_whitelist_delete.php remoting_client/examples/mail_spamfilter_whitelist_get.php remoting_client/examples/mail_spamfilter_whitelist_update.php remoting_client/examples/mail_transport_add.php remoting_client/examples/mail_transport_delete.php remoting_client/examples/mail_transport_get.php remoting_client/examples/mail_transport_update.php remoting_client/examples/mail_user_add.php remoting_client/examples/mail_user_delete.php remoting_client/examples/mail_user_filter_add.php remoting_client/examples/mail_user_filter_delete.php remoting_client/examples/mail_user_filter_get.php remoting_client/examples/mail_user_filter_update.php remoting_client/examples/mail_user_get.php remoting_client/examples/mail_user_update.php remoting_client/examples/mail_whitelist_add.php remoting_client/examples/mail_whitelist_delete.php remoting_client/examples/mail_whitelist_get.php remoting_client/examples/mail_whitelist_update.php remoting_client/examples/openvz_get_free_ip.php remoting_client/examples/openvz_ip_add.php remoting_client/examples/openvz_ip_delete.php remoting_client/examples/openvz_ip_get.php remoting_client/examples/openvz_ip_update.php remoting_client/examples/openvz_ostemplate_add.php remoting_client/examples/openvz_ostemplate_delete.php remoting_client/examples/openvz_ostemplate_get.php remoting_client/examples/openvz_ostemplate_update.php remoting_client/examples/openvz_template_add.php remoting_client/examples/openvz_template_delete.php remoting_client/examples/openvz_template_get.php remoting_client/examples/openvz_template_update.php remoting_client/examples/openvz_vm_add.php remoting_client/examples/openvz_vm_add_from_template.php remoting_client/examples/openvz_vm_delete.php remoting_client/examples/openvz_vm_get.php remoting_client/examples/openvz_vm_get_by_client.php remoting_client/examples/openvz_vm_update.php remoting_client/examples/server_get.php remoting_client/examples/server_get_serverid_by_ip.php remoting_client/examples/sites_cron_add.php remoting_client/examples/sites_cron_delete.php remoting_client/examples/sites_cron_get.php remoting_client/examples/sites_cron_update.php remoting_client/examples/sites_database_add.php remoting_client/examples/sites_database_delete.php remoting_client/examples/sites_database_get.php remoting_client/examples/sites_database_get_all_by_user.php remoting_client/examples/sites_database_update.php remoting_client/examples/sites_database_user_add.php remoting_client/examples/sites_database_user_delete.php remoting_client/examples/sites_database_user_get.php remoting_client/examples/sites_database_user_update.php remoting_client/examples/sites_ftp_user_add.php remoting_client/examples/sites_ftp_user_delete.php remoting_client/examples/sites_ftp_user_get.php remoting_client/examples/sites_ftp_user_update.php remoting_client/examples/sites_shell_user_add.php remoting_client/examples/sites_shell_user_delete.php remoting_client/examples/sites_shell_user_get.php remoting_client/examples/sites_shell_user_update.php remoting_client/examples/sites_web_aliasdomain_add.php remoting_client/examples/sites_web_aliasdomain_delete.php remoting_client/examples/sites_web_aliasdomain_get.php remoting_client/examples/sites_web_aliasdomain_update.php remoting_client/examples/sites_web_domain_add.php remoting_client/examples/sites_web_domain_delete.php remoting_client/examples/sites_web_domain_get.php remoting_client/examples/sites_web_domain_set_status.php remoting_client/examples/sites_web_domain_update.php remoting_client/examples/sites_web_subdomain_add.php remoting_client/examples/sites_web_subdomain_delete.php remoting_client/examples/sites_web_subdomain_get.php remoting_client/examples/sites_web_subdomain_update.php remoting_client/examples/soap-database-add.php server/cron.php server/cron_daily.php server/lib/app.inc.php server/lib/classes/aps_base.inc.php server/lib/classes/aps_installer.inc.php server/lib/classes/cron.d/100-mailbox_stats.inc.php server/lib/classes/cron.d/100-monitor_clamav_log.inc.php server/lib/classes/cron.d/100-monitor_cpu.inc.php server/lib/classes/cron.d/100-monitor_database_size.inc.php server/lib/classes/cron.d/100-monitor_disk_usage.inc.php server/lib/classes/cron.d/100-monitor_email_quota.inc.php server/lib/classes/cron.d/100-monitor_fail2ban.inc.php server/lib/classes/cron.d/100-monitor_hd_quota.inc.php server/lib/classes/cron.d/100-monitor_iptables.inc.php server/lib/classes/cron.d/100-monitor_ispconfig_log.inc.php server/lib/classes/cron.d/100-monitor_ispconfig_version.inc.php server/lib/classes/cron.d/100-monitor_mail_log.inc.php server/lib/classes/cron.d/100-monitor_mail_queue.inc.php server/lib/classes/cron.d/100-monitor_mem_usage.inc.php server/lib/classes/cron.d/100-monitor_mongodb.inc.php server/lib/classes/cron.d/100-monitor_openvz.inc.php server/lib/classes/cron.d/100-monitor_os_version.inc.php server/lib/classes/cron.d/100-monitor_raid.inc.php server/lib/classes/cron.d/100-monitor_rkhunter.inc.php server/lib/classes/cron.d/100-monitor_server.inc.php server/lib/classes/cron.d/100-monitor_services.inc.php server/lib/classes/cron.d/100-monitor_syslog.inc.php server/lib/classes/cron.d/100-monitor_system_update.inc.php server/lib/classes/cron.d/150-awstats.inc.php server/lib/classes/cron.d/150-webalizer.inc.php server/lib/classes/cron.d/200-logfiles.inc.php server/lib/classes/cron.d/300-quota_notify.inc.php server/lib/classes/cron.d/400-openvz.inc.php server/lib/classes/cron.d/500-backup.inc.php server/lib/classes/cron.inc.php server/lib/classes/cronjob.inc.php server/lib/classes/db_mysql.inc.php server/lib/classes/file.inc.php server/lib/classes/functions.inc.php server/lib/classes/getconf.inc.php server/lib/classes/ini_parser.inc.php server/lib/classes/libdatetime.inc.php server/lib/classes/mod_mail_base.inc.php server/lib/classes/modules.inc.php server/lib/classes/monitor_tools.inc.php server/lib/classes/openvz_tools.inc.php server/lib/classes/plugins.inc.php server/lib/classes/services.inc.php server/lib/classes/system.inc.php server/lib/classes/tpl.inc.php server/lib/classes/tpl_cache.inc.php server/lib/classes/tpl_error.inc.php server/lib/classes/tpl_ini.inc.php server/mods-available/client_module.inc.php server/mods-available/cron_module.inc.php server/mods-available/database_module.inc.php server/mods-available/dns_module.inc.php server/mods-available/mail_module.inc.php server/mods-available/monitor_core_module.inc.php server/mods-available/remoteaction_core_module.inc.php server/mods-available/rescue_core_module.inc.php server/mods-available/server_module.inc.php server/mods-available/vm_module.inc.php server/mods-available/web_module.inc.php server/plugins-available/apache2_plugin.inc.php server/plugins-available/apps_vhost_plugin.inc.php server/plugins-available/aps_plugin.inc.php server/plugins-available/backup_plugin.inc.php server/plugins-available/bind_dlz_plugin.inc.php server/plugins-available/bind_plugin.inc.php server/plugins-available/cron_jailkit_plugin.inc.php server/plugins-available/cron_plugin.inc.php server/plugins-available/firewall_plugin.inc.php server/plugins-available/ftpuser_base_plugin.inc.php server/plugins-available/getmail_plugin.inc.php server/plugins-available/iptables_plugin.inc.php server/plugins-available/mail_plugin.inc.php server/plugins-available/mail_plugin_dkim.inc.php server/plugins-available/maildeliver_plugin.inc.php server/plugins-available/maildrop_plugin.inc.php server/plugins-available/mailman_plugin.inc.php server/plugins-available/mongo_clientdb_plugin.inc.php server/plugins-available/mysql_clientdb_plugin.inc.php server/plugins-available/network_settings_plugin.inc.php server/plugins-available/nginx_plugin.inc.php server/plugins-available/nginx_reverseproxy_plugin.inc.php server/plugins-available/openvz_plugin.inc.php server/plugins-available/pma_symlink_plugin.inc.php server/plugins-available/postfix_filter_plugin.inc.php server/plugins-available/postfix_server_plugin.inc.php server/plugins-available/powerdns_plugin.inc.php server/plugins-available/shelluser_base_plugin.inc.php server/plugins-available/shelluser_jailkit_plugin.inc.php server/plugins-available/software_update_plugin.inc.php server/plugins-available/squid_plugin.inc.php server/plugins-available/webmail_symlink_plugin.inc.php server/plugins-available/webserver_plugin.inc.php server/scripts/ispconfig_update.php server/server.php