From 30e8f0d53ee5ec8914d626929834188ce9ecaca1 Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Wed, 25 Jun 2014 15:56:59 +0200 Subject: [PATCH 01/15] rollback of update_domaines to 3.1 version --- src/update_domains.sh | 113 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 106 insertions(+), 7 deletions(-) mode change 100644 => 100755 src/update_domains.sh diff --git a/src/update_domains.sh b/src/update_domains.sh old mode 100644 new mode 100755 index 41694717..89df3bc6 --- a/src/update_domains.sh +++ b/src/update_domains.sh @@ -4,6 +4,7 @@ for CONFIG_FILE in \ /etc/alternc/local.sh \ /usr/lib/alternc/functions.sh \ + /usr/lib/alternc/functions_hosting.sh \ /usr/lib/alternc/functions_dns.sh do if [ ! -r "$CONFIG_FILE" ]; then @@ -18,6 +19,13 @@ stop_if_jobs_locked # Some vars umask 022 LOCK_FILE="/usr/share/alternc/panel/cron.lock" # FIXME doesn't seem clean to be here +OLDIFS="$IFS" +NEWIFS=" " +LOGFORMAT_FILE="/etc/alternc/apache_logformat.conf" +RELOAD_WEB="$(mktemp /tmp/alternc_reload_web.XXXX)" +B="µµ§§" # Strange letters to make split in query + +echo "" > "$RELOAD_WEB" # Somes check before start operations if [ `id -u` -ne 0 ]; then @@ -45,22 +53,113 @@ echo $$ > "$LOCK_FILE" # set sub_domaines.web_action = delete where domaines.dns_action = DELETE mysql_query "update sub_domaines sd, domaines d set sd.web_action = 'DELETE' where sd.domaine = d.domaine and sd.compte=d.compte and d.dns_action = 'DELETE';" -# Launc apache script. If the script said so, reload apache. -if [ $(/usr/lib/alternc/generate_apache_conf.php) -gt 0 ] ; then +# Sub_domaines we want to delete +# sub_domaines.web_action = delete +for sub in $( mysql_query "select concat_ws('$B',lower(sd.type), if(length(sd.sub)>0,concat_ws('.',sd.sub,sd.domaine),sd.domaine)) from sub_domaines sd where web_action ='DELETE';") ; do + host_delete ${sub/$B/ } + mysql_query "delete from sub_domaines where concat_ws('$B',lower(type), if(length(sub)>0,concat_ws('.',sub,domaine),domaine)) = '$sub' and web_action ='DELETE';" + echo 1 > "$RELOAD_WEB" +done + +# Sub domaines we want to update +# sub_domaines.web_action = update and sub_domains.only_dns = false +IFS="$NEWIFS" +mysql_query " +select concat_ws('$IFS',sd.id, lower(sd.type), if(length(sd.sub)>0,concat_ws('.',sd.sub,sd.domaine),sd.domaine), concat_ws('@',m.login,v.value), sd.valeur ) +from sub_domaines sd,membres m,variable v +where sd.compte=m.uid and sd.web_action ='UPDATE' and v.name='mailname_bounce' +;" | while read sdid type domain mail valeur ; do + host_create "$type" "$domain" "$mail" "$valeur" + mysql_query "update sub_domaines sd set web_action='OK',web_result='$?' where sd.id = '$sdid' ; " + echo 1 > "$RELOAD_WEB" +done + +# Domaine to enable +mysql_query "select concat_ws('$IFS',sd.id, lower(sd.type),if(length(sd.sub)>0,concat_ws('.',sd.sub,sd.domaine),sd.domaine),sd.valeur) from sub_domaines sd where sd.enable ='ENABLE' ;"|while read sdid type domain valeur ; do + host_enable "$type" "$domain" "$valeur" + mysql_query "update sub_domaines sd set enable='ENABLED' where sd.id = '$sdid' ;" + echo 1 > "$RELOAD_WEB" +done + +# Domains to disable +mysql_query "select concat_ws('$IFS', sd.id, lower(sd.type),if(length(sd.sub)>0,concat_ws('.',sd.sub,sd.domaine),sd.domaine),sd.valeur) from sub_domaines sd where sd.enable ='DISABLE' ;"|while read sdid type domain valeur ; do + host_disable "$type" "$domain" "$valeur" + mysql_query "update sub_domaines sd set enable='DISABLED' where sd.id = '$sdid' ;" + echo 1 > "$RELOAD_WEB" +done + +# Domains we do not want to be the DNS serveur anymore : +# domaines.dns_action = UPDATE and domaines.gesdns = 0 +for dom in `mysql_query "select domaine from domaines where dns_action = 'UPDATE' and gesdns = 0;"| tr '\n' ' '` +do + dns_delete $dom + mysql_query "update domaines set dns_action = 'OK', dns_result = '$?' where domaine = '$dom'" +done + +# Domains we have to update the dns : +# domaines.dns_action = UPDATE +for dom in `mysql_query "select domaine from domaines where dns_action = 'UPDATE';" | tr '\n' ' '` +do + echo "dns_regenerate : domain=/$dom/" + dns_regenerate $dom + mysql_query "update domaines set dns_action = 'OK', dns_result = '$?' where domaine = '$dom'" +done + +# Domains we want to delete completely, now we do it +# domaines.dns_action = DELETE +for dom in `mysql_query "select domaine from domaines where dns_action = 'DELETE';" | tr '\n' ' '` +do + dns_delete $dom + # Web configurations have already bean cleaned previously + mysql_query "delete from sub_domaines where domaine='$dom'; delete from domaines where domaine='$dom';" +done + +if [ ! -z "$(cat "$RELOAD_WEB")" ] ; then + + # Just to encourage user to use THIS directory and not another one + test -d "$VHOST_MANUALCONF" || mkdir -p "$VHOST_MANUALCONF" + + # Concat the apaches files + tempo=$(mktemp "$VHOST_FILE.XXXXX") + + ( + echo "###BEGIN OF ALTERNC AUTO-GENERATED FILE - DO NOT EDIT MANUALLY###" + # If exists and readable, include conf file "apache_logformat.conf" + # contain LogFormat and CustomLog directives for our Vhosts) + echo "## LogFormat informations" + if [ ! -r "$LOGFORMAT_FILE" ] ; then + echo "## Warning : Cannot read $LOGFORMAT_FILE" + else + echo "Include \"$LOGFORMAT_FILE\"" + fi + find "$VHOST_DIR" -mindepth 2 -type f -iname "*.conf" -print0 | xargs -0 cat + echo "###END OF ALTERNC AUTO-GENERATED FILE - DO NOT EDIT MANUALLY###" + ) > "$tempo" + + if [ $? -ne 0 ] ; then + log_error " web file concatenation failed" + fi + touch "$VHOST_FILE" + if [ ! -w "$VHOST_FILE" ] ; then + log_error "cannot write on $VHOST_FILE" + fi + mv "$tempo" "$VHOST_FILE" # We must reload apache # we assume we run apache on the master /usr/lib/alternc/alternc_reload apache || true - # Launch hooks for apache reload - # In this directory, you can add you remote web server control run-parts --arg=web_reload /usr/lib/alternc/reload.d fi -# Do bind updates -/usr/lib/alternc/generate_bind_conf.php +## FIXME : move the slave part into the /usr/lib/alternc/reload.d directory to be an hook +#for slave in $ALTERNC_SLAVES; do +# if [ "$slave" != "localhost" ]; then +# ssh alternc@$slave alternc_reload 'apache' || true +# fi +#done -rm -f "$LOCK_FILE" "$RELOAD_ZONES" "$INOTIFY_UPDATE_DOMAIN" +rm -f "$LOCK_FILE" "$RELOAD_ZONES" "$RELOAD_WEB" "$INOTIFY_UPDATE_DOMAIN" exit 0 From 5a1f53760e7801b17472aa38e45cdca31d018230 Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Wed, 25 Jun 2014 16:06:48 +0200 Subject: [PATCH 02/15] removing 'not used anymore' --- src/functions_hosting.sh | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/functions_hosting.sh b/src/functions_hosting.sh index 3569de6f..7c163fb5 100644 --- a/src/functions_hosting.sh +++ b/src/functions_hosting.sh @@ -1,8 +1,5 @@ #!/bin/bash -echo Not used anymore -exit 1 - . /usr/lib/alternc/functions.sh TEMPLATE_DIR="/etc/alternc/templates/apache2" From 9c2090ff8b5ad2c94c711a9045b978ad43ce5a07 Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Wed, 25 Jun 2014 16:38:00 +0200 Subject: [PATCH 03/15] ignore redundant entries when not OK on web_action --- bureau/class/m_dom.php | 1 + 1 file changed, 1 insertion(+) diff --git a/bureau/class/m_dom.php b/bureau/class/m_dom.php index 6dcc8283..a51e6b7b 100644 --- a/bureau/class/m_dom.php +++ b/bureau/class/m_dom.php @@ -2170,6 +2170,7 @@ order by // by subdomain $tmp = array(); foreach ($da['sub'] as $sub) { + if ($sub['web_action']!='OK') continue; if (!$sub['only_dns']) { if (!isset($tmp[$sub['fqdn']])) { $tmp[$sub['fqdn']] = 0; From c298cd4aaf60de3183d040b2544b4644767b6639 Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Fri, 4 Jul 2014 12:37:37 +0200 Subject: [PATCH 04/15] fixing bug when installing (bad upgrade check) --- debian/changelog | 6 ++++++ install/mysql.sql | 3 ++- install/upgrades/3.1.0~c.sh | 4 ++-- wheezy/changelog.diff | 6 +++--- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/debian/changelog b/debian/changelog index e6b5a2dd..0f34da76 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,9 @@ +alternc (3.1.2) oldstable; urgency=low + + * fix a bug when installing (doing patches from 3.1~rc) + + -- Benjamin Sonntag Fri, 4 Jul 2014 12:44:12 +0100 + alternc (3.1.1) oldstable; urgency=low * many bugfixed from 3.1 / 3.2 : diff --git a/install/mysql.sql b/install/mysql.sql index 867f117a..251475fc 100644 --- a/install/mysql.sql +++ b/install/mysql.sql @@ -747,4 +747,5 @@ CREATE TABLE IF NOT EXISTS `alternc_status` ( KEY `name` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -INSERT INTO alternc_status SET name='alternc_version',value='3.1.0~b.php'; +INSERT INTO alternc_status SET name='alternc_version',value='3.1.0~c.sh'; + diff --git a/install/upgrades/3.1.0~c.sh b/install/upgrades/3.1.0~c.sh index ab5332f7..fc9cb5ba 100644 --- a/install/upgrades/3.1.0~c.sh +++ b/install/upgrades/3.1.0~c.sh @@ -12,7 +12,7 @@ if [ ! -r "$CONFIG_FILE" ]; then fi if [ `id -u` -ne 0 ]; then - echo "3.0.3~b.sh must be launched as root" + echo "$0 must be launched as root" exit 1 fi @@ -28,5 +28,5 @@ test -d /var/alternc/bind/zones/ || exit 0 cp --no-clobber /var/alternc/bind/zones/* /var/lib/alternc/bind/zones/ # No need to regenerate zone, we are launched by upgrade_check, -# launched by alternc.install, and alternc.install regenerate everything +# launched by alternc.install, and alternc.install regenerate everything # when it end diff --git a/wheezy/changelog.diff b/wheezy/changelog.diff index 14a64f68..d7f5ba6c 100644 --- a/wheezy/changelog.diff +++ b/wheezy/changelog.diff @@ -1,13 +1,13 @@ --- changelog 2014-06-24 13:42:50.234304438 +0200 +++ changelog.wheezy 2014-06-24 13:43:51.978313552 +0200 @@ -1,3 +1,10 @@ -+alternc (3.2.1) stable; urgency=low ++alternc (3.2.2) stable; urgency=low + + * Version identical to 3.1 for Squeeze + * Includes a small dovecot patch / dependency for dovecot 2.0 for Wheezy + + -- Benjamin Sonntag Thu, 28 Mar 2014 18:19:00 +0200 + - alternc (3.1.1) oldstable; urgency=low + alternc (3.1.2) oldstable; urgency=low - * many bugfixed from 3.1 / 3.2 : + * fix a bug when installing (doing patches from 3.1~rc) From 0fa8aa8fc6a709d3987af591af764d20226a69ee Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Fri, 4 Jul 2014 13:17:57 +0200 Subject: [PATCH 05/15] fixing for real the upgrade path --- install/mysql.sql | 3 ++- install/upgrades/{3.2.1~a.sql => 3.1.1~a.sql} | 0 install/upgrades/3.3.0~a.sql | 10 ---------- 3 files changed, 2 insertions(+), 11 deletions(-) rename install/upgrades/{3.2.1~a.sql => 3.1.1~a.sql} (100%) delete mode 100644 install/upgrades/3.3.0~a.sql diff --git a/install/mysql.sql b/install/mysql.sql index 251475fc..5a8c15ee 100644 --- a/install/mysql.sql +++ b/install/mysql.sql @@ -747,5 +747,6 @@ CREATE TABLE IF NOT EXISTS `alternc_status` ( KEY `name` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -INSERT INTO alternc_status SET name='alternc_version',value='3.1.0~c.sh'; +INSERT INTO alternc_status SET name='alternc_version',value='3.1.1~a.sql'; + diff --git a/install/upgrades/3.2.1~a.sql b/install/upgrades/3.1.1~a.sql similarity index 100% rename from install/upgrades/3.2.1~a.sql rename to install/upgrades/3.1.1~a.sql diff --git a/install/upgrades/3.3.0~a.sql b/install/upgrades/3.3.0~a.sql deleted file mode 100644 index 5bed9c5d..00000000 --- a/install/upgrades/3.3.0~a.sql +++ /dev/null @@ -1,10 +0,0 @@ - -ALTER TABLE variable DROP PRIMARY KEY; -ALTER TABLE variable ADD id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST; -ALTER TABLE variable ADD strata enum('DEFAULT','GLOBAL','FQDN', 'FQDN_CREATOR', 'CREATOR', 'MEMBER', 'DOMAIN') NOT NULL DEFAULT 'DEFAULT'; -ALTER TABLE variable ADD strata_id bigint DEFAULT NULL; -ALTER TABLE variable ADD type text DEFAULT ''; -ALTER TABLE variable ADD UNIQUE (name, strata, strata_id); - -ALTER TABLE actions MODIFY COLUMN type enum('CREATE_FILE','FIX_USER','CREATE_DIR','DELETE','MOVE','FIX_DIR','FIX_FILE'); - From fe6b632b740aaa4f120c2bf114626369a53e930c Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Fri, 4 Jul 2014 16:04:17 +0200 Subject: [PATCH 06/15] fixing upgrade from 3.0 / 3.1 / 3.2 --- install/alternc.install | 2 +- install/upgrade_check.sh | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/install/alternc.install b/install/alternc.install index dd82800e..8a43f490 100644 --- a/install/alternc.install +++ b/install/alternc.install @@ -1,4 +1,4 @@ -#!/bin/bash -e +#!/bin/bash # ---------------------------------------------------------------------- # AlternC - Web Hosting System diff --git a/install/upgrade_check.sh b/install/upgrade_check.sh index 026256cb..19e5b637 100755 --- a/install/upgrade_check.sh +++ b/install/upgrade_check.sh @@ -1,4 +1,4 @@ -#!/bin/bash -e +#!/bin/bash # this script will look for upgrade scripts in # /usr/share/alternc/install/upgrades and execute them based on the @@ -31,7 +31,7 @@ then # this is a *version number*, not a *last upgrade script* we have this *border case* if [ "$oldvers" = "3.1" ] then - oldvers="3.1.0~b.php" + oldvers="3.1.0~c.sh" fi else echo "##############################################" @@ -71,7 +71,7 @@ for file in $( ls $extensions | sort -n ) ; do cat $file echo "UPDATE alternc_status SET value='$file' WHERE name='alternc_version';" echo "COMMIT;" - ) | mysql --defaults-file=/etc/alternc/my.cnf + ) | mysql -f --defaults-file=/etc/alternc/my.cnf ;; php) php -q $file From 204cb56326639e5bda9abaea76df44f9bd89a3f7 Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Fri, 4 Jul 2014 16:17:07 +0200 Subject: [PATCH 07/15] mysql accept no argument BEFORE --defaults-file --- install/upgrade_check.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install/upgrade_check.sh b/install/upgrade_check.sh index 19e5b637..02775acf 100755 --- a/install/upgrade_check.sh +++ b/install/upgrade_check.sh @@ -71,7 +71,7 @@ for file in $( ls $extensions | sort -n ) ; do cat $file echo "UPDATE alternc_status SET value='$file' WHERE name='alternc_version';" echo "COMMIT;" - ) | mysql -f --defaults-file=/etc/alternc/my.cnf + ) | mysql --defaults-file=/etc/alternc/my.cnf -f ;; php) php -q $file From 4749974bf1109a83103725c3d04c4e3e662a23c0 Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Fri, 4 Jul 2014 17:00:30 +0200 Subject: [PATCH 08/15] fixing DEBCONF error when upgrading from 1.0 to 3.x : it migrates automatically to /var/www without telling / asking the user --- debian/alternc.config | 2 ++ 1 file changed, 2 insertions(+) diff --git a/debian/alternc.config b/debian/alternc.config index 5544818e..3ebfccf9 100644 --- a/debian/alternc.config +++ b/debian/alternc.config @@ -135,6 +135,8 @@ while [ "$QUEST_STATE" != 0 -a "$QUEST_STATE" != 14 ]; do if [ "x$ALTERNC_LOC" != "x" ]; then ALTERNC_HTML="$ALTERNC_LOC/html" ALTERNC_MAIL="$ALTERNC_LOC/mail" + db_set alternc/alternc_html "$ALTERNC_HTML" + db_set alternc/alternc_mail "$ALTERNC_MAIL" fi # We ask for the hosting name and the FQDN From 5f8dea3c8de015b57195b8937fe7d2ad237790fa Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Fri, 1 Aug 2014 11:59:56 +0200 Subject: [PATCH 09/15] fixing man install properly done now --- Makefile | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 686875c4..9cfa2766 100644 --- a/Makefile +++ b/Makefile @@ -27,7 +27,6 @@ export VERSION build: # gettext are built at runtime, to be able to MERGE them from CORE + MODULES before msgfmt - pod2man --center "" --date "" --release "AlternC" --section=8 man/alternc.install.pod >man/alternc.install.8 install: #install-alternc install-squirrelmail install-roundcube install-upnp install-awstats @@ -78,7 +77,7 @@ install-alternc: install-common install-slave: install-common # Man pages - install -o root -g root -m 644 man/alternc.install.8 $(DESTDIR)/usr/share/man/man8/ + pod2man --center "" --date "" --release "AlternC" --section=8 man/alternc.install.pod >$(DESTDIR)/usr/share/man/man8/alternc.install.8 # Then its modules : From d4d746bce87103aa6b40bd3ec6486e790cb27910 Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Fri, 1 Aug 2014 12:00:17 +0200 Subject: [PATCH 10/15] fixing dovecot configuration for LASTLOGIN variable on DOVECOT2 --- wheezy/95_alternc.conf | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/wheezy/95_alternc.conf b/wheezy/95_alternc.conf index 8cda78d0..c4d66687 100644 --- a/wheezy/95_alternc.conf +++ b/wheezy/95_alternc.conf @@ -9,6 +9,8 @@ protocols = imap pop3 sieve +default_process_limit = 1000 + ## ------------------------------------------------------------------------- ## 10-auth @@ -189,12 +191,22 @@ protocol imap { # list of plugins to load. mail_plugins = quota imap_quota #mail_plugin_dir = /usr/lib/dovecot/modules/imap + mail_max_userip_connections = 500 } service imap { - executable = /usr/lib/alternc/popimap-log-login.sh /usr/lib/dovecot/imap + executable = imap imap-postlogin + vsz_limit = 512M } +service imap-postlogin { + executable = script-login /usr/lib/alternc/popimap-log-login.sh + # the script process runs as the user specified here (v2.0.14+): +# user = $default_internal_user + # this UNIX socket listener must use the same name as given to imap executable + unix_listener imap-postlogin { + } +} # ---------------------------------------------------------------------------- # 20-managesieve.conf From beebd51f375b4fa7fdb7844ac1e45ee81a83dfca Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Thu, 21 Aug 2014 11:37:48 +0200 Subject: [PATCH 11/15] fixing a bug when deleting file (double directory) --- bureau/admin/bro_main.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bureau/admin/bro_main.php b/bureau/admin/bro_main.php index 3c133057..86d30eaa 100644 --- a/bureau/admin/bro_main.php +++ b/bureau/admin/bro_main.php @@ -92,7 +92,7 @@ if (!empty($formu) && $formu) {
- +

user["login"].$R."/"; ?>

    From 81aae4c2f4811f83a4ac0edc779790220f9acca8 Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Fri, 22 Aug 2014 11:04:05 +0200 Subject: [PATCH 12/15] back to our normal code syntax, fixing 'R = ' bug in urls --- bureau/class/m_bro.php | 816 ++++++++++++++++++++--------------------- 1 file changed, 408 insertions(+), 408 deletions(-) diff --git a/bureau/class/m_bro.php b/bureau/class/m_bro.php index 8835a695..5064f738 100644 --- a/bureau/class/m_bro.php +++ b/bureau/class/m_bro.php @@ -46,34 +46,34 @@ class m_bro { /** internal cache */ - var $mime_desc = array(); + var $mime_desc=array(); /** internal cache */ - var $mime_icon = array(); + var $mime_icon=array(); /** internal cache */ - var $mime_type = array(); + var $mime_type=array(); /** Internal cache for viewurl */ - var $cacheurl = array(); + var $cacheurl=array(); /** Font choice in the editor */ - var $l_editor_font = array("Arial, Helvetica, Sans-serif","Times, Bookman, Serif","Courier New, Courier, Fixed"); + var $l_editor_font=array("Arial, Helvetica, Sans-serif","Times, Bookman, Serif","Courier New, Courier, Fixed"); /** font size in the editor */ - var $l_editor_size = array("18px","14px","12px","10px","8px","0.8em","0.9em","1em","1.1em","1.2em"); + var $l_editor_size=array("18px","14px","12px","10px","8px","0.8em","0.9em","1em","1.1em","1.2em"); /** * Constructor **/ function m_bro() { - $this->l_mode = array( 0=>_("1 column, detailed"), 1=>_("2 columns, short"), 2=>_("3 columns, short") ); - $this->l_tgz = array( 0=>_("tgz (Linux)"), 1=>_("tar.bz2 (Linux)"), 2=>_("zip (Windows/Dos)"), 3=>_("tar.Z (Unix)") ); - $this->l_icons = array( 0=>_("No"), 1=>_("Yes") ); - $this->l_createfile = array( 0=>_("Go back to the file manager"), 1=>_("Edit the newly created file") ); + $this->l_mode=array( 0=>_("1 column, detailed"), 1=>_("2 columns, short"), 2=>_("3 columns, short") ); + $this->l_tgz=array( 0=>_("tgz (Linux)"), 1=>_("tar.bz2 (Linux)"), 2=>_("zip (Windows/Dos)"), 3=>_("tar.Z (Unix)") ); + $this->l_icons=array( 0=>_("No"), 1=>_("Yes") ); + $this->l_createfile=array( 0=>_("Go back to the file manager"), 1=>_("Edit the newly created file") ); } /** @@ -81,14 +81,14 @@ class m_bro { * @return array */ function hook_menu() { - $obj = array( - 'title' => _("File browser"), - 'ico' => 'images/folder.png', - 'link' => 'bro_main.php', - 'pos' => 40, - ) ; + $obj=array( + 'title' => _("File browser"), + 'ico' => 'images/folder.png', + 'link' => 'bro_main.php', + 'pos' => 40, + ) ; - return $obj; + return $obj; } @@ -96,45 +96,45 @@ class m_bro { /** * Verifie un dossier relatif au dossier de l'utilisateur courant * - * @param string $dir - * @global m_mem $mem - * @param string $dir Dossier absolu que l'on souhaite vérifier - * @param boolean $strip - * @return false|string Retourne le nom du dossier vérifié, relatif au + * @param string $dir + * @global m_mem $mem + * @param string $dir Dossier absolu que l'on souhaite vérifier + * @param boolean $strip + * @return false|string Retourne le nom du dossier vérifié, relatif au * dossier de l'utilisateur courant, éventuellement corrigé. * ou FALSE si le dossier n'est pas dans le dossier de l'utilisateur. */ - function convertabsolute($dir,$strip = true) { + function convertabsolute($dir,$strip=true) { global $mem; - $root = $this->get_user_root($mem->user["login"]); + $root=$this->get_user_root($mem->user["login"]); // Sauvegarde du chemin de base. - $root_alternc = $root ; + $root_alternc=$root ; // Passage du root en chemin rel (diffrent avec un lien) - $root = realpath($root) ; + $root=realpath($root) ; // separer le chemin entre le repertoire et le fichier - $file = basename($dir); - $dir = dirname($dir); - $dir = realpath($root."/".$dir); + $file=basename($dir); + $dir=dirname($dir); + $dir=realpath($root."/".$dir); // verifier que le repertoire est dans le home de l'usager if (substr($dir,0,strlen($root)) != $root) { return false; } // recomposer le chemin - $dir = $dir . '/' . $file; + $dir=$dir.'/'.$file; # Si on tente de mettre un '..' alors erreur - if ( preg_match("/\/\.\.\//", $dir) || preg_match("/\/\.\.$/", $dir) ) { - return false; - } + if ( preg_match("/\/\.\.\//", $dir) || preg_match("/\/\.\.$/", $dir) ) { + return false; + } if ($strip) { - $dir = substr($dir,strlen($root)); + $dir=substr($dir,strlen($root)); } else { // si on ne strip pas, il faut enlever le chemin rel // et mettre la racine d'alternc pour viter les // problmes de lien depuis /var /alternc ! - $dir = $root_alternc . substr($dir,strlen($root)); + $dir=$root_alternc.substr($dir,strlen($root)); } if (substr($dir,-1) == "/") { return substr($dir,0,strlen($dir)-1); @@ -148,8 +148,8 @@ class m_bro { * * Returns the complete path to the root of the user's directory. * - * @param string $login Username - * @return string Returns the complete path to the root of the user's directory. + * @param string $login Username + * @return string Returns the complete path to the root of the user's directory. */ function get_user_root($login) { return getuserpath(); @@ -164,17 +164,17 @@ class m_bro { * C'est utilise' dans class/m_dom.php quand un utilisateur ajoute un domaine dans son compte * et nous devons savoir quel est le chemin complet vers la racine de son compte.. * - * @global m_admin $admin - * @param int $uid User id. - * @return string Returns the complete path to the root of the user's directory. + * @global m_admin $admin + * @param int $uid User id. + * @return string Returns the complete path to the root of the user's directory. */ function get_userid_root($uid) { global $admin; - $old_enabled = $admin->enabled; - $admin->enabled = true; - $member = $admin->get($uid); - $admin->enabled = $old_enabled; + $old_enabled=$admin->enabled; + $admin->enabled=true; + $member=$admin->get($uid); + $admin->enabled=$old_enabled; return $this->get_user_root($member['login']); } @@ -185,31 +185,31 @@ class m_bro { * * Ce tableau contient tous les paramtres des fichiers du dossier courant * sous la forme d'un tableau index de tableaux associatifs comme suit : - * $a["name"] = nom du fichier / dossier - * $a["size"] = Taille totale du fichier / dossier + sous-dossier - * $a["date"] = Date de dernire modification - * $a["type"] = Type du fichier (1 pour fichier, 0 pour dossier) + * $a["name"]=nom du fichier / dossier + * $a["size"]=Taille totale du fichier / dossier + sous-dossier + * $a["date"]=Date de dernire modification + * $a["type"]=Type du fichier (1 pour fichier, 0 pour dossier) * - * @global m_mysql $db - * @global int $cuid - * @global m_err $err - * @param string $dir Dossier relatif au dossier racine du compte du membre courant - * @param boolean $showdirsize - * @return array Le tableau contenant les fichiers de $dir, et + * @global m_mysql $db + * @global int $cuid + * @global m_err $err + * @param string $dir Dossier relatif au dossier racine du compte du membre courant + * @param boolean $showdirsize + * @return array Le tableau contenant les fichiers de $dir, et */ - function filelist($dir = "", $showdirsize = false) { + function filelist($dir="", $showdirsize=false) { global $db,$cuid,$err; - $db->query("UPDATE browser SET lastdir = '$dir' WHERE uid = '$cuid';"); - $absolute = $this->convertabsolute($dir,false); + $db->query("UPDATE browser SET lastdir='$dir' WHERE uid='$cuid';"); + $absolute=$this->convertabsolute($dir,false); if (!$absolute || !file_exists($absolute)) { $err->raise('bro',_("This directory do not exist")); return false; } - $c = array(); - if ($dir = @opendir($absolute)) { - while (($file = readdir($dir)) !== false) { + $c=array(); + if ($dir=@opendir($absolute)) { + while (($file=readdir($dir)) !== false) { if ($file!="." && $file!="..") { - $c[] = array("name"=>$file, "size"=>$this->fsize($absolute."/".$file, $showdirsize), "date"=>filemtime($absolute."/".$file), "type"=> (!is_dir($absolute."/".$file)) ); + $c[]=array("name"=>$file, "size"=>$this->fsize($absolute."/".$file, $showdirsize), "date"=>filemtime($absolute."/".$file), "type"=> (!is_dir($absolute."/".$file)) ); } } closedir($dir); @@ -225,16 +225,16 @@ class m_bro { * Ce tableau associatif contient les valeurs des champs de la table "browser" * pour l'utilisateur courant. * - * @global m_mysql $db - * @global int $cuid - * @return array Tableau des prfrences de l'utilisateur courant. + * @global m_mysql $db + * @global int $cuid + * @return array Tableau des prfrences de l'utilisateur courant. */ function GetPrefs() { global $db,$cuid; - $db->query("SELECT * FROM browser WHERE uid = '$cuid';"); + $db->query("SELECT * FROM browser WHERE uid='$cuid';"); if ($db->num_rows() == 0) { $db->query("INSERT INTO browser (editsizex, editsizey, listmode, showicons, downfmt, createfile, showtype, uid, editor_font, editor_size) VALUES (70, 21, 0, 0, 0, 0, 0, '$cuid','Arial, Helvetica, Sans-serif','12px');"); - $db->query("SELECT * FROM browser WHERE uid = '$cuid';"); + $db->query("SELECT * FROM browser WHERE uid='$cuid';"); } $db->next_record(); return $db->Record; @@ -242,37 +242,37 @@ class m_bro { /** - Modifie les prfrences de l'utilisateur courant. - * - * @global m_mysql $db - * @global int $cuid - * @param integer $editsizex Taille de l'diteur (nombre de colonnes) - * @param integer $editsizey Taille de l'diteur (nombre de lignes) - * @param integer $listmode Mode d'affichage de la liste des fichiers - * @param integer $showicons Faut-il afficher / cacher les icones des fichiers - * @param integer $downfmt Dans quel format faut-il tlcharger les dossiers compresss - * @param integer $createfile Faut-il editer/revenir au browser aprs cration d'un fichier - * @param integer $showtype Faut-il afficher le type mime des fichiers - * @param integer $editor_font Quelle police faut-il utiliser pour l'diteur - * @param integer $editor_size Quelle taille de police faut-il utiliser pour l'diteur - * @param integer $golastdir Faut-il revenir la racine ou au dernier dossier visit ? - * @return boolean - */ + Modifie les prfrences de l'utilisateur courant. + * + * @global m_mysql $db + * @global int $cuid + * @param integer $editsizex Taille de l'diteur (nombre de colonnes) + * @param integer $editsizey Taille de l'diteur (nombre de lignes) + * @param integer $listmode Mode d'affichage de la liste des fichiers + * @param integer $showicons Faut-il afficher / cacher les icones des fichiers + * @param integer $downfmt Dans quel format faut-il tlcharger les dossiers compresss + * @param integer $createfile Faut-il editer/revenir au browser aprs cration d'un fichier + * @param integer $showtype Faut-il afficher le type mime des fichiers + * @param integer $editor_font Quelle police faut-il utiliser pour l'diteur + * @param integer $editor_size Quelle taille de police faut-il utiliser pour l'diteur + * @param integer $golastdir Faut-il revenir la racine ou au dernier dossier visit ? + * @return boolean + */ function SetPrefs($editsizex, $editsizey, $listmode, $showicons, $downfmt, $createfile, $showtype, $editor_font, $editor_size, $golastdir) { global $db,$cuid; - $editsizex = intval($editsizex); - $editsizey = intval($editsizey); - $listmode = intval($listmode); - $showicons = intval($showicons); - $showtype = intval($showtype); - $downfmt = intval($downfmt); - $createfile = intval($createfile); - $golastdir = intval($golastdir); - $db->query("SELECT * FROM browser WHERE uid = '".intval($cuid)."';"); + $editsizex=intval($editsizex); + $editsizey=intval($editsizey); + $listmode=intval($listmode); + $showicons=intval($showicons); + $showtype=intval($showtype); + $downfmt=intval($downfmt); + $createfile=intval($createfile); + $golastdir=intval($golastdir); + $db->query("SELECT * FROM browser WHERE uid='".intval($cuid)."';"); if ($db->num_rows() == 0) { $db->query("INSERT INTO browser (editsizex, editsizey, listmode, showicons, downfmt, createfile, showtype, uid, editor_font, editor_size, golastdir) VALUES (70, 21, 0, 0, 0, 0, 0, '".intval($cuid)."','Arial, Helvetica, Sans-serif','12px',1);"); } - $db->query("UPDATE browser SET editsizex = '$editsizex', editsizey = '$editsizey', listmode = '$listmode', showicons = '$showicons', downfmt = '$downfmt', createfile = '$createfile', showtype = '$showtype', editor_font = '$editor_font', editor_size = '$editor_size', golastdir = '$golastdir' WHERE uid = '".intval($cuid)."';"); + $db->query("UPDATE browser SET editsizex='$editsizex', editsizey='$editsizey', listmode='$listmode', showicons='$showicons', downfmt='$downfmt', createfile='$createfile', showtype='$showtype', editor_font='$editor_font', editor_size='$editor_size', golastdir='$golastdir' WHERE uid='".intval($cuid)."';"); return true; } @@ -281,20 +281,20 @@ class m_bro { * Retourne le nom du fichier icone associ au fichier donc le nom est $file * Note: Les fichiers icones sont mis en cache sur la page courante. * - * @global array $bro_icon - * @param string $file Fichier dont on souhaite connaitre le fichier icone - * @return string Fichier icone correspondant. + * @global array $bro_icon + * @param string $file Fichier dont on souhaite connaitre le fichier icone + * @return string Fichier icone correspondant. */ function icon($file) { global $bro_icon; if (!strpos($file,".") && substr($file,0,1)!=".") { return "file.png"; } - $t = explode(".",$file); + $t=explode(".",$file); if (!is_array($t)) - $ext = $t; + $ext=$t; else - $ext = $t[count($t)-1]; + $ext=$t[count($t)-1]; // Now seek the extension if (!isset($bro_icon[$ext]) || ! $bro_icon[$ext]) { return "file.png"; @@ -309,20 +309,20 @@ class m_bro { * Note: Les types mimes sont mis en cache sur la page courante. * Le type mime est dtermin d'aprs l'extension du fichier. * - * @global array $bro_type - * @param string $file Fichier dont on souhaite connaitre le type mime - * @return string Type mime / Sous type du fichier demand + * @global array $bro_type + * @param string $file Fichier dont on souhaite connaitre le type mime + * @return string Type mime / Sous type du fichier demand */ function mime($file) { global $bro_type; if (!strpos($file,".") && substr($file,0,1)!=".") { return "File"; } - $t = explode(".",$file); + $t=explode(".",$file); if (!is_array($t)) - $ext = $t; + $ext=$t; else - $ext = $t[count($t)-1]; + $ext=$t[count($t)-1]; // Now seek the extension if (empty($bro_type[$ext])) { return "File"; @@ -337,17 +337,17 @@ class m_bro { * si $file est un dossier, retourne la taille de ce dossier et de tous * ses sous dossiers. * - * @param string $file Fichier dont on souhaite connaitre la taille - * @param boolean $showdirsize Recursively compute the directory size. - * @return integer Taille du fichier en octets. - * @return int|string + * @param string $file Fichier dont on souhaite connaitre la taille + * @param boolean $showdirsize Recursively compute the directory size. + * @return integer Taille du fichier en octets. + * @return int|string */ - function fsize($file, $showdirsize = false) { + function fsize($file, $showdirsize=false) { if (is_dir($file)) { if ($showdirsize) { - return $this->dirsize($file); + return $this->dirsize($file); } else { - return "-"; + return "-"; } } else { return filesize($file); @@ -358,23 +358,23 @@ class m_bro { /** * Returns the size of a directory, by adding all it's files sizes * - * @param string $dir The directory whose size we want to compute - * @return integer The total size in bytes. + * @param string $dir The directory whose size we want to compute + * @return integer The total size in bytes. */ function dirsize($dir) { - $totalsize = 0; + $totalsize=0; - if ($handle = opendir($dir)) { - while (false !== ($file = readdir($handle))) { - $nextpath = $dir . '/' . $file; + if ($handle=opendir($dir)) { + while (false !== ($file=readdir($handle))) { + $nextpath=$dir.'/'.$file; if ($file != '.' && $file != '..' && !is_link($nextpath)) { - if (is_dir($nextpath)) { - $totalsize += $this->dirsize($nextpath); - } elseif (is_file ($nextpath)) { - $totalsize += filesize($nextpath); - } - } + if (is_dir($nextpath)) { + $totalsize += $this->dirsize($nextpath); + } elseif (is_file ($nextpath)) { + $totalsize += filesize($nextpath); + } + } } closedir($handle); } @@ -385,24 +385,24 @@ class m_bro { /** * Crée le dossier $file dans le dossier (parent) $dir * - * @global m_mysql $db - * @global int $cuid - * @global m_err $err - * @param string $dir Dossier dans lequel on veut crer un sous-dossier - * @param string $file Nom du dossier à créer - * @return boolean TRUE si le dossier a été créé, FALSE si une erreur s'est produite. + * @global m_mysql $db + * @global int $cuid + * @global m_err $err + * @param string $dir Dossier dans lequel on veut crer un sous-dossier + * @param string $file Nom du dossier à créer + * @return boolean TRUE si le dossier a été créé, FALSE si une erreur s'est produite. */ function CreateDir($dir,$file) { global $db,$cuid,$err; - $file = ssla($file); - $absolute = $this->convertabsolute($dir."/".$file,false); + $file=ssla($file); + $absolute=$this->convertabsolute($dir."/".$file,false); #echo "$absolute"; if ($absolute && (!file_exists($absolute))) { if (!mkdir($absolute,00777,true)) { $err->raise("bro",_("Cannot create the requested directory. Please check the permissions")); return false; } - $db->query("UPDATE browser SET crff = 1 WHERE uid = '$cuid';"); + $db->query("UPDATE browser SET crff=1 WHERE uid='$cuid';"); return true; } else { $err->raise("bro",_("File or folder name is incorrect")); @@ -414,17 +414,17 @@ class m_bro { /** * Crée un fichier vide dans un dossier * - * @global m_mysql $db - * @global m_err $err - * @global int $cuid - * @param string $dir Dossier dans lequel on veut crer un sous-dossier - * @param string $file Nom du dossier à créer - * @return boolean TRUE si le dossier a été créé, FALSE si une erreur s'est produite. + * @global m_mysql $db + * @global m_err $err + * @global int $cuid + * @param string $dir Dossier dans lequel on veut crer un sous-dossier + * @param string $file Nom du dossier à créer + * @return boolean TRUE si le dossier a été créé, FALSE si une erreur s'est produite. */ function CreateFile($dir,$file) { global $db,$err,$cuid; - $file = ssla($file); - $absolute = $this->convertabsolute($dir."/".$file,false); + $file=ssla($file); + $absolute=$this->convertabsolute($dir."/".$file,false); if (!$absolute || file_exists($absolute)) { $err->raise("bro",_("File or folder name is incorrect")); return false; @@ -435,7 +435,7 @@ class m_bro { return false; } } - $db->query("UPDATE browser SET crff = 0 WHERE uid = '$cuid';"); + $db->query("UPDATE browser SET crff=0 WHERE uid='$cuid';"); return true; } @@ -443,22 +443,22 @@ class m_bro { /** * Efface les fichiers du tableau $file_list dans le dossier $R * - * @global m_err $err - * @global m_mem $mem - * @param array $file_list Liste des fichiers effacer. - * @param string $R Dossier dans lequel on efface les fichiers - * @return boolean TRUE si les fichiers ont t effacs, FALSE si une erreur s'est produite. + * @global m_err $err + * @global m_mem $mem + * @param array $file_list Liste des fichiers effacer. + * @param string $R Dossier dans lequel on efface les fichiers + * @return boolean TRUE si les fichiers ont t effacs, FALSE si une erreur s'est produite. */ function DeleteFile($file_list,$R) { global $err, $mem; - $root = realpath(getuserpath()); - $absolute = $this->convertabsolute($R,false); + $root=realpath(getuserpath()); + $absolute=$this->convertabsolute($R,false); if (!$absolute && strpos($root,$absolute) === 0 && strlen($absolute) > (strlen($root)+1) ) { $err->raise("bro",_("File or folder name is incorrect")); return false; } - for ($i = 0;$i_delete($absolute."/".$file_list[$i]); } @@ -470,30 +470,30 @@ class m_bro { /** * Renomme les fichier de $old du dossier $R en $new * - * @global m_err $err - * @param string $R Dossier dans lequel se trouve les fichiers renommer. - * @param array $old Ancien nom des fichiers - * @param array $new Nouveau nom des fichiers - * @return boolean TRUE si les fichiers ont t renomms, FALSE si une erreur s'est produite. + * @global m_err $err + * @param string $R Dossier dans lequel se trouve les fichiers renommer. + * @param array $old Ancien nom des fichiers + * @param array $new Nouveau nom des fichiers + * @return boolean TRUE si les fichiers ont t renomms, FALSE si une erreur s'est produite. */ function RenameFile($R,$old,$new) { global $err; - $absolute = $this->convertabsolute($R,false); + $absolute=$this->convertabsolute($R,false); if (!$absolute) { $err->raise("bro",_("File or folder name is incorrect")); return false; } - $alea = ".".time().rand(1000,9999); - for ($i = 0;$iconvertabsolute($old,false); + $old=$this->convertabsolute($old,false); if (!$old) { $err->raise("bro",_("File or folder name is incorrect")); return false; } if ($new[0] != '/') { - $new = $old . '/' . $new; + $new=$old.'/'.$new; } - $new = $this->convertabsolute($new,false); + $new=$this->convertabsolute($new,false); if (!$new) { $err->raise("bro",_("File or folder name is incorrect")); @@ -531,11 +531,11 @@ class m_bro { $err->raise("bro",_("You cannot move or copy a file to the same folder")); return false; } - for ($i = 0;$iraise("bro", "error renaming $old/$d[$i] -> $new/$d[$i]"); + for ($i=0;$iraise("bro", "error renaming $old/$d[$i] -> $new/$d[$i]"); } } return true; @@ -545,33 +545,33 @@ class m_bro { /** * Change les droits d'acces aux fichier de $d du dossier $R en $p * - * @global m_err $err - * @param string $R Dossier dans lequel se trouve les fichiers renommer. - * @param boolean $verbose Shall we 'echo' what we did ? - * @return boolean TRUE Si les fichiers ont t renomms, FALSE si une erreur s'est produite. + * @global m_err $err + * @param string $R Dossier dans lequel se trouve les fichiers renommer. + * @param boolean $verbose Shall we 'echo' what we did ? + * @return boolean TRUE Si les fichiers ont t renomms, FALSE si une erreur s'est produite. */ - function ChangePermissions($R,$d,$perm,$verbose = false) { + function ChangePermissions($R,$d,$perm,$verbose=false) { global $err; - $absolute = $this->convertabsolute($R,false); + $absolute=$this->convertabsolute($R,false); if (!$absolute) { $err->raise("bro",_("File or folder name is incorrect")); return false; } - for ($i = 0;$iconvertabsolute($R,false); + $absolute=$this->convertabsolute($R,false); if (!$absolute) { $err->raise("bro",_("File or folder name is incorrect")); return false; } if (!strpos($_FILES['userfile']['name'],"/")) { - if ($_FILES['userfile']['error'] == UPLOAD_ERR_OK && is_uploaded_file($_FILES['userfile']['tmp_name'])) { - if (!file_exists($absolute."/".$_FILES['userfile']['name'])) { - @touch($absolute."/".$_FILES['userfile']['name']); - } - if (@move_uploaded_file($_FILES['userfile']['tmp_name'], $absolute."/".$_FILES['userfile']['name'])) { - $action->fix_file($absolute."/".$_FILES['userfile']['name']); + if ($_FILES['userfile']['error'] == UPLOAD_ERR_OK && is_uploaded_file($_FILES['userfile']['tmp_name'])) { + if (!file_exists($absolute."/".$_FILES['userfile']['name'])) { + @touch($absolute."/".$_FILES['userfile']['name']); + } + if (@move_uploaded_file($_FILES['userfile']['tmp_name'], $absolute."/".$_FILES['userfile']['name'])) { + $action->fix_file($absolute."/".$_FILES['userfile']['name']); return $absolute."/".$_FILES['userfile']['name']; } else { $err->raise("bro",_("Cannot create the requested file. Please check the permissions")); return false; } } else { - // there was an error, raise it + // there was an error, raise it $err->log("bro","uploadfile","Problem when uploading a file"); - switch ( $_FILES['userfile']['error'] ) { - case UPLOAD_ERR_INI_SIZE: - $erstr = _("The uploaded file exceeds the max file size allowed"); - break; - case UPLOAD_ERR_FORM_SIZE: - case UPLOAD_ERR_PARTIAL: - case UPLOAD_ERR_NO_FILE: - case UPLOAD_ERR_NO_TMP_DIR: - case UPLOAD_ERR_CANT_WRITE: - case UPLOAD_ERR_EXTENSION: - default: - $erstr = _("Undefined error ").$_FILES['userfile']['error']; - break; - } - $err->raise("bro",_("Error during the upload of the file: ").$erstr); - return false; + switch ( $_FILES['userfile']['error'] ) { + case UPLOAD_ERR_INI_SIZE: + $erstr=_("The uploaded file exceeds the max file size allowed"); + break; + case UPLOAD_ERR_FORM_SIZE: + case UPLOAD_ERR_PARTIAL: + case UPLOAD_ERR_NO_FILE: + case UPLOAD_ERR_NO_TMP_DIR: + case UPLOAD_ERR_CANT_WRITE: + case UPLOAD_ERR_EXTENSION: + default: + $erstr=_("Undefined error ").$_FILES['userfile']['error']; + break; + } + $err->raise("bro",_("Error during the upload of the file: ").$erstr); + return false; } } return $absolute."/".$_FILES['userfile']['name']; @@ -640,44 +640,44 @@ class m_bro { /** * Extract an archive by using GNU and non-GNU tools * - * @global m_err $err - * @global int $cuid - * @global m_mem $mem - * @global m_action $action - * @param string $file Full or relative path to the archive - * @param string $dest Path of the extract destination, the - * same directory as the archive by default - * @return integer|null != 0 on error + * @global m_err $err + * @global int $cuid + * @global m_mem $mem + * @global m_action $action + * @param string $file Full or relative path to the archive + * @param string $dest Path of the extract destination, the + * same directory as the archive by default + * @return integer|null != 0 on error */ - function ExtractFile($file, $dest = null) { + function ExtractFile($file, $dest=null) { global $err,$cuid,$mem,$action; - $file = $this->convertabsolute($file,false); + $file=$this->convertabsolute($file,false); if (is_null($dest)) { - $dest = dirname($file); + $dest=dirname($file); } else { - $dest = $this->convertabsolute($dest,false); + $dest=$this->convertabsolute($dest,false); } if (!$file || !$dest) { $err->raise("bro",_("File or folder name is incorrect")); return 1; } - $file = escapeshellarg($file); - $dest_to_fix = $dest; - $dest = escapeshellarg($dest); - #$dest_to_fix = str_replace(getuserpath(),'',$dest); + $file=escapeshellarg($file); + $dest_to_fix=$dest; + $dest=escapeshellarg($dest); + #$dest_to_fix=str_replace(getuserpath(),'',$dest); // TODO new version of tar supports `tar xf ...` so there is no - // need to specify the compression format + // need to specify the compression format exec("tar -xf $file -C $dest", $void, $ret); if ($ret) { exec("tar -xjf $file -C $dest", $void, $ret); } if ($ret) { - $cmd = "unzip -o $file -d $dest"; + $cmd="unzip -o $file -d $dest"; exec($cmd, $void, $ret); } if ($ret) { - $cmd = "gunzip $file"; + $cmd="gunzip $file"; exec($cmd, $void, $ret); } if ($ret) { @@ -692,20 +692,20 @@ class m_bro { /** * Copy many files from point A to point B * - * @global m_err $err - * @param array $d List of files to move - * @param string $old - * @param string $new + * @global m_err $err + * @param array $d List of files to move + * @param string $old + * @param string $new * @return boolean */ function CopyFile($d,$old,$new) { global $err; - $old = $this->convertabsolute($old,false); + $old=$this->convertabsolute($old,false); if (!$old) { $err->raise("bro",_("File or folder name is incorrect")); return false; } - $new = $this->convertabsolute($new,false); + $new=$this->convertabsolute($new,false); if (!$new) { $err->raise("bro",_("File or folder name is incorrect")); return false; @@ -714,10 +714,10 @@ class m_bro { $err->raise("bro",_("You cannot move or copy a file to the same folder")); return false; } - for ($i = 0;$iCopyOneFile($old."/".$d[$i],$new); + for ($i=0;$iCopyOneFile($old."/".$d[$i],$new); } } return true; @@ -731,15 +731,15 @@ class m_bro { * * Note that we assume that the inputs have been convertabsolute()'d * - * @global m_err $err - * @param string $src Path or URL - * @param string $dest Absolute path inside the users directory - * @return boolean false on error + * @global m_err $err + * @param string $src Path or URL + * @param string $dest Absolute path inside the users directory + * @return boolean false on error */ - function CopyOneFile($src, $dest) { + function CopyOneFile($src, $dest) { global $err; - $src = escapeshellarg($src); - $dest = escapeshellarg($dest); + $src=escapeshellarg($src); + $dest=escapeshellarg($dest); exec("cp -Rpf $src $dest", $void, $ret); if ($ret) { $err->raise("bro","Errors happened while copying the source to destination. cp return value: %d", $ret); @@ -752,27 +752,27 @@ class m_bro { /** * Affiche le chemin et les liens de la racine au dossier $path * Affiche autant de liens HTML (anchor) que le chemin $path contient de - * niveaux de dossier. Chaque lien est associ la page web $action - * laquelle on ajoute le paramtre R = +Le nom du dossier courant. + * niveaux de dossier. Chaque lien est associ la page web $action + * laquelle on ajoute le paramtre R=+Le nom du dossier courant. * - * @param string $path Dossier vers lequel on trace le chemin - * @param string $action Page web de destination des liens - * @param boolean $justparent - * @return string Le code HTML ainsi obtenu. + * @param string $path Dossier vers lequel on trace le chemin + * @param string $action Page web de destination des liens + * @param boolean $justparent + * @return string Le code HTML ainsi obtenu. */ - function PathList($path,$action, $justparent = false) { - $path = $this->convertabsolute($path,true); - $a = explode("/",$path); - if (!is_array($a)) $a = array($a); - $c = ''; - $R = ''; + function PathList($path,$action, $justparent=false) { + $path=$this->convertabsolute($path,true); + $a=explode("/",$path); + if (!is_array($a)) $a=array($a); + $c=''; + $R=''; if ($justparent) { - return ""; + return ""; } - for($i = 0;$i".$a[$i]." / "; + $R.=$a[$i]."/"; + $c.="".$a[$i]." / "; } } return $c; @@ -785,20 +785,20 @@ class m_bro { * Affiche le contenu du fichier $file dans le dossier $R. Le contenu * du fichier est reformat pour pouvoir entrer dans un champs TextArea * - * @global m_err $err - * @param string $R Dossier dans lequel on cherche le fichier - * @param string $file Fichier dont on souhaite obtenir le contenu. - * @return string|false TRUE si le fichier a bien été mis sur - * echo, ou FALSE si une erreur est survenue. + * @global m_err $err + * @param string $R Dossier dans lequel on cherche le fichier + * @param string $file Fichier dont on souhaite obtenir le contenu. + * @return string|false TRUE si le fichier a bien été mis sur + * echo, ou FALSE si une erreur est survenue. */ function content($R,$file) { global $err; - $absolute = $this->convertabsolute($R,false); + $absolute=$this->convertabsolute($R,false); if (!strpos($file,"/")) { - $absolute .= "/".$file; + $absolute.="/".$file; if (file_exists($absolute)) { - $std = str_replace("<","<",str_replace("&","&",file_get_contents($absolute))); - return $std; + $std=str_replace("<","<",str_replace("&","&",file_get_contents($absolute))); + return $std; } else { $err->raise("bro",_("Cannot read the requested file. Please check the permissions")); return false; @@ -819,43 +819,43 @@ class m_bro { * Return a browsing url if available. * Maintain a url cache (positive AND negative(-) cache) * - * @global m_mysql $db - * @global int $cuid + * @global m_mysql $db + * @global int $cuid * - * @param string $dir Dossier concerné - * @param string $name Fichier dont on souhaite obtenir une URL - * @return string URL concerne, ou FALSE si aucune URL n'est disponible pour ce fichier + * @param string $dir Dossier concerné + * @param string $name Fichier dont on souhaite obtenir une URL + * @return string URL concerne, ou FALSE si aucune URL n'est disponible pour ce fichier */ function viewurl($dir,$name) { global $db,$cuid; // Is it in cache ? - if (substr($dir,0,1) == "/") $dir = substr($dir,1); - if (substr($dir,-1) == "/") $dir = substr($dir,0,-1); - $dir = str_replace("%2F", "/", urlencode($dir)); - $name = urlencode($name); + if (substr($dir,0,1) == "/") $dir=substr($dir,1); + if (substr($dir,-1) == "/") $dir=substr($dir,0,-1); + $dir=str_replace("%2F", "/", urlencode($dir)); + $name=urlencode($name); if (!@$this->cacheurl["d".$dir]) { // On parcours $dir en remontant les / - $end = ""; $beg = $dir; $tofind = true; + $end=""; $beg=$dir; $tofind=true; while ($tofind) { - $db->query("SELECT sub,domaine FROM sub_domaines WHERE compte = '$cuid' - AND type = 0 AND (valeur = '/$beg/' or valeur = '/$beg');"); - $db->next_record(); - if ($db->num_rows()) { - $tofind = false; - $this->cacheurl["d".$dir] = "http://".$db->f("sub").ife($db->f("sub"),".").$db->f("domaine").$end; - } - if (!$beg && $tofind) { - $tofind = false; - $this->cacheurl["d".$dir] = "-"; + $db->query("SELECT sub,domaine FROM sub_domaines WHERE compte='$cuid' + AND type=0 AND (valeur='/$beg/' or valeur='/$beg');"); + $db->next_record(); + if ($db->num_rows()) { + $tofind=false; + $this->cacheurl["d".$dir]="http://".$db->f("sub").ife($db->f("sub"),".").$db->f("domaine").$end; + } + if (!$beg && $tofind) { + $tofind=false; + $this->cacheurl["d".$dir]="-"; // We did not find it ;( - } - if (($tt = strrpos($beg,"/"))!==false) { - $end = substr($beg,$tt).$end; // = /topdir$end so $end starts AND ends with / - $beg = substr($beg,0,$tt); - } else { - $end = "/".$beg.$end; - $beg = "/"; - } + } + if (($tt=strrpos($beg,"/"))!==false) { + $end=substr($beg,$tt).$end; //=/topdir$end so $end starts AND ends with / + $beg=substr($beg,0,$tt); + } else { + $end="/".$beg.$end; + $beg="/"; + } } } if ($this->cacheurl["d".$dir] && $this->cacheurl["d".$dir]!="-") { @@ -867,23 +867,23 @@ class m_bro { /** * - * @global m_mem $mem - * @global m_err $err - * @param string $dir - * @param string $name + * @global m_mem $mem + * @global m_err $err + * @param string $dir + * @param string $name * @return null|boolean */ function can_edit($dir,$name) { global $mem,$err; - $absolute = "$dir/$name"; - $absolute = $this->convertabsolute($absolute,false); + $absolute="$dir/$name"; + $absolute=$this->convertabsolute($absolute,false); if (!$absolute) { $err->raise('bro',_("File not in authorized directory")); include('foot.php'); exit; } - $finfo = finfo_open(FILEINFO_MIME_TYPE); - $mime = finfo_file($finfo,$absolute); + $finfo=finfo_open(FILEINFO_MIME_TYPE); + $mime=finfo_file($finfo,$absolute); if ( substr($mime,0,5) == "text/" || $mime == "application/x-empty" || $mime == "inode/x-empty") { return true; } @@ -894,17 +894,17 @@ class m_bro { /** * Return a HTML snippet representing an extraction function only if the mimetype of $name is supported * - * @param string $name - * @return boolean + * @param string $name + * @return boolean */ function is_extractable($name) { - if ($parts = explode(".", $name)) { - $ext = array_pop($parts); + if ($parts=explode(".", $name)) { + $ext=array_pop($parts); switch ($ext) { case "gz": case "bz": case "bz2": - $ext = array_pop($parts) . $ext; + $ext=array_pop($parts).$ext; /* FALLTHROUGH */ case "tar.gz": case "tar.bz": @@ -915,7 +915,7 @@ class m_bro { case "tar": case "Z": case "zip": - return true; + return true; } } return false; @@ -929,9 +929,9 @@ class m_bro { * @return boolean */ function is_sqlfile($name) { - if ($parts = explode(".", $name)) { - $ext = array_pop($parts); - $ext2 = array_pop($parts) . '.'.$ext; + if ($parts=explode(".", $name)) { + $ext=array_pop($parts); + $ext2=array_pop($parts).'.'.$ext; if ( $ext == 'sql' or $ext2 == 'sql.gz') return true; } return false; @@ -939,14 +939,14 @@ class m_bro { /** * - * @global m_err $err - * @param string $dir - * @param string $file + * @global m_err $err + * @param string $dir + * @param string $file */ function download_link($dir,$file){ global $err; $err->log("bro","download_link"); - header("Content-Disposition: attachment; filename = $file"); + header("Content-Disposition: attachment; filename=$file"); header("Content-Type: application/force-download"); header("Content-Transfer-Encoding: binary"); $this->content_send($dir,$file); @@ -956,16 +956,16 @@ class m_bro { /** * Echoes the content of the file $file located in directory $R * - * @global m_err $err - * @param string $R - * @param string $file - * @return null|false + * @global m_err $err + * @param string $R + * @param string $file + * @return null|false */ function content_send($R,$file) { global $err; - $absolute = $this->convertabsolute($R,false); + $absolute=$this->convertabsolute($R,false); if (!strpos($file,"/")) { - $absolute .= "/".$file; + $absolute.="/".$file; if (file_exists($absolute)) { readfile($absolute); } @@ -981,20 +981,20 @@ class m_bro { * le contenu est issu d'un textarea, et ne DOIT PAS contenir de \ ajouts * automatiquement par addslashes * - * @global m_err $err - * @param string $file Nom du fichier sauver. S'il existe déjà, il sera - * écrasé sans confirmation. - * @param string $R Dossier dans lequel on modifie le fichier - * @param string $texte Texte du fichier à sauver dedans - * @return false|null TRUE si tout s'est bien pass, FALSE si une erreur s'est produite. + * @global m_err $err + * @param string $file Nom du fichier sauver. S'il existe déjà, il sera + * écrasé sans confirmation. + * @param string $R Dossier dans lequel on modifie le fichier + * @param string $texte Texte du fichier à sauver dedans + * @return false|null TRUE si tout s'est bien pass, FALSE si une erreur s'est produite. */ function save($file,$R,$texte) { global $err; - $absolute = $this->convertabsolute($R,false); + $absolute=$this->convertabsolute($R,false); if (!strpos($file,"/")) { - $absolute .= "/".$file; + $absolute.="/".$file; if (file_exists($absolute)) { - if (! file_put_contents($absolute, $texte ) ) { + if (! file_put_contents($absolute, $texte ) ) { $err->raise("bro",_("Cannot edit the requested file. Please check the permissions")); return false; } @@ -1009,16 +1009,16 @@ class m_bro { /** * Echo d'un flux .tar.Z contenant tout le contenu du dossier $dir * - * @global m_mem $mem - * @param string $dir Dossier à dumper, relatif la racine du compte du membre. - * @return void NE RETOURNE RIEN, et il faut Quitter le script immdiatement aprs + * @global m_mem $mem + * @param string $dir Dossier à dumper, relatif la racine du compte du membre. + * @return void NE RETOURNE RIEN, et il faut Quitter le script immdiatement aprs */ - function DownloadZ($dir = "") { + function DownloadZ($dir="") { global $mem; - header("Content-Disposition: attachment; filename = ".$mem->user["login"].".Z"); + header("Content-Disposition: attachment; filename=".$mem->user["login"].".Z"); header("Content-Type: application/x-Z"); header("Content-Transfer-Encoding: binary"); - $d = escapeshellarg(".".$this->convertabsolute($dir,true)); + $d=escapeshellarg(".".$this->convertabsolute($dir,true)); set_time_limit(0); passthru("/bin/tar -cZ -C ".getuserpath()."/".$mem->user["login"]."/ $d"); } @@ -1027,65 +1027,65 @@ class m_bro { /** * Echo d'un flux .tgz contenant tout le contenu du dossier $dir * - * @global type $mem - * @param string $dir Dossier à dumper, relatif la racine du compte du membre. - * @return void NE RETOURNE RIEN, et il faut Quitter le script immdiatement aprs + * @global type $mem + * @param string $dir Dossier à dumper, relatif la racine du compte du membre. + * @return void NE RETOURNE RIEN, et il faut Quitter le script immdiatement aprs */ - function DownloadTGZ($dir = "") { + function DownloadTGZ($dir="") { global $mem; - header("Content-Disposition: attachment; filename = ".$mem->user["login"].".tgz"); + header("Content-Disposition: attachment; filename=".$mem->user["login"].".tgz"); header("Content-Type: application/x-tgz"); header("Content-Transfer-Encoding: binary"); - $d = escapeshellarg(".".$this->convertabsolute($dir,true)); + $d=escapeshellarg(".".$this->convertabsolute($dir,true)); set_time_limit(0); passthru("/bin/tar -cz -C ".getuserpath()."/ $d"); } - - + + /** * Echo d'un flux .tar.bz2 contenant tout le contenu du dossier $dir * - * @global type $mem - * @param string $dir Dossier à dumper, relatif la racine du compte du membre. - * @return void NE RETOURNE RIEN, et il faut Quitter le script immdiatement aprs + * @global type $mem + * @param string $dir Dossier à dumper, relatif la racine du compte du membre. + * @return void NE RETOURNE RIEN, et il faut Quitter le script immdiatement aprs */ - function DownloadTBZ($dir = "") { + function DownloadTBZ($dir="") { global $mem; - header("Content-Disposition: attachment; filename = ".$mem->user["login"].".tar.bz2"); + header("Content-Disposition: attachment; filename=".$mem->user["login"].".tar.bz2"); header("Content-Type: application/x-bzip2"); header("Content-Transfer-Encoding: binary"); - $d = escapeshellarg(".".$this->convertabsolute($dir,true)); + $d=escapeshellarg(".".$this->convertabsolute($dir,true)); set_time_limit(0); passthru("/bin/tar -cj -C ".getuserpath()."/ $d"); } - + /** - * Echo d'un flux .ZIP contenant tout le contenu du dossier $dir + * Echo d'un flux .ZIP contenant tout le contenu du dossier $dir * - * @global type $mem - * @param string $dir Dossier à dumper, relatif la racine du compte du membre. - * @return void NE RETOURNE RIEN, et il faut Quitter le script immdiatement aprs + * @global type $mem + * @param string $dir Dossier à dumper, relatif la racine du compte du membre. + * @return void NE RETOURNE RIEN, et il faut Quitter le script immdiatement aprs */ - function DownloadZIP($dir = "") { + function DownloadZIP($dir="") { global $mem; - header("Content-Disposition: attachment; filename = ".$mem->user["login"].".zip"); + header("Content-Disposition: attachment; filename=".$mem->user["login"].".zip"); header("Content-Type: application/x-zip"); header("Content-Transfer-Encoding: binary"); - $d = escapeshellarg($this->convertabsolute($dir,false)); + $d=escapeshellarg($this->convertabsolute($dir,false)); set_time_limit(0); passthru("/usr/bin/zip -r - $d"); } - + /** * Fonction de tri perso utilis par filelist. * - * @access private - * @param string $a - * @param string $b - * @return int + * @access private + * @param string $a + * @param string $b + * @return int */ function _sort_filelist_name($a,$b) { if ($a["type"] && !$b["type"]) return 1; @@ -1097,16 +1097,16 @@ class m_bro { /** * Efface $file et tous ses sous-dossiers s'il s'agit d'un dossier * A UTILISER AVEC PRECAUTION !!! - * @param string $file Fichier ou dossier supprimer. - * @access private + * @param string $file Fichier ou dossier supprimer. + * @access private */ function _delete($file) { // permet d'effacer de nombreux fichiers @set_time_limit(0); //chmod($file,0777); if (is_dir($file)) { - $handle = opendir($file); - while($filename = readdir($handle)) { + $handle=opendir($file); + while($filename=readdir($handle)) { if ($filename != "." && $filename != "..") { $this->_delete($file."/".$filename); } @@ -1123,52 +1123,52 @@ class m_bro { * Function d'exportation de configuration appelé par la classe m_export via un hooks * Produit en sorti un tableau formatté ( pour le moment) en HTML * - * @global m_mysql $db - * @global m_err $err - * @return string + * @global m_mysql $db + * @global m_err $err + * @return string */ function alternc_export_conf() { global $db,$err; $err->log("bro","export_conf"); - $str = "\n"; - $str .= " \n"; - $pref = $this->GetPrefs(); - - $i = 1; + $str="
    Browser
    \n"; + $str.=" \n"; + $pref=$this->GetPrefs(); + + $i=1; foreach ($pref as $k=>$v) { if (($i % 2) == 0){ - $str .= " <$k>$v\n"; + $str.=" <$k>$v\n"; } $i++; } - $str .= " \n"; - + $str.=" \n"; + return $str; } /** - * Function d'exportation des données appelé par la classe m_export via un hooks + * Function d'exportation des données appelé par la classe m_export via un hooks * - * @global m_mem $mem - * @global m_err $err - * @param string $dir Le chemin destination du tarball produit - * @return boolean|null + * @global m_mem $mem + * @global m_err $err + * @param string $dir Le chemin destination du tarball produit + * @return boolean|null */ function alternc_export_data($dir){ global $mem,$err; $err->log("bro","export_data"); - $dir .= "html/"; + $dir.="html/"; if(!is_dir($dir)){ if(!mkdir($dir)) $err->raise("bro",_("Cannot create the requested directory. Please check the permissions")); } - $timestamp = date("H:i:s"); + $timestamp=date("H:i:s"); // relacher le lock global sinon ce download va geler alternc pour // tout le monde alternc_shutdown(); - if(exec("/bin/tar cvf - ".getuserpath()."/ | gzip -9c > ".$dir."/".$mem->user['login']."_html_".$timestamp.".tar.gz")){ + if(exec("/bin/tar cvf - ".getuserpath()."/ | gzip -9c > ".$dir."/".$mem->user['login']."_html_".$timestamp.".tar.gz")){ $err->log("bro","export_data_succes"); }else{ $err->log("bro","export_data_failed"); @@ -1178,7 +1178,7 @@ class m_bro { } function getMaxAllowedUploadSize() { - return min(ini_get('post_max_size'), ini_get('upload_max_filesize')); + return min(ini_get('post_max_size'), ini_get('upload_max_filesize')); } } /* Class Browser */ From c96f928056ac6c7fdaadaaa9b51bb66525f0657c Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Wed, 27 Aug 2014 11:20:54 +0200 Subject: [PATCH 13/15] fixing alternc_shutdown bug --- bureau/admin/bro_tgzdown.php | 4 +--- bureau/class/config.php | 17 ----------------- bureau/class/m_bro.php | 3 --- 3 files changed, 1 insertion(+), 23 deletions(-) diff --git a/bureau/admin/bro_tgzdown.php b/bureau/admin/bro_tgzdown.php index 7f1a4ee8..644472db 100644 --- a/bureau/admin/bro_tgzdown.php +++ b/bureau/admin/bro_tgzdown.php @@ -36,9 +36,7 @@ getFields($fields); $p=$bro->GetPrefs(); -// need to release the giant lock, otherwise those downloads will hang -// AlternC for all users! -alternc_shutdown(); + switch ($p["downfmt"]) { case 0: $bro->DownloadTGZ($dir); diff --git a/bureau/class/config.php b/bureau/class/config.php index 0bc75529..c52e4adb 100644 --- a/bureau/class/config.php +++ b/bureau/class/config.php @@ -52,23 +52,6 @@ Merci de revenir plus tard."; } /* */ -/* Toutes les pages du bureau passent ici. On utilise une s�maphore pour - s'assurer que personne ne pourra acc�der � 2 pages du bureau en m�me temps. -*/ -/* * / -// 1. Get a semaphore id for the alternc magic number (18577) -$alternc_sem = sem_get ( 18577 ); -// 2. Declare the shutdown function, that release the semaphore -function alternc_shutdown() { - global $alternc_sem; - @sem_release( $alternc_sem ); -} -// 3. Register the shutdown function -register_shutdown_function("alternc_shutdown"); -// 4. Acquire the semaphore : with that process, -sem_acquire( $alternc_sem ); -/* */ - if (ini_get("safe_mode")) { echo "SAFE MODE IS ENABLED for the web panel ! It's a bug in your php or apache configuration, please fix it !!"; exit(); diff --git a/bureau/class/m_bro.php b/bureau/class/m_bro.php index 5064f738..57820ca6 100644 --- a/bureau/class/m_bro.php +++ b/bureau/class/m_bro.php @@ -1165,9 +1165,6 @@ class m_bro { } $timestamp=date("H:i:s"); - // relacher le lock global sinon ce download va geler alternc pour - // tout le monde - alternc_shutdown(); if(exec("/bin/tar cvf - ".getuserpath()."/ | gzip -9c > ".$dir."/".$mem->user['login']."_html_".$timestamp.".tar.gz")){ $err->log("bro","export_data_succes"); }else{ From 58d16d47f9637409b2ccc1ff049b9fe2ce49d250 Mon Sep 17 00:00:00 2001 From: Benjamin Sonntag Date: Wed, 3 Sep 2014 15:10:18 +0200 Subject: [PATCH 14/15] setting user cron timeout to 3600 Sec (1H) + NOT RETRYING when using wget --- src/cron_users_doit.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/cron_users_doit.sh b/src/cron_users_doit.sh index 06d36bb3..2998a136 100755 --- a/src/cron_users_doit.sh +++ b/src/cron_users_doit.sh @@ -10,7 +10,7 @@ now=$5 user=$6 password=$7 -timeout=5 +timeout=3600 for CONFIG_FILE in \ /etc/alternc/local.sh \ @@ -55,7 +55,7 @@ tmpfile=$(mktemp /tmp/altern-cron-id$id-$$.XXX) ( echo -e "Here the report for the scheduled task for the cron #$id in your AlternC configuration (from http://$FQDN)\n\n" echo -e "\n---------- BEGIN ----------" -bash -c "wget -O - --no-check-certificate --http-user=$(urldecode $user) --http-password=$(urldecode $password) \"$(urldecode $url)\" --timeout=$timeout 2>&1" +bash -c "wget --tries=1 -O - --no-check-certificate --http-user=$(urldecode $user) --http-password=$(urldecode $password) \"$(urldecode $url)\" --timeout=$timeout 2>&1" echo -e "\n---------- END ----------" ) > "$tmpfile" From 7c597daa730f16404ccdf422372a55d06d3d04ac Mon Sep 17 00:00:00 2001 From: alban Date: Tue, 9 Sep 2014 14:52:56 +0200 Subject: [PATCH 15/15] =?UTF-8?q?[fix]=C2=A0Missing=20chmod=20action?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bureau/class/m_action.php | 17 ++- bureau/class/m_bro.php | 3 +- phpunit/tests/bureau/class/m_actionTest.php | 9 ++ src/do_actions.php | 135 +++++++++++++------- 4 files changed, 118 insertions(+), 46 deletions(-) diff --git a/bureau/class/m_action.php b/bureau/class/m_action.php index a1bec46d..cbbba4cd 100644 --- a/bureau/class/m_action.php +++ b/bureau/class/m_action.php @@ -69,7 +69,19 @@ class m_action { } /** - * Plans the cration of a dir + * Plans the a chmod on file or dir + * + * @param string $filename + * @param int $perms + * @param string $user + * @return boolean + */ + function chmod($filename, $perms, $user = "root") { + return $this->set('chmod', $user, array('filename' => $filename,"perms"=>$perms)); + } + + /** + * Plans the creation of a dir * * @param string $dir * @param int $user @@ -186,6 +198,9 @@ class m_action { $serialized = serialize($parameters); switch ($type) { + case 'chmod': + $query = "insert into actions values ('','CHMOD','$serialized',now(),'','','$user','');"; + break; case 'create_file': $query = "insert into actions values ('','CREATE_FILE','$serialized',now(),'','','$user','');"; break; diff --git a/bureau/class/m_bro.php b/bureau/class/m_bro.php index 57820ca6..4b5246ac 100644 --- a/bureau/class/m_bro.php +++ b/bureau/class/m_bro.php @@ -546,6 +546,7 @@ class m_bro { * Change les droits d'acces aux fichier de $d du dossier $R en $p * * @global m_err $err + * @global m_action $action * @param string $R Dossier dans lequel se trouve les fichiers renommer. * @param boolean $verbose Shall we 'echo' what we did ? * @return boolean TRUE Si les fichiers ont t renomms, FALSE si une erreur s'est produite. @@ -569,7 +570,7 @@ class m_bro { } else { $m=$m ^ 0222; // ugo-w } - chmod($absolute."/".$d[$i], $m); + $action->chmod($absolute."/".$d[$i], $m); if ($verbose) { echo "chmod ".sprintf('%o', $m)." file, was ".sprintf('%o', fileperms($absolute."/". $d[$i])). " -- ".$perm[$i]['w']; } diff --git a/phpunit/tests/bureau/class/m_actionTest.php b/phpunit/tests/bureau/class/m_actionTest.php index 1de07cdf..6aebe7d1 100644 --- a/phpunit/tests/bureau/class/m_actionTest.php +++ b/phpunit/tests/bureau/class/m_actionTest.php @@ -69,6 +69,15 @@ class m_actionTest extends AlterncTest { $this->assertFileExists($L_INOTIFY_DO_ACTION); } + /** + * @covers m_action::chmod + */ + public function testChmod() { + $result = $this->object->chmod(self::TEST_FILE, 0777,"phpunit"); + $this->assertEquals(1, $this->getConnection()->getRowCount('actions')); + + } + /** * @covers m_action::create_file */ diff --git a/src/do_actions.php b/src/do_actions.php index bd2a3d93..dc01d302 100644 --- a/src/do_actions.php +++ b/src/do_actions.php @@ -39,34 +39,69 @@ /* Fixme - - handle error correctly - check all those cases - */ /////////////////////////////////// // Put this var to 1 if you want to enable debug prints -$debug=1; -$error_raise=''; +$debug=0; -// Debug function that print infos +// Collects errors along execution. If length > 1, an email is sent. +$errorsList=array(); + +// Bootstraps +require_once("/usr/share/alternc/panel/class/config_nochk.php"); + +// Script lock through filesystem +$admin->stop_if_jobs_locked(); + +if( !defined("ALTERNC_DO_ACTION_LOCK")){ + define("ALTERNC_DO_ACTION_LOCK",'/var/run/alternc/do_actions_cron.lock'); +} + +$SCRIPT='/usr/bin/php do_actions.php'; +$MY_PID=getmypid(); +$FIXPERM='/usr/lib/alternc/fixperms.sh'; + + +/** + * + * Debug function that print infos + * + * @global int $debug + * @param type $mess + */ function d($mess){ global $debug; if ($debug == 1) echo "$mess\n"; } -// Function to mail the panel's administrator if something failed +/** + * Function to mail the panel's administrator if something failed + * @global array $errorsList + * @global type $L_FQDN + */ function mail_it(){ - global $error_raise,$L_FQDN; - mail("alterncpanel@$L_FQDN",'Script do_actions.php issues',"\n Errors reporting mail:\n\n$error_raise"); + global $errorsList,$L_FQDN; + // Forces array + if( !is_array($errorsList)){ + $errorsList = array($errorsList); + } + // Builds message from array + $msg = implode("\n", $errorsList); + // Attempts to send email + // @todo log if fails + mail("alterncpanel@$L_FQDN",'Script do_actions.php issues',"\n Errors reporting mail:\n\n$msg"); } -/* - * $command: the command - * $parameters: of the command (they are going to be protected) - * return array('output'=>'output of exec', 'return_var'=>'returned integer of exec') +/** + * Common routine for system calls + * + * @param type $command the command + * @param type $parameters of the command (they are going to be protected) + * @return array('output'=>'output of exec', 'return_var'=>'returned integer of exec') */ function execute_cmd($command, $parameters=array()) { $cmd_line = "$command "; @@ -84,20 +119,12 @@ function execute_cmd($command, $parameters=array()) { return array('executed' => $cmd_line, 'output'=>$output, 'return_var'=>$code); } -require_once("/usr/share/alternc/panel/class/config_nochk.php"); - -$admin->stop_if_jobs_locked(); - -$LOCK_FILE='/var/run/alternc/do_actions_cron.lock'; -$SCRIPT='/usr/bin/php do_actions.php'; -$MY_PID=getmypid(); -$FIXPERM='/usr/lib/alternc/fixperms.sh'; // Check if script isn't already running -if (file_exists($LOCK_FILE) !== false){ +if (file_exists(ALTERNC_DO_ACTION_LOCK) !== false){ d("Lock file already exists. "); // Check if file is in process list - $PID=file_get_contents($LOCK_FILE); + $PID=file_get_contents(ALTERNC_DO_ACTION_LOCK); d("My PID is $MY_PID, PID in the lock file is $PID"); if ($PID == exec("pidof $SCRIPT | tr ' ' '\n' | grep -v $MY_PID")){ // Previous cron is not finished yet, just exit @@ -105,16 +132,16 @@ if (file_exists($LOCK_FILE) !== false){ exit(0); }else{ // Previous cron failed! - $error_raise.="Lock file already exists. No process with PID $PID found! Previous cron failed...\n"; + $errorsList[]="Lock file already exists. No process with PID $PID found! Previous cron failed...\n"; // No need to remove anything, we're going to recreate it //d("Removing lock file and trying to process the failed action..."); // Delete the lock and continue to the next action - //unlink($LOCK_FILE); + //unlink(ALTERNC_DO_ACTION_LOCK); // Lock with the current script's PID - if (file_put_contents($LOCK_FILE,$MY_PID) === false){ - $error_raise.="Cannot open/write $LOCK_FILE\n"; + if (file_put_contents(ALTERNC_DO_ACTION_LOCK,$MY_PID) === false){ + $errorsList[]="Cannot open/write ALTERNC_DO_ACTION_LOCK\n"; mail_it(); exit(1); } @@ -131,9 +158,9 @@ if (file_exists($LOCK_FILE) !== false){ $action->reset_job($c["id"]); }else{ // We can't resume the others types, notify the fail and finish this action - $error_raise.="Can't resume the job n°".$c["id"]." action '".$c["type"]."', finishing it with a fail status.\n"; + $errorsList[]="Can't resume the job n°".$c["id"]." action '".$c["type"]."', finishing it with a fail status.\n"; if(!$action->finish($c["id"],"Fail: Previous script crashed while processing this action, cannot resume it.")){ - $error_raise.="Cannot finish the action! Error while inserting the error value in the DB for action n°".$c["id"]." : action '".$c["type"]."'\n"; + $errorsList[]="Cannot finish the action! Error while inserting the error value in the DB for action n°".$c["id"]." : action '".$c["type"]."'\n"; break; // Else we go into an infinite loop... AAAAHHHHHH } } @@ -141,8 +168,8 @@ if (file_exists($LOCK_FILE) !== false){ } }else{ // Lock with the current script's PID - if (file_put_contents($LOCK_FILE,$MY_PID) === false){ - $error_raise.="Cannot open/write $LOCK_FILE\n"; + if (file_put_contents(ALTERNC_DO_ACTION_LOCK,$MY_PID) === false){ + $errorsList[]="Cannot open/write ALTERNC_DO_ACTION_LOCK\n"; mail_it(); exit(1); } @@ -157,7 +184,6 @@ while ($rr=$action->get_action()){ $SU="su ".$r["user"]." 2>&1 ;"; else $SU=""; - unset($output); // We lock the action d("-----------\nBeginning action n°".$r["id"]); $action->begin($r["id"]); @@ -170,19 +196,36 @@ while ($rr=$action->get_action()){ // Create the directory and make parent directories as needed #@exec("$FIXPERM -u ".$params["uid"]." 2>&1", $trash, $code); $returned = execute_cmd("$FIXPERM -u", $params["uid"]); + break; + case "CHMOD" : + $filename=$params["file"]; + $perms=$params["perms"]; + // Checks the file or directory exists + if( !is_dir($filename) && ! is_file($filename)){ + $errorsList=array("Fail: cannot create ".$params["dst"]); + } + // Checks the perms are correct + else if ( !is_int( $perms)){ + $errorsList=array("Fail: cannot create ".$params["dst"]); + } + // Attempts to change the rights on the file or directory + else if( !chmod($filename, $perms)) { + $errorsList=array("Fail: cannot create ".$params["dst"]); + } + break; case "CREATE_FILE" : if(!file_exists($params["file"])) { #@exec("$SU touch ".$params["file"]." 2>&1 ; echo '".$params["content"]."' > '".$params["file"]."' 2>&1", $output); if ( file_put_contents($params["file"], $params["content"]) === false ) { - $log_error=array("Fail: can't write into file ".$params["file"]); + $errorsList=array("Fail: can't write into file ".$params["file"]); } else { if (!chown($params["file"], $r["user"])) { - $log_error=array("Fail: cannot chown ".$params["file"]); + $errorsList=array("Fail: cannot chown ".$params["file"]); } } } else { - $log_error=array("Fail: file already exists ".$params["file"]); + $errorsList=array("Fail: file already exists ".$params["file"]); } break; case "CREATE_DIR" : @@ -203,18 +246,22 @@ while ($rr=$action->get_action()){ $returned = execute_cmd("$SU mv -f", array($params["src"], $params["dst"])); } } else { //is_dir false - $log_error=array("Fail: cannot create ".$params["dst"]); + $errorsList=array("Fail: cannot create ".$params["dst"]); } // is_dir break; case "FIX_DIR" : $returned = execute_cmd($FIXPERM, array('-d', $params["dir"])); - if($returned['return_val'] != 0) $log_error=array("Fixperms.sh failed, returned error code : ".$returned['return_val']); + if($returned['return_val'] != 0) { + $errorsList=array("Fixperms.sh failed, returned error code : ".$returned['return_val']); + } break; case "FIX_FILE" : #@exec("$FIXPERM -f ".$params["file"]." 2>&1", $trash, $code); $returned = execute_cmd($FIXPERM, array('-f', $params["file"])); - if($returned['return_val'] != 0) $log_error=array("Fixperms.sh failed, returned error code : ".$returned['return_val']); + if($returned['return_val'] != 0){ + $errorsList=array("Fixperms.sh failed, returned error code : ".$returned['return_val']); + } break; default : $output=array("Fail: Sorry dude, i do not know this type of action"); @@ -223,24 +270,24 @@ while ($rr=$action->get_action()){ // Get the error (if exists). if(isset($output[0])){ $return=$output[0]; - $error_raise.="\nAction n°".$r["id"]." '".$r["type"]."' failed! With user: ".$r["user"]."\nHere is the complete output:\n".print_r($output); + $errorsList[]="\nAction n°".$r["id"]." '".$r["type"]."' failed! With user: ".$r["user"]."\nHere is the complete output:\n".print_r($output); } // We finished the action, notify the DB. d("Finishing... return value is : $return\n"); if(!$action->finish($r["id"],addslashes($return))){ - $error_raise.="Cannot finish the action! Error while inserting the error value in the DB for action n°".$r["id"]." : action '".$r["type"]."'\nReturn value: ".addslashes($return)."\n"; + $errorsList[]="Cannot finish the action! Error while inserting the error value in the DB for action n°".$r["id"]." : action '".$r["type"]."'\nReturn value: ".addslashes($return)."\n"; break; // Else we go into an infinite loop... AAAAHHHHHH } } -// If something have failed, notify it to the admin -if($error_raise !== '') { +// If an error occured, notify it to the admin +if(count($errorsList)) { mail_it(); } // Unlock the script -unlink($LOCK_FILE); +// @todo This could be handled by m_admin +unlink(ALTERNC_DO_ACTION_LOCK); // Exit this script -exit(0); -?> +exit(0); \ No newline at end of file
    Browser