From 0f4ceca8ec12a61ea370c57d42cc59eaf7a5dea8 Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@destailleur.fr>
Date: Sun, 17 Nov 2013 02:59:01 +0100
Subject: [PATCH] Fix: tons of bugs into ecm module

---
 build/debian/README.howto                     | 11 +++--
 htdocs/core/ajax/ajaxdirtree.php              |  3 +-
 htdocs/core/class/html.formfile.class.php     | 41 ++++++++++---------
 htdocs/ecm/index.php                          | 41 +++++++++++++------
 htdocs/ecm/tpl/builddatabase.tpl.php          | 40 +++++++++++-------
 .../plugins/jqueryFileTree/jqueryFileTree.js  |  4 +-
 6 files changed, 90 insertions(+), 50 deletions(-)

diff --git a/build/debian/README.howto b/build/debian/README.howto
index 463ba111c46..b34d296d2e4 100644
--- a/build/debian/README.howto
+++ b/build/debian/README.howto
@@ -39,7 +39,13 @@ END
 
 
 # To use Alioth.debian.org
-* Create a login
+* Create an account login
+* Update your ~/.ssh/config file to add:
+Host svn.debian.org git.debian.org bzr.debian.org hg.debian.org darcs.debian.org arch.debian.org
+	User eldy-guest
+	IdentityFile ~/.ssh/id_rsa
+* Check login on page https://alioth.debian.org/users/login
+Ex: https://alioth.debian.org/users/eldy-guest
 * Setup your ssh as described into page: http://wiki.debian.org/Alioth/SSH
 * Ask to be included into project collab-maint: http://alioth.debian.org/projects/collab-maint/
 
@@ -192,8 +198,7 @@ To update dolibarr debian package
 * You can git clone debian git repo
 > git clone git.debian.org:/git/collab-maint/dolibarr.git [dolibarr-debian]
 or better
-> mkdir gitdebian
-> cd gitdebian
+> cd ~; mkdir git-debian; cd git-debian
 > gbp-clone git.debian.org:/git/collab-maint/dolibarr.git
 
 * You can then create a PHP project from Eclipse called dolibarr-debian
diff --git a/htdocs/core/ajax/ajaxdirtree.php b/htdocs/core/ajax/ajaxdirtree.php
index db8af5ba265..640c64f40f7 100644
--- a/htdocs/core/ajax/ajaxdirtree.php
+++ b/htdocs/core/ajax/ajaxdirtree.php
@@ -207,6 +207,7 @@ if (file_exists($fullpathselecteddir))
     		// Enable jquery handlers on new generated HTML objects
             print '<script type="text/javascript">';
             print 'jQuery(".classfortooltip").tipTip({ maxWidth: "600px", edgeOffset: 10, delay: 50, fadeIn: 50, fadeOut: 50});';
+			// TODO Remove this. Is replaced with function as 3rd parameter of fileTree
             print 'jQuery(".fmdirlia").click(function(e) {
             			id=jQuery(this).attr(\'id\').substr(12);
             			jQuery("#formuserfile_section_dir").val(jQuery(this).attr(\'rel\'));
@@ -221,7 +222,7 @@ if (file_exists($fullpathselecteddir))
     else print "PermissionDenied";
 }
 
-// This ajax service is called only when a directory $selecteddir is opened but not closed.
+// This ajax service is called only when a directory $selecteddir is opened but not when closed.
 //print '<script language="javascript">';
 //print "loadandshowpreview('".dol_escape_js($selecteddir)."');";
 //print '</script>';
diff --git a/htdocs/core/class/html.formfile.class.php b/htdocs/core/class/html.formfile.class.php
index c578e5d9786..45221876e91 100644
--- a/htdocs/core/class/html.formfile.class.php
+++ b/htdocs/core/class/html.formfile.class.php
@@ -64,9 +64,10 @@ class FormFile
      *  @param	boolean	$useajax		Use fileupload ajax (0=never, 1=if enabled, 2=always whatever is option). 2 should never be used.
      *  @param	string	$savingdocmask	Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__'
      *  @param	string	$linkfiles		1=Also add form to link files, 0=Do not show form to link files
+     *  @param	string	$htmlname		Name and id of HTML form
      * 	@return	int						<0 if KO, >0 if OK
      */
-    function form_attach_new_file($url, $title='', $addcancel=0, $sectionid=0, $perm=1, $size=50, $object='', $options='', $useajax=1, $savingdocmask='', $linkfiles=1)
+    function form_attach_new_file($url, $title='', $addcancel=0, $sectionid=0, $perm=1, $size=50, $object='', $options='', $useajax=1, $savingdocmask='', $linkfiles=1, $htmlname='formuserfile')
     {
         global $conf,$langs, $hookmanager;
         $hookmanager->initHooks(array('formfile'));
@@ -90,9 +91,9 @@ class FormFile
             if (empty($title)) $title=$langs->trans("AttachANewFile");
             if ($title != 'none') print_titre($title);
 
-            $out .= '<form name="formuserfile" action="'.$url.'" enctype="multipart/form-data" method="POST">';
-            $out .= '<input type="hidden" id="formuserfile_section_dir" name="section_dir" value="">';
-            $out .= '<input type="hidden" id="formuserfile_section_id"  name="section_id" value="'.$sectionid.'">';
+            $out .= '<form name="'.$htmlname.'" id="'.$htmlname.'" action="'.$url.'" enctype="multipart/form-data" method="POST">';
+            $out .= '<input type="hidden" id="'.$htmlname.'_section_dir" name="section_dir" value="">';
+            $out .= '<input type="hidden" id="'.$htmlname.'_section_id"  name="section_id" value="'.$sectionid.'">';
             $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 
             $out .= '<table width="100%" class="nobordernopadding">';
@@ -165,9 +166,9 @@ class FormFile
 	            $langs->load('link');
 	            $title = $langs->trans("LinkANewFile");
 	            $out .= load_fiche_titre($title, null, null);
-	            $out .= '<form name="formuserfile" action="'.$url.'" method="POST">';
-	            $out .= '<input type="hidden" id="formuserfile_section_dir" name="section_dir" value="">';
-	            $out .= '<input type="hidden" id="formuserfile_section_id"  name="section_id" value="'.$sectionid.'">';
+	            $out .= '<form name="'.$htmlname.'_link" id="'.$htmlname.'_link" action="'.$url.'" method="POST">';
+	            $out .= '<input type="hidden" id="'.$htmlname.'_link_section_dir" name="link_section_dir" value="">';
+	            $out .= '<input type="hidden" id="'.$htmlname.'_link_section_id"  name="link_section_id" value="'.$sectionid.'">';
 	            $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 
 	            $out .= '<table width="100%" class="nobordernopadding">';
@@ -770,14 +771,14 @@ class FormFile
 					print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
 					if ($forcedownload) print '&attachment=1';
 					if (! empty($object->entity)) print '&entity='.$object->entity;
-					print '&file='.urlencode($relativepath.$file['name']);
-					/* Restore old code: When file is at level 2+, full relative path must be in url, not only level1
+					$filepath=$relativepath.$file['name'];
+					/* Restore old code: When file is at level 2+, full relative path (and not only level1) must be into url
 					if ($file['level1name'] <> $object->id)
-						$filepath=urlencode($object->id.'/'.$file['level1name'].'/'.$file['name']);
+						$filepath=$object->id.'/'.$file['level1name'].'/'.$file['name'];
 					else
-						$filepath=urlencode($object->id.'/'.$file['name']);
-					print '&file='.$filepath;
-						*/
+						$filepath=$object->id.'/'.$file['name'];
+					*/
+					print '&file='.urlencode($filepath);
 					print '">';
 
 					print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')').' ';
@@ -800,14 +801,16 @@ class FormFile
 					// Delete or view link
 					// ($param must start with &)
 					print '<td align="right">';
-					if ($useinecm)     print '<a href="'.DOL_URL_ROOT.'/ecm/docfile.php?urlfile='.urlencode($file['name']).$param.'" class="editfilelink" rel="'.urlencode($file['name']).$param.'">'.img_view().'</a> &nbsp; ';
+					if ($useinecm)     print '<a href="'.DOL_URL_ROOT.'/ecm/docfile.php?urlfile='.urlencode($file['name']).$param.'" class="editfilelink" rel="'.urlencode($file['name']).'">'.img_view().'</a> &nbsp; ';
 					if ($permtodelete)
 					{
+						/*
 						if ($file['level1name'] <> $object->id)
-							$filepath=urlencode($file['level1name'].'/'.$file['name']);
+							$filepath=$file['level1name'].'/'.$file['name'];
 						else
-							$filepath=urlencode($file['name']);
-						print '<a href="'.(($useinecm && ! empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS))?'#':$url.'?action=delete&urlfile='.$filepath.$param).'" class="deletefilelink" rel="'.$filepath.$param.'">'.img_delete().'</a>';
+							$filepath=$file['name'];
+						*/
+						print '<a href="'.(($useinecm && ! empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS))?'#':$url.'?action=delete&urlfile='.urlencode($filepath).$param).'" class="deletefilelink" rel="'.$filepath.'">'.img_delete().'</a>';
 					}
 					else print '&nbsp;';
 					print "</td>";
@@ -831,7 +834,7 @@ class FormFile
     /**
      *	Show list of documents in a directory
      *
-     *  @param	 string	$upload_dir         Directory that was scanned
+     *  @param	string	$upload_dir         Directory that was scanned
      *  @param  array	$filearray          Array of files loaded by dol_dir_list function before calling this function
      *  @param  string	$modulepart         Value for modulepart used by download wrapper
      *  @param  string	$param              Parameters on sort links
@@ -841,7 +844,7 @@ class FormFile
      *  @param  int		$useinecm           Change output for use in ecm module
      *  @param  int		$textifempty        Text to show if filearray is empty
      *  @param  int		$maxlength          Maximum length of file name shown
-     *  @param	 string $url				Full url to use for click links ('' = autodetect)
+     *  @param	string $url				Full url to use for click links ('' = autodetect)
      *  @return int                 		<0 if KO, nb of files shown if OK
      */
     function list_of_autoecmfiles($upload_dir,$filearray,$modulepart,$param,$forcedownload=0,$relativepath='',$permtodelete=1,$useinecm=0,$textifempty='',$maxlength=0,$url='')
diff --git a/htdocs/ecm/index.php b/htdocs/ecm/index.php
index 5368c1b52be..531138aaab9 100644
--- a/htdocs/ecm/index.php
+++ b/htdocs/ecm/index.php
@@ -53,6 +53,7 @@ $action=GETPOST("action");
 $section=GETPOST("section")?GETPOST("section","int"):GETPOST("section_id","int");
 $module=GETPOST("module");
 if (! $section) $section=0;
+$section_dir=GETPOST('section_dir');
 
 $sortfield = GETPOST("sortfield",'alpha');
 $sortorder = GETPOST("sortorder",'alpha');
@@ -93,7 +94,7 @@ if (GETPOST("sendit") && ! empty($conf->global->MAIN_UPLOAD_DOC))
 	// Define relativepath and upload_dir
     $relativepath='';
 	if ($ecmdir->id) $relativepath=$ecmdir->getRelativePath();
-	else $relativepath=GETPOST('section_dir');
+	else $relativepath=$section_dir;
 	$upload_dir = $conf->ecm->dir_output.'/'.$relativepath;
 
 	if (empty($_FILES['userfile']['tmp_name']))
@@ -167,16 +168,20 @@ if ($action == 'confirm_deletefile')
 {
     if (GETPOST('confirm') == 'yes')
     {
-        $langs->load("other");
-    	$result=$ecmdir->fetch($section);
-    	if (! ($result > 0))
+    	$langs->load("other");
+    	if ($section)
     	{
-    		dol_print_error($db,$ecmdir->error);
-    		exit;
+	    	$result=$ecmdir->fetch($section);
+	    	if (! ($result > 0))
+	    	{
+	    		dol_print_error($db,$ecmdir->error);
+	    		exit;
+	    	}
+	    	$relativepath=$ecmdir->getRelativePath();
     	}
-    	$relativepath=$ecmdir->getRelativePath();
-    	$upload_dir = $conf->ecm->dir_output.'/'.$relativepath;
-    	$file = $upload_dir . "/" . GETPOST('urlfile');	// Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
+    	else $relativepath='';
+    	$upload_dir = $conf->ecm->dir_output.($relativepath?'/'.$relativepath:'');
+    	$file = $upload_dir . "/" . GETPOST('urlfile');	// Do not use urldecode here ($_GET and $_POST are already decoded by PHP).
 
     	$ret=dol_delete_file($file);
     	if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('urlfile')));
@@ -391,7 +396,7 @@ if (!empty($conf->global->ECM_AUTO_TREE_ENABLED)) {
 	if (! empty($conf->fournisseur->enabled)) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'order_supplier',   'test'=>$conf->fournisseur->enabled, 'label'=>$langs->trans("SuppliersOrders"),     'desc'=>$langs->trans("ECMDocsByOrders")); }
 	if (! empty($conf->fournisseur->enabled)) { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'invoice_supplier', 'test'=>$conf->fournisseur->enabled, 'label'=>$langs->trans("SuppliersInvoices"),   'desc'=>$langs->trans("ECMDocsByInvoices")); }
 	if (! empty($conf->tax->enabled))         { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'tax', 'test'=>$conf->tax->enabled, 'label'=>$langs->trans("SocialContributions"),     'desc'=>$langs->trans("ECMDocsBySocialContributions")); }
-	if (! empty($conf->projet->enabled))         { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'project', 'test'=>$conf->projet->enabled, 'label'=>$langs->trans("Projects"),     'desc'=>$langs->trans("ECMDocsByProjects")); }
+	if (! empty($conf->projet->enabled))      { $rowspan++; $sectionauto[]=array('level'=>1, 'module'=>'project', 'test'=>$conf->projet->enabled, 'label'=>$langs->trans("Projects"),     'desc'=>$langs->trans("ECMDocsByProjects")); }
 }
 
 print_fiche_titre($langs->trans("ECMArea").' - '.$langs->trans("ECMFileManager"));
@@ -461,7 +466,6 @@ if ($action == 'delete_section')
 // End confirm
 
 
-
 if (empty($action) || $action == 'file_manager' || preg_match('/refresh/i',$action) || $action == 'delete')
 {
 	print '<table width="100%" class="nobordernopadding">';
@@ -774,8 +778,19 @@ include_once DOL_DOCUMENT_ROOT.'/core/ajax/ajaxdirpreview.php';
 // To attach new file
 if ((! empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) || ! empty($section))
 {
+	if (empty($section) || $section == -1)
+	{
+		?>
+		<script type="text/javascript">
+    	jQuery(document).ready(function() {
+			jQuery('#formuserfile').hide();
+    	});
+    	</script>
+		<?php
+	}
+	
     $formfile=new FormFile($db);
-	$formfile->form_attach_new_file(DOL_URL_ROOT.'/ecm/index.php', 'none', 0, ($section?$section:-1), $user->rights->ecm->upload, 48, null, '', 0, '', 0);
+	$formfile->form_attach_new_file(DOL_URL_ROOT.'/ecm/index.php', 'none', 0, ($section?$section:-1), $user->rights->ecm->upload, 48, null, '', 0, '', 0, 'formuserfile');
 }
 else print '&nbsp;';
 
@@ -789,6 +804,8 @@ else print '&nbsp;';
 <?php
 // End of page
 
+
+
 if (! empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) {
 	include 'tpl/builddatabase.tpl.php';
 }
diff --git a/htdocs/ecm/tpl/builddatabase.tpl.php b/htdocs/ecm/tpl/builddatabase.tpl.php
index 7f997ed6209..4d5c0ab953a 100644
--- a/htdocs/ecm/tpl/builddatabase.tpl.php
+++ b/htdocs/ecm/tpl/builddatabase.tpl.php
@@ -13,28 +13,39 @@
  *
  * You should have received a copy of the GNU General Public License
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
- *
+ * 
+ * Output javascript for interactions code of ecm module
  */
+?>
 
-$openeddir='/';
+<!-- BEGIN PHP TEMPLATE ecm/tpl/builddatabase.tpl.php -->
+<!-- Doc of fileTree plugin at http://www.abeautifulsite.net/blog/2008/03/jquery-file-tree/ -->
 
-// TODO: just use ajaxdirtree.php for load database after ajax refresh and not scan directories
-// too slow every page loaded !
+<script type="text/javascript">
 
+<?php
+$openeddir='/';
 ?>
 
-<!-- BEGIN PHP TEMPLATE FOR JQUERY -->
-<script type="text/javascript">
-$(document).ready( function() {
-	$('#filetree').fileTree({ root: '<?php print dol_escape_js($openeddir); ?>',
-			// Called if we click on a file (not a dir)
-			script: '<?php echo DOL_URL_ROOT.'/core/ajax/ajaxdirtree.php?modulepart=ecm&openeddir='.urlencode($openeddir); ?>',
-			folderEvent: 'click',
-			multiFolder: false  },
-			// Called if we click on a file (not a dir)
+$(document).ready(function() {
+
+	$('#filetree').fileTree({ 
+		root: '<?php print dol_escape_js($openeddir); ?>',
+		// Ajax called if we click to expand a dir (not a file). Parameter of dir is provided as a POST parameter.
+		script: '<?php echo DOL_URL_ROOT.'/core/ajax/ajaxdirtree.php?modulepart=ecm&openeddir='.urlencode($openeddir); ?>',
+		folderEvent: 'click',	// 'dblclick'
+		multiFolder: false  },
+		// Called if we click on a file (not a dir)
 		function(file) {
 			$("#mesg").hide();
 			loadandshowpreview(file,0);
+		},
+		// Called if we click on a dir (not a file)
+		function(elem) {
+			id=elem.attr('id').substr(12);
+			jQuery("#formuserfile_section_dir").val(elem.attr('rel'));
+   			jQuery("#formuserfile_section_id").val(id);
+			jQuery('#formuserfile').show();
 		}
 	);
 
@@ -78,5 +89,6 @@ ecmBuildDatabase = function() {
 		location.href="<?php echo $_SERVER['PHP_SELF']; ?>";
 	});
 };
+
 </script>
-<!-- END PHP TEMPLATE FOR JQUERY -->
\ No newline at end of file
+<!-- END PHP TEMPLATE ecm/tpl/builddatabase.tpl.php -->
\ No newline at end of file
diff --git a/htdocs/includes/jquery/plugins/jqueryFileTree/jqueryFileTree.js b/htdocs/includes/jquery/plugins/jqueryFileTree/jqueryFileTree.js
index c9b0e3853df..390f71cda16 100755
--- a/htdocs/includes/jquery/plugins/jqueryFileTree/jqueryFileTree.js
+++ b/htdocs/includes/jquery/plugins/jqueryFileTree/jqueryFileTree.js
@@ -33,7 +33,7 @@
 if(jQuery) (function($){
 	
 	$.extend($.fn, {
-		fileTree: function(o, h) {
+		fileTree: function(o, h, hd) {	// CHANGE DOL_LDR add hd param
 			// Defaults
 			if( !o ) var o = {};
 			if( o.root == undefined ) o.root = '/';
@@ -77,6 +77,8 @@ if(jQuery) (function($){
 								$(this).parent().find('UL').slideUp({ duration: o.collapseSpeed, easing: o.collapseEasing });
 								$(this).parent().removeClass('expanded').addClass('collapsed');
 							}
+							// CHANGE DOL_LDR use hd function provided in param
+							if (hd != null) hd($(this));
 						} else {
 							h($(this).attr('rel'));
 						}
-- 
GitLab