Test Failed
Push — master ( e0c20c...b8c830 )
by Alxarafe
39:29
created
dolibarr/htdocs/core/class/interfaces.class.php 3 patches
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -36,12 +36,12 @@  discard block
 block discarded – undo
36 36
      */
37 37
     public $db;
38 38
 
39
-	var $dir;				// Directory with all core and external triggers files
39
+    var $dir;				// Directory with all core and external triggers files
40 40
 
41 41
     /**
42
-	 * @var string[] Error codes (or messages)
43
-	 */
44
-	public $errors = array();
42
+     * @var string[] Error codes (or messages)
43
+     */
44
+    public $errors = array();
45 45
 
46 46
     /**
47 47
      *	Constructor
@@ -71,9 +71,9 @@  discard block
 block discarded – undo
71 71
         // Check parameters
72 72
         if (! is_object($object) || ! is_object($conf))	// Error
73 73
         {
74
-        	$this->error='function run_triggers called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf);
74
+            $this->error='function run_triggers called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf);
75 75
             dol_syslog(get_class($this).'::run_triggers '.$this->error, LOG_ERR);
76
-        	$this->errors[]=$this->error;
76
+            $this->errors[]=$this->error;
77 77
             return -1;
78 78
         }
79 79
         if (! is_object($langs))	// Warning
@@ -92,9 +92,9 @@  discard block
 block discarded – undo
92 92
         $files = array();
93 93
         $modules = array();
94 94
         $orders = array();
95
-		$i=0;
95
+        $i=0;
96 96
 
97
-		$dirtriggers=array_merge(array('/core/triggers'),$conf->modules_parts['triggers']);
97
+        $dirtriggers=array_merge(array('/core/triggers'),$conf->modules_parts['triggers']);
98 98
         foreach($dirtriggers as $reldir)
99 99
         {
100 100
             $dir=dol_buildpath($reldir,0);
@@ -111,9 +111,9 @@  discard block
 block discarded – undo
111 111
                 {
112 112
                     if (is_readable($newdir."/".$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php$/i',$file,$reg))
113 113
                     {
114
-						$part1=$reg[1];
115
-						$part2=$reg[2];
116
-						$part3=$reg[3];
114
+                        $part1=$reg[1];
115
+                        $part2=$reg[2];
116
+                        $part3=$reg[3];
117 117
 
118 118
                         $nbfile++;
119 119
 
@@ -175,22 +175,22 @@  discard block
 block discarded – undo
175 175
             $objMod = new $modName($this->db);
176 176
             if ($objMod)
177 177
             {
178
-            	$result=0;
179
-
180
-				if (method_exists($objMod, 'runTrigger'))	// New method to implement
181
-				{
182
-	                //dol_syslog(get_class($this)."::run_triggers action=".$action." Launch runTrigger for file '".$files[$key]."'", LOG_DEBUG);
183
-	                $result=$objMod->runTrigger($action,$object,$user,$langs,$conf);
184
-				}
185
-				elseif (method_exists($objMod, 'run_trigger'))	// Deprecated method
186
-				{
187
-	                dol_syslog(get_class($this)."::run_triggers action=".$action." Launch old method run_trigger (rename your trigger into runTrigger) for file '".$files[$key]."'", LOG_WARNING);
188
-					$result=$objMod->run_trigger($action,$object,$user,$langs,$conf);
189
-				}
190
-				else
191
-				{
192
-	                dol_syslog(get_class($this)."::run_triggers action=".$action." A trigger was declared for class ".get_class($objMod)." but method runTrigger was not found", LOG_ERR);
193
-				}
178
+                $result=0;
179
+
180
+                if (method_exists($objMod, 'runTrigger'))	// New method to implement
181
+                {
182
+                    //dol_syslog(get_class($this)."::run_triggers action=".$action." Launch runTrigger for file '".$files[$key]."'", LOG_DEBUG);
183
+                    $result=$objMod->runTrigger($action,$object,$user,$langs,$conf);
184
+                }
185
+                elseif (method_exists($objMod, 'run_trigger'))	// Deprecated method
186
+                {
187
+                    dol_syslog(get_class($this)."::run_triggers action=".$action." Launch old method run_trigger (rename your trigger into runTrigger) for file '".$files[$key]."'", LOG_WARNING);
188
+                    $result=$objMod->run_trigger($action,$object,$user,$langs,$conf);
189
+                }
190
+                else
191
+                {
192
+                    dol_syslog(get_class($this)."::run_triggers action=".$action." A trigger was declared for class ".get_class($objMod)." but method runTrigger was not found", LOG_ERR);
193
+                }
194 194
 
195 195
                 if ($result > 0)
196 196
                 {
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
                 }
216 216
             }
217 217
             else
218
-			{
218
+            {
219 219
                 dol_syslog(get_class($this)."::run_triggers action=".$action." Failed to instantiate trigger for file '".$files[$key]."'", LOG_ERR);
220 220
             }
221 221
         }
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
         $dirtriggers=array_merge(array('/core/triggers/'),$conf->modules_parts['triggers']);
255 255
         if (is_array($forcedirtriggers))
256 256
         {
257
-        	$dirtriggers=$forcedirtriggers;
257
+            $dirtriggers=$forcedirtriggers;
258 258
         }
259 259
 
260 260
         foreach($dirtriggers as $reldir)
@@ -274,9 +274,9 @@  discard block
 block discarded – undo
274 274
                     {
275 275
                         if (preg_match('/\.back$/',$file)) continue;
276 276
 
277
-						$part1=$reg[1];
278
-						$part2=$reg[2];
279
-						$part3=$reg[3];
277
+                        $part1=$reg[1];
278
+                        $part2=$reg[2];
279
+                        $part3=$reg[3];
280 280
 
281 281
                         $modName = 'Interface'.ucfirst($reg[3]);
282 282
                         //print "file=$file"; print "modName=$modName"; exit;
@@ -317,8 +317,8 @@  discard block
 block discarded – undo
317 317
 
318 318
             if (! class_exists($modName))
319 319
             {
320
-				print 'Error: A trigger file was found but its class "'.$modName.'" was not found.'."<br>\n";
321
-            	continue;
320
+                print 'Error: A trigger file was found but its class "'.$modName.'" was not found.'."<br>\n";
321
+                continue;
322 322
             }
323 323
 
324 324
             $objMod = new $modName($db);
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
                 $triggers[$j]['module']=strtolower($module);
341 341
             }
342 342
 
343
-			// We set info of modules
343
+            // We set info of modules
344 344
             $triggers[$j]['picto'] = $objMod->picto?img_object('',$objMod->picto):img_object('','generic');
345 345
             $triggers[$j]['file'] = $files[$key];
346 346
             $triggers[$j]['fullpath'] = $fullpath[$key];
Please login to merge, or discard this patch.
Spacing   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
      */
37 37
     public $db;
38 38
 
39
-	var $dir;				// Directory with all core and external triggers files
39
+	var $dir; // Directory with all core and external triggers files
40 40
 
41 41
     /**
42 42
 	 * @var string[] Error codes (or messages)
@@ -65,22 +65,22 @@  discard block
 block discarded – undo
65 65
      *   @param     Conf		$conf       Objet conf
66 66
      *   @return    int         			Nb of triggers ran if no error, -Nb of triggers with errors otherwise.
67 67
      */
68
-    function run_triggers($action,$object,$user,$langs,$conf)
68
+    function run_triggers($action, $object, $user, $langs, $conf)
69 69
     {
70 70
         // phpcs:enable
71 71
         // Check parameters
72
-        if (! is_object($object) || ! is_object($conf))	// Error
72
+        if (!is_object($object) || !is_object($conf))	// Error
73 73
         {
74
-        	$this->error='function run_triggers called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf);
74
+        	$this->error = 'function run_triggers called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf);
75 75
             dol_syslog(get_class($this).'::run_triggers '.$this->error, LOG_ERR);
76
-        	$this->errors[]=$this->error;
76
+        	$this->errors[] = $this->error;
77 77
             return -1;
78 78
         }
79
-        if (! is_object($langs))	// Warning
79
+        if (!is_object($langs))	// Warning
80 80
         {
81 81
             dol_syslog(get_class($this).'::run_triggers was called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf), LOG_WARNING);
82 82
         }
83
-        if (! is_object($user))	    // Warning
83
+        if (!is_object($user))	    // Warning
84 84
         {
85 85
             dol_syslog(get_class($this).'::run_triggers was called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf), LOG_WARNING);
86 86
             global $db;
@@ -92,43 +92,43 @@  discard block
 block discarded – undo
92 92
         $files = array();
93 93
         $modules = array();
94 94
         $orders = array();
95
-		$i=0;
95
+		$i = 0;
96 96
 
97
-		$dirtriggers=array_merge(array('/core/triggers'),$conf->modules_parts['triggers']);
98
-        foreach($dirtriggers as $reldir)
97
+		$dirtriggers = array_merge(array('/core/triggers'), $conf->modules_parts['triggers']);
98
+        foreach ($dirtriggers as $reldir)
99 99
         {
100
-            $dir=dol_buildpath($reldir,0);
101
-            $newdir=dol_osencode($dir);
100
+            $dir = dol_buildpath($reldir, 0);
101
+            $newdir = dol_osencode($dir);
102 102
             //print "xx".$dir;exit;
103 103
 
104 104
             // Check if directory exists (we do not use dol_is_dir to avoir loading files.lib.php at each call)
105
-            if (! is_dir($newdir)) continue;
105
+            if (!is_dir($newdir)) continue;
106 106
 
107
-            $handle=opendir($newdir);
107
+            $handle = opendir($newdir);
108 108
             if (is_resource($handle))
109 109
             {
110
-                while (($file = readdir($handle))!==false)
110
+                while (($file = readdir($handle)) !== false)
111 111
                 {
112
-                    if (is_readable($newdir."/".$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php$/i',$file,$reg))
112
+                    if (is_readable($newdir."/".$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php$/i', $file, $reg))
113 113
                     {
114
-						$part1=$reg[1];
115
-						$part2=$reg[2];
116
-						$part3=$reg[3];
114
+						$part1 = $reg[1];
115
+						$part2 = $reg[2];
116
+						$part3 = $reg[3];
117 117
 
118 118
                         $nbfile++;
119 119
 
120 120
                         // Check if trigger file is disabled by name
121
-                        if (preg_match('/NORUN$/i',$file)) continue;
121
+                        if (preg_match('/NORUN$/i', $file)) continue;
122 122
                         // Check if trigger file is for a particular module
123
-                        $qualified=true;
123
+                        $qualified = true;
124 124
                         if (strtolower($reg[2]) != 'all')
125 125
                         {
126
-                            $module=preg_replace('/^mod/i','',$reg[2]);
127
-                            $constparam='MAIN_MODULE_'.strtoupper($module);
128
-                            if (empty($conf->global->$constparam)) $qualified=false;
126
+                            $module = preg_replace('/^mod/i', '', $reg[2]);
127
+                            $constparam = 'MAIN_MODULE_'.strtoupper($module);
128
+                            if (empty($conf->global->$constparam)) $qualified = false;
129 129
                         }
130 130
 
131
-                        if (! $qualified)
131
+                        if (!$qualified)
132 132
                         {
133 133
                             //dol_syslog(get_class($this)."::run_triggers action=".$action." Triggers for file '".$file."' need module to be enabled", LOG_DEBUG);
134 134
                             continue;
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
 
137 137
                         $modName = "Interface".ucfirst($reg[3]);
138 138
                         //print "file=$file - modName=$modName\n";
139
-                        if (in_array($modName,$modules))    // $modules = list of modName already loaded
139
+                        if (in_array($modName, $modules))    // $modules = list of modName already loaded
140 140
                         {
141 141
                             $langs->load("errors");
142 142
                             dol_syslog(get_class($this)."::run_triggers action=".$action." ".$langs->trans("ErrorDuplicateTrigger", $newdir."/".$file, $fullpathfiles[$modName]), LOG_WARNING);
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
                             include_once $newdir.'/'.$file;
149 149
                             //print 'Done for '.$modName."\n";
150 150
                         }
151
-                        catch(Exception $e)
151
+                        catch (Exception $e)
152 152
                         {
153 153
                             dol_syslog('ko for '.$modName." ".$e->getMessage()."\n", LOG_ERR);
154 154
                         }
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
                         $modules[$i] = $modName;
157 157
                         $files[$i] = $file;
158 158
                         $fullpathfiles[$modName] = $newdir.'/'.$file;
159
-                        $orders[$i] = $part1.'_'.$part2.'_'.$part3;   // Set sort criteria value
159
+                        $orders[$i] = $part1.'_'.$part2.'_'.$part3; // Set sort criteria value
160 160
 
161 161
                         $i++;
162 162
                     }
@@ -175,17 +175,17 @@  discard block
 block discarded – undo
175 175
             $objMod = new $modName($this->db);
176 176
             if ($objMod)
177 177
             {
178
-            	$result=0;
178
+            	$result = 0;
179 179
 
180 180
 				if (method_exists($objMod, 'runTrigger'))	// New method to implement
181 181
 				{
182 182
 	                //dol_syslog(get_class($this)."::run_triggers action=".$action." Launch runTrigger for file '".$files[$key]."'", LOG_DEBUG);
183
-	                $result=$objMod->runTrigger($action,$object,$user,$langs,$conf);
183
+	                $result = $objMod->runTrigger($action, $object, $user, $langs, $conf);
184 184
 				}
185 185
 				elseif (method_exists($objMod, 'run_trigger'))	// Deprecated method
186 186
 				{
187 187
 	                dol_syslog(get_class($this)."::run_triggers action=".$action." Launch old method run_trigger (rename your trigger into runTrigger) for file '".$files[$key]."'", LOG_WARNING);
188
-					$result=$objMod->run_trigger($action,$object,$user,$langs,$conf);
188
+					$result = $objMod->run_trigger($action, $object, $user, $langs, $conf);
189 189
 				}
190 190
 				else
191 191
 				{
@@ -209,8 +209,8 @@  discard block
 block discarded – undo
209 209
                     //dol_syslog("Error in trigger ".$action." - Nb of error string returned = ".count($objMod->errors), LOG_ERR);
210 210
                     $nbtotal++;
211 211
                     $nbko++;
212
-                    if (! empty($objMod->errors)) $this->errors=array_merge($this->errors,$objMod->errors);
213
-                    else if (! empty($objMod->error))  $this->errors[]=$objMod->error;
212
+                    if (!empty($objMod->errors)) $this->errors = array_merge($this->errors, $objMod->errors);
213
+                    else if (!empty($objMod->error))  $this->errors[] = $objMod->error;
214 214
                     //dol_syslog("Error in trigger ".$action." - Nb of error string returned = ".count($this->errors), LOG_ERR);
215 215
                 }
216 216
             }
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
      *	@param	array		$forcedirtriggers		null=All default directories. This parameter is used by modulebuilder module only.
240 240
      * 	@return	array								Array list of triggers
241 241
      */
242
-    function getTriggersList($forcedirtriggers=null)
242
+    function getTriggersList($forcedirtriggers = null)
243 243
     {
244 244
         global $conf, $langs, $db;
245 245
 
@@ -251,39 +251,39 @@  discard block
 block discarded – undo
251 251
         $orders = array();
252 252
         $i = 0;
253 253
 
254
-        $dirtriggers=array_merge(array('/core/triggers/'),$conf->modules_parts['triggers']);
254
+        $dirtriggers = array_merge(array('/core/triggers/'), $conf->modules_parts['triggers']);
255 255
         if (is_array($forcedirtriggers))
256 256
         {
257
-        	$dirtriggers=$forcedirtriggers;
257
+        	$dirtriggers = $forcedirtriggers;
258 258
         }
259 259
 
260
-        foreach($dirtriggers as $reldir)
260
+        foreach ($dirtriggers as $reldir)
261 261
         {
262
-            $dir=dol_buildpath($reldir,0);
263
-            $newdir=dol_osencode($dir);
262
+            $dir = dol_buildpath($reldir, 0);
263
+            $newdir = dol_osencode($dir);
264 264
 
265 265
             // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php at each call)
266
-            if (! is_dir($newdir)) continue;
266
+            if (!is_dir($newdir)) continue;
267 267
 
268
-            $handle=opendir($newdir);
268
+            $handle = opendir($newdir);
269 269
             if (is_resource($handle))
270 270
             {
271
-                while (($file = readdir($handle))!==false)
271
+                while (($file = readdir($handle)) !== false)
272 272
                 {
273
-                    if (is_readable($newdir.'/'.$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/',$file,$reg))
273
+                    if (is_readable($newdir.'/'.$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/', $file, $reg))
274 274
                     {
275
-                        if (preg_match('/\.back$/',$file)) continue;
275
+                        if (preg_match('/\.back$/', $file)) continue;
276 276
 
277
-						$part1=$reg[1];
278
-						$part2=$reg[2];
279
-						$part3=$reg[3];
277
+						$part1 = $reg[1];
278
+						$part2 = $reg[2];
279
+						$part3 = $reg[3];
280 280
 
281 281
                         $modName = 'Interface'.ucfirst($reg[3]);
282 282
                         //print "file=$file"; print "modName=$modName"; exit;
283
-                        if (in_array($modName,$modules))
283
+                        if (in_array($modName, $modules))
284 284
                         {
285 285
                             $langs->load("errors");
286
-                            print '<div class="error">'.$langs->trans("Error").' : '.$langs->trans("ErrorDuplicateTrigger",$modName,"/htdocs/core/triggers/").'</div>';
286
+                            print '<div class="error">'.$langs->trans("Error").' : '.$langs->trans("ErrorDuplicateTrigger", $modName, "/htdocs/core/triggers/").'</div>';
287 287
                         }
288 288
                         else
289 289
                         {
@@ -292,10 +292,10 @@  discard block
 block discarded – undo
292 292
 
293 293
                         $files[$i] = $file;
294 294
                         $fullpath[$i] = $dir.'/'.$file;
295
-                        $relpath[$i] = preg_replace('/^\//','',$reldir).'/'.$file;
296
-                        $iscoreorexternal[$i] = ($reldir == '/core/triggers/'?'internal':'external');
295
+                        $relpath[$i] = preg_replace('/^\//', '', $reldir).'/'.$file;
296
+                        $iscoreorexternal[$i] = ($reldir == '/core/triggers/' ? 'internal' : 'external');
297 297
                         $modules[$i] = $modName;
298
-                        $orders[$i] = $part1.'_'.$part2.'_'.$part3;   // Set sort criteria value
298
+                        $orders[$i] = $part1.'_'.$part2.'_'.$part3; // Set sort criteria value
299 299
 
300 300
                         $i++;
301 301
                     }
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
             $modName = $modules[$key];
316 316
             if (empty($modName)) continue;
317 317
 
318
-            if (! class_exists($modName))
318
+            if (!class_exists($modName))
319 319
             {
320 320
 				print 'Error: A trigger file was found but its class "'.$modName.'" was not found.'."<br>\n";
321 321
             	continue;
@@ -324,45 +324,45 @@  discard block
 block discarded – undo
324 324
             $objMod = new $modName($db);
325 325
 
326 326
             // Define disabledbyname and disabledbymodule
327
-            $disabledbyname=0;
328
-            $disabledbymodule=1;
329
-            $module='';
327
+            $disabledbyname = 0;
328
+            $disabledbymodule = 1;
329
+            $module = '';
330 330
 
331 331
             // Check if trigger file is disabled by name
332
-            if (preg_match('/NORUN$/i',$files[$key])) $disabledbyname=1;
332
+            if (preg_match('/NORUN$/i', $files[$key])) $disabledbyname = 1;
333 333
             // Check if trigger file is for a particular module
334
-            if (preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/i',$files[$key],$reg))
334
+            if (preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/i', $files[$key], $reg))
335 335
             {
336
-                $module=preg_replace('/^mod/i','',$reg[2]);
337
-                $constparam='MAIN_MODULE_'.strtoupper($module);
338
-                if (strtolower($module) == 'all') $disabledbymodule=0;
339
-                else if (empty($conf->global->$constparam)) $disabledbymodule=2;
340
-                $triggers[$j]['module']=strtolower($module);
336
+                $module = preg_replace('/^mod/i', '', $reg[2]);
337
+                $constparam = 'MAIN_MODULE_'.strtoupper($module);
338
+                if (strtolower($module) == 'all') $disabledbymodule = 0;
339
+                else if (empty($conf->global->$constparam)) $disabledbymodule = 2;
340
+                $triggers[$j]['module'] = strtolower($module);
341 341
             }
342 342
 
343 343
 			// We set info of modules
344
-            $triggers[$j]['picto'] = $objMod->picto?img_object('',$objMod->picto):img_object('','generic');
344
+            $triggers[$j]['picto'] = $objMod->picto ?img_object('', $objMod->picto) : img_object('', 'generic');
345 345
             $triggers[$j]['file'] = $files[$key];
346 346
             $triggers[$j]['fullpath'] = $fullpath[$key];
347 347
             $triggers[$j]['relpath'] = $relpath[$key];
348 348
             $triggers[$j]['iscoreorexternal'] = $iscoreorexternal[$key];
349 349
             $triggers[$j]['version'] = $objMod->getVersion();
350
-            $triggers[$j]['status'] = img_picto($langs->trans("Active"),'tick');
350
+            $triggers[$j]['status'] = img_picto($langs->trans("Active"), 'tick');
351 351
             if ($disabledbyname > 0 || $disabledbymodule > 1) $triggers[$j]['status'] = '';
352 352
 
353
-            $text ='<b>'.$langs->trans("Description").':</b><br>';
354
-            $text.=$objMod->getDesc().'<br>';
355
-            $text.='<br><b>'.$langs->trans("Status").':</b><br>';
353
+            $text = '<b>'.$langs->trans("Description").':</b><br>';
354
+            $text .= $objMod->getDesc().'<br>';
355
+            $text .= '<br><b>'.$langs->trans("Status").':</b><br>';
356 356
             if ($disabledbyname == 1)
357 357
             {
358
-                $text.=$langs->trans("TriggerDisabledByName").'<br>';
359
-                if ($disabledbymodule == 2) $text.=$langs->trans("TriggerDisabledAsModuleDisabled",$module).'<br>';
358
+                $text .= $langs->trans("TriggerDisabledByName").'<br>';
359
+                if ($disabledbymodule == 2) $text .= $langs->trans("TriggerDisabledAsModuleDisabled", $module).'<br>';
360 360
             }
361 361
             else
362 362
             {
363
-                if ($disabledbymodule == 0) $text.=$langs->trans("TriggerAlwaysActive").'<br>';
364
-                if ($disabledbymodule == 1) $text.=$langs->trans("TriggerActiveAsModuleActive",$module).'<br>';
365
-                if ($disabledbymodule == 2) $text.=$langs->trans("TriggerDisabledAsModuleDisabled",$module).'<br>';
363
+                if ($disabledbymodule == 0) $text .= $langs->trans("TriggerAlwaysActive").'<br>';
364
+                if ($disabledbymodule == 1) $text .= $langs->trans("TriggerActiveAsModuleActive", $module).'<br>';
365
+                if ($disabledbymodule == 2) $text .= $langs->trans("TriggerDisabledAsModuleDisabled", $module).'<br>';
366 366
             }
367 367
 
368 368
             $triggers[$j]['info'] = $text;
Please login to merge, or discard this patch.
Braces   +72 added lines, -35 removed lines patch added patch discarded remove patch
@@ -69,20 +69,26 @@  discard block
 block discarded – undo
69 69
     {
70 70
         // phpcs:enable
71 71
         // Check parameters
72
-        if (! is_object($object) || ! is_object($conf))	// Error
72
+        if (! is_object($object) || ! is_object($conf)) {
73
+            // Error
73 74
         {
74 75
         	$this->error='function run_triggers called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf);
76
+        }
75 77
             dol_syslog(get_class($this).'::run_triggers '.$this->error, LOG_ERR);
76 78
         	$this->errors[]=$this->error;
77 79
             return -1;
78 80
         }
79
-        if (! is_object($langs))	// Warning
81
+        if (! is_object($langs)) {
82
+            // Warning
80 83
         {
81 84
             dol_syslog(get_class($this).'::run_triggers was called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf), LOG_WARNING);
82 85
         }
83
-        if (! is_object($user))	    // Warning
86
+        }
87
+        if (! is_object($user)) {
88
+            // Warning
84 89
         {
85 90
             dol_syslog(get_class($this).'::run_triggers was called with wrong parameters action='.$action.' object='.is_object($object).' user='.is_object($user).' langs='.is_object($langs).' conf='.is_object($conf), LOG_WARNING);
91
+        }
86 92
             global $db;
87 93
             $user = new User($db);
88 94
         }
@@ -102,7 +108,9 @@  discard block
 block discarded – undo
102 108
             //print "xx".$dir;exit;
103 109
 
104 110
             // Check if directory exists (we do not use dol_is_dir to avoir loading files.lib.php at each call)
105
-            if (! is_dir($newdir)) continue;
111
+            if (! is_dir($newdir)) {
112
+                continue;
113
+            }
106 114
 
107 115
             $handle=opendir($newdir);
108 116
             if (is_resource($handle))
@@ -118,14 +126,18 @@  discard block
 block discarded – undo
118 126
                         $nbfile++;
119 127
 
120 128
                         // Check if trigger file is disabled by name
121
-                        if (preg_match('/NORUN$/i',$file)) continue;
129
+                        if (preg_match('/NORUN$/i',$file)) {
130
+                            continue;
131
+                        }
122 132
                         // Check if trigger file is for a particular module
123 133
                         $qualified=true;
124 134
                         if (strtolower($reg[2]) != 'all')
125 135
                         {
126 136
                             $module=preg_replace('/^mod/i','',$reg[2]);
127 137
                             $constparam='MAIN_MODULE_'.strtoupper($module);
128
-                            if (empty($conf->global->$constparam)) $qualified=false;
138
+                            if (empty($conf->global->$constparam)) {
139
+                                $qualified=false;
140
+                            }
129 141
                         }
130 142
 
131 143
                         if (! $qualified)
@@ -136,9 +148,11 @@  discard block
 block discarded – undo
136 148
 
137 149
                         $modName = "Interface".ucfirst($reg[3]);
138 150
                         //print "file=$file - modName=$modName\n";
139
-                        if (in_array($modName,$modules))    // $modules = list of modName already loaded
151
+                        if (in_array($modName,$modules)) {
152
+                            // $modules = list of modName already loaded
140 153
                         {
141 154
                             $langs->load("errors");
155
+                        }
142 156
                             dol_syslog(get_class($this)."::run_triggers action=".$action." ".$langs->trans("ErrorDuplicateTrigger", $newdir."/".$file, $fullpathfiles[$modName]), LOG_WARNING);
143 157
                             continue;
144 158
                         }
@@ -147,8 +161,7 @@  discard block
 block discarded – undo
147 161
                             //print 'Todo for '.$modName." : ".$newdir.'/'.$file."\n";
148 162
                             include_once $newdir.'/'.$file;
149 163
                             //print 'Done for '.$modName."\n";
150
-                        }
151
-                        catch(Exception $e)
164
+                        } catch(Exception $e)
152 165
                         {
153 166
                             dol_syslog('ko for '.$modName." ".$e->getMessage()."\n", LOG_ERR);
154 167
                         }
@@ -170,24 +183,28 @@  discard block
 block discarded – undo
170 183
         foreach ($orders as $key => $value)
171 184
         {
172 185
             $modName = $modules[$key];
173
-            if (empty($modName)) continue;
186
+            if (empty($modName)) {
187
+                continue;
188
+            }
174 189
 
175 190
             $objMod = new $modName($this->db);
176 191
             if ($objMod)
177 192
             {
178 193
             	$result=0;
179 194
 
180
-				if (method_exists($objMod, 'runTrigger'))	// New method to implement
195
+				if (method_exists($objMod, 'runTrigger')) {
196
+				    // New method to implement
181 197
 				{
182 198
 	                //dol_syslog(get_class($this)."::run_triggers action=".$action." Launch runTrigger for file '".$files[$key]."'", LOG_DEBUG);
183 199
 	                $result=$objMod->runTrigger($action,$object,$user,$langs,$conf);
184 200
 				}
185
-				elseif (method_exists($objMod, 'run_trigger'))	// Deprecated method
201
+				} elseif (method_exists($objMod, 'run_trigger')) {
202
+				    // Deprecated method
186 203
 				{
187 204
 	                dol_syslog(get_class($this)."::run_triggers action=".$action." Launch old method run_trigger (rename your trigger into runTrigger) for file '".$files[$key]."'", LOG_WARNING);
188
-					$result=$objMod->run_trigger($action,$object,$user,$langs,$conf);
189 205
 				}
190
-				else
206
+					$result=$objMod->run_trigger($action,$object,$user,$langs,$conf);
207
+				} else
191 208
 				{
192 209
 	                dol_syslog(get_class($this)."::run_triggers action=".$action." A trigger was declared for class ".get_class($objMod)." but method runTrigger was not found", LOG_ERR);
193 210
 				}
@@ -209,12 +226,14 @@  discard block
 block discarded – undo
209 226
                     //dol_syslog("Error in trigger ".$action." - Nb of error string returned = ".count($objMod->errors), LOG_ERR);
210 227
                     $nbtotal++;
211 228
                     $nbko++;
212
-                    if (! empty($objMod->errors)) $this->errors=array_merge($this->errors,$objMod->errors);
213
-                    else if (! empty($objMod->error))  $this->errors[]=$objMod->error;
229
+                    if (! empty($objMod->errors)) {
230
+                        $this->errors=array_merge($this->errors,$objMod->errors);
231
+                    } else if (! empty($objMod->error)) {
232
+                        $this->errors[]=$objMod->error;
233
+                    }
214 234
                     //dol_syslog("Error in trigger ".$action." - Nb of error string returned = ".count($this->errors), LOG_ERR);
215 235
                 }
216
-            }
217
-            else
236
+            } else
218 237
 			{
219 238
                 dol_syslog(get_class($this)."::run_triggers action=".$action." Failed to instantiate trigger for file '".$files[$key]."'", LOG_ERR);
220 239
             }
@@ -224,8 +243,7 @@  discard block
 block discarded – undo
224 243
         {
225 244
             dol_syslog(get_class($this)."::run_triggers action=".$action." Files found: ".$nbfile.", Files launched: ".$nbtotal.", Done: ".$nbok.", Failed: ".$nbko." - Nb of error string returned in this->errors = ".count($this->errors), LOG_ERR);
226 245
             return -$nbko;
227
-        }
228
-        else
246
+        } else
229 247
         {
230 248
             //dol_syslog(get_class($this)."::run_triggers Files found: ".$nbfile.", Files launched: ".$nbtotal.", Done: ".$nbok.", Failed: ".$nbko, LOG_DEBUG);
231 249
             return $nbok;
@@ -263,7 +281,9 @@  discard block
 block discarded – undo
263 281
             $newdir=dol_osencode($dir);
264 282
 
265 283
             // Check if directory exists (we do not use dol_is_dir to avoid loading files.lib.php at each call)
266
-            if (! is_dir($newdir)) continue;
284
+            if (! is_dir($newdir)) {
285
+                continue;
286
+            }
267 287
 
268 288
             $handle=opendir($newdir);
269 289
             if (is_resource($handle))
@@ -272,7 +292,9 @@  discard block
 block discarded – undo
272 292
                 {
273 293
                     if (is_readable($newdir.'/'.$file) && preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/',$file,$reg))
274 294
                     {
275
-                        if (preg_match('/\.back$/',$file)) continue;
295
+                        if (preg_match('/\.back$/',$file)) {
296
+                            continue;
297
+                        }
276 298
 
277 299
 						$part1=$reg[1];
278 300
 						$part2=$reg[2];
@@ -284,8 +306,7 @@  discard block
 block discarded – undo
284 306
                         {
285 307
                             $langs->load("errors");
286 308
                             print '<div class="error">'.$langs->trans("Error").' : '.$langs->trans("ErrorDuplicateTrigger",$modName,"/htdocs/core/triggers/").'</div>';
287
-                        }
288
-                        else
309
+                        } else
289 310
                         {
290 311
                             include_once $newdir.'/'.$file;
291 312
                         }
@@ -313,7 +334,9 @@  discard block
 block discarded – undo
313 334
         foreach ($orders as $key => $value)
314 335
         {
315 336
             $modName = $modules[$key];
316
-            if (empty($modName)) continue;
337
+            if (empty($modName)) {
338
+                continue;
339
+            }
317 340
 
318 341
             if (! class_exists($modName))
319 342
             {
@@ -329,14 +352,19 @@  discard block
 block discarded – undo
329 352
             $module='';
330 353
 
331 354
             // Check if trigger file is disabled by name
332
-            if (preg_match('/NORUN$/i',$files[$key])) $disabledbyname=1;
355
+            if (preg_match('/NORUN$/i',$files[$key])) {
356
+                $disabledbyname=1;
357
+            }
333 358
             // Check if trigger file is for a particular module
334 359
             if (preg_match('/^interface_([0-9]+)_([^_]+)_(.+)\.class\.php/i',$files[$key],$reg))
335 360
             {
336 361
                 $module=preg_replace('/^mod/i','',$reg[2]);
337 362
                 $constparam='MAIN_MODULE_'.strtoupper($module);
338
-                if (strtolower($module) == 'all') $disabledbymodule=0;
339
-                else if (empty($conf->global->$constparam)) $disabledbymodule=2;
363
+                if (strtolower($module) == 'all') {
364
+                    $disabledbymodule=0;
365
+                } else if (empty($conf->global->$constparam)) {
366
+                    $disabledbymodule=2;
367
+                }
340 368
                 $triggers[$j]['module']=strtolower($module);
341 369
             }
342 370
 
@@ -348,7 +376,9 @@  discard block
 block discarded – undo
348 376
             $triggers[$j]['iscoreorexternal'] = $iscoreorexternal[$key];
349 377
             $triggers[$j]['version'] = $objMod->getVersion();
350 378
             $triggers[$j]['status'] = img_picto($langs->trans("Active"),'tick');
351
-            if ($disabledbyname > 0 || $disabledbymodule > 1) $triggers[$j]['status'] = '';
379
+            if ($disabledbyname > 0 || $disabledbymodule > 1) {
380
+                $triggers[$j]['status'] = '';
381
+            }
352 382
 
353 383
             $text ='<b>'.$langs->trans("Description").':</b><br>';
354 384
             $text.=$objMod->getDesc().'<br>';
@@ -356,13 +386,20 @@  discard block
 block discarded – undo
356 386
             if ($disabledbyname == 1)
357 387
             {
358 388
                 $text.=$langs->trans("TriggerDisabledByName").'<br>';
359
-                if ($disabledbymodule == 2) $text.=$langs->trans("TriggerDisabledAsModuleDisabled",$module).'<br>';
360
-            }
361
-            else
389
+                if ($disabledbymodule == 2) {
390
+                    $text.=$langs->trans("TriggerDisabledAsModuleDisabled",$module).'<br>';
391
+                }
392
+            } else
362 393
             {
363
-                if ($disabledbymodule == 0) $text.=$langs->trans("TriggerAlwaysActive").'<br>';
364
-                if ($disabledbymodule == 1) $text.=$langs->trans("TriggerActiveAsModuleActive",$module).'<br>';
365
-                if ($disabledbymodule == 2) $text.=$langs->trans("TriggerDisabledAsModuleDisabled",$module).'<br>';
394
+                if ($disabledbymodule == 0) {
395
+                    $text.=$langs->trans("TriggerAlwaysActive").'<br>';
396
+                }
397
+                if ($disabledbymodule == 1) {
398
+                    $text.=$langs->trans("TriggerActiveAsModuleActive",$module).'<br>';
399
+                }
400
+                if ($disabledbymodule == 2) {
401
+                    $text.=$langs->trans("TriggerDisabledAsModuleDisabled",$module).'<br>';
402
+                }
366 403
             }
367 404
 
368 405
             $triggers[$j]['info'] = $text;
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/google.class.php 2 patches
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -26,63 +26,63 @@
 block discarded – undo
26 26
  */
27 27
 class GoogleAPI
28 28
 {
29
-	/**
29
+    /**
30 30
      * @var DoliDB Database handler.
31 31
      */
32 32
     public $db;
33 33
 
34
-	/**
35
-	 * @var string Error code (or message)
36
-	 */
37
-	public $error='';
34
+    /**
35
+     * @var string Error code (or message)
36
+     */
37
+    public $error='';
38 38
 
39
-	public $key;
39
+    public $key;
40 40
 
41
-	/**
42
-	 * Constructor
43
-	 *
44
-	 * @param 	DoliDB		$db			Database handler
45
-	 * @param	string		$key		Google key
46
-	 */
47
-	function __construct($db,$key)
48
-	{
49
-		$this->db=$db;
50
-		$this->key=$key;
51
-	}
41
+    /**
42
+     * Constructor
43
+     *
44
+     * @param 	DoliDB		$db			Database handler
45
+     * @param	string		$key		Google key
46
+     */
47
+    function __construct($db,$key)
48
+    {
49
+        $this->db=$db;
50
+        $this->key=$key;
51
+    }
52 52
 
53 53
 
54
-	/**
55
-	 *  Return geo coordinates of an address
56
-	 *
57
-	 *  @param	string	$address	Address
58
-	 * 								Example: 68 Grande rue Charles de Gaulle,+94130,+Nogent sur Marne,+France
59
-	 *								Example: 188, rue de Fontenay,+94300,+Vincennes,+France
60
-	 *	@return	string				Coordinates
61
-	 */
62
-	function getGeoCoordinatesOfAddress($address)
63
-	{
64
-		global $conf;
54
+    /**
55
+     *  Return geo coordinates of an address
56
+     *
57
+     *  @param	string	$address	Address
58
+     * 								Example: 68 Grande rue Charles de Gaulle,+94130,+Nogent sur Marne,+France
59
+     *								Example: 188, rue de Fontenay,+94300,+Vincennes,+France
60
+     *	@return	string				Coordinates
61
+     */
62
+    function getGeoCoordinatesOfAddress($address)
63
+    {
64
+        global $conf;
65 65
 
66
-		$i=0;
66
+        $i=0;
67 67
 
68
-		// Desired address
69
-		$urladdress = "https://maps.google.com/maps/geo?q=".urlencode($address)."&output=xml&key=".$this->key;
68
+        // Desired address
69
+        $urladdress = "https://maps.google.com/maps/geo?q=".urlencode($address)."&output=xml&key=".$this->key;
70 70
 
71
-		// Retrieve the URL contents
72
-		$page = file_get_contents($urladdress);
71
+        // Retrieve the URL contents
72
+        $page = file_get_contents($urladdress);
73 73
 
74
-		$code = strstr($page, '<coordinates>');
75
-		$code = strstr($code, '>');
76
-		$val=strpos($code, "<");
77
-		$code = substr($code, 1, $val-1);
78
-		//print $code;
79
-		//print "<br>";
80
-		$latitude = substr($code, 0, strpos($code, ","));
81
-		$longitude = substr($code, strpos($code, ",")+1, dol_strlen(strpos($code, ","))-3);
74
+        $code = strstr($page, '<coordinates>');
75
+        $code = strstr($code, '>');
76
+        $val=strpos($code, "<");
77
+        $code = substr($code, 1, $val-1);
78
+        //print $code;
79
+        //print "<br>";
80
+        $latitude = substr($code, 0, strpos($code, ","));
81
+        $longitude = substr($code, strpos($code, ",")+1, dol_strlen(strpos($code, ","))-3);
82 82
 
83
-		// Output the coordinates
84
-		//echo "Longitude: $longitude ',' Latitude: $latitude";
83
+        // Output the coordinates
84
+        //echo "Longitude: $longitude ',' Latitude: $latitude";
85 85
 
86
-		$i++;
87
-	}
86
+        $i++;
87
+    }
88 88
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
 	/**
35 35
 	 * @var string Error code (or message)
36 36
 	 */
37
-	public $error='';
37
+	public $error = '';
38 38
 
39 39
 	public $key;
40 40
 
@@ -44,10 +44,10 @@  discard block
 block discarded – undo
44 44
 	 * @param 	DoliDB		$db			Database handler
45 45
 	 * @param	string		$key		Google key
46 46
 	 */
47
-	function __construct($db,$key)
47
+	function __construct($db, $key)
48 48
 	{
49
-		$this->db=$db;
50
-		$this->key=$key;
49
+		$this->db = $db;
50
+		$this->key = $key;
51 51
 	}
52 52
 
53 53
 
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
 	{
64 64
 		global $conf;
65 65
 
66
-		$i=0;
66
+		$i = 0;
67 67
 
68 68
 		// Desired address
69 69
 		$urladdress = "https://maps.google.com/maps/geo?q=".urlencode($address)."&output=xml&key=".$this->key;
@@ -73,12 +73,12 @@  discard block
 block discarded – undo
73 73
 
74 74
 		$code = strstr($page, '<coordinates>');
75 75
 		$code = strstr($code, '>');
76
-		$val=strpos($code, "<");
77
-		$code = substr($code, 1, $val-1);
76
+		$val = strpos($code, "<");
77
+		$code = substr($code, 1, $val - 1);
78 78
 		//print $code;
79 79
 		//print "<br>";
80 80
 		$latitude = substr($code, 0, strpos($code, ","));
81
-		$longitude = substr($code, strpos($code, ",")+1, dol_strlen(strpos($code, ","))-3);
81
+		$longitude = substr($code, strpos($code, ",") + 1, dol_strlen(strpos($code, ",")) - 3);
82 82
 
83 83
 		// Output the coordinates
84 84
 		//echo "Longitude: $longitude ',' Latitude: $latitude";
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/commoninvoice.class.php 3 patches
Indentation   +698 added lines, -698 removed lines patch added patch discarded remove patch
@@ -61,624 +61,624 @@  discard block
 block discarded – undo
61 61
      */
62 62
     const TYPE_SITUATION = 5;
63 63
 
64
-	/**
65
-	 * Draft status
66
-	 */
67
-	const STATUS_DRAFT = 0;
68
-
69
-	/**
70
-	 * Validated (need to be paid)
71
-	 */
72
-	const STATUS_VALIDATED = 1;
73
-
74
-	/**
75
-	 * Classified paid.
76
-	 * If paid partially, $this->close_code can be:
77
-	 * - CLOSECODE_DISCOUNTVAT
78
-	 * - CLOSECODE_BADDEBT
79
-	 * If paid completelly, this->close_code will be null
80
-	 */
81
-	const STATUS_CLOSED = 2;
82
-
83
-	/**
84
-	 * Classified abandoned and no payment done.
85
-	 * $this->close_code can be:
86
-	 * - CLOSECODE_BADDEBT
87
-	 * - CLOSECODE_ABANDONED
88
-	 * - CLOSECODE_REPLACED
89
-	 */
90
-	const STATUS_ABANDONED = 3;
91
-
92
-
93
-	/**
94
-	 * 	Return remain amount to pay. Property ->id and ->total_ttc must be set.
95
-	 *  This does not include open direct debit requests.
96
-	 *
97
-	 *  @param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
98
-	 *	@return		double						Remain of amount to pay
99
-	 */
100
-	function getRemainToPay($multicurrency=0)
101
-	{
102
-	    $alreadypaid=0;
103
-	    $alreadypaid+=$this->getSommePaiement($multicurrency);
104
-	    $alreadypaid+=$this->getSumDepositsUsed($multicurrency);
105
-	    $alreadypaid+=$this->getSumCreditNotesUsed($multicurrency);
106
-    	return $this->total_ttc - $alreadypaid;
107
-	}
108
-
109
-	/**
110
-	 * 	Return amount of payments already done
111
-	 *
112
-	 *  @param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
113
-	 *	@return		int						Amount of payment already done, <0 if KO
114
-	 */
115
-	function getSommePaiement($multicurrency=0)
116
-	{
117
-		$table='paiement_facture';
118
-		$field='fk_facture';
119
-		if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
120
-		{
121
-			$table='paiementfourn_facturefourn';
122
-			$field='fk_facturefourn';
123
-		}
124
-
125
-		$sql = 'SELECT sum(amount) as amount, sum(multicurrency_amount) as multicurrency_amount';
126
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$table;
127
-		$sql.= ' WHERE '.$field.' = '.$this->id;
128
-
129
-		dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG);
130
-		$resql=$this->db->query($sql);
131
-		if ($resql)
132
-		{
133
-			$obj = $this->db->fetch_object($resql);
134
-			$this->db->free($resql);
135
-			if ($multicurrency) return $obj->multicurrency_amount;
136
-			else return $obj->amount;
137
-		}
138
-		else
139
-		{
140
-			$this->error=$this->db->lasterror();
141
-			return -1;
142
-		}
143
-	}
144
-
145
-	/**
146
-	 *    	Return amount (with tax) of all deposits invoices used by invoice.
64
+    /**
65
+     * Draft status
66
+     */
67
+    const STATUS_DRAFT = 0;
68
+
69
+    /**
70
+     * Validated (need to be paid)
71
+     */
72
+    const STATUS_VALIDATED = 1;
73
+
74
+    /**
75
+     * Classified paid.
76
+     * If paid partially, $this->close_code can be:
77
+     * - CLOSECODE_DISCOUNTVAT
78
+     * - CLOSECODE_BADDEBT
79
+     * If paid completelly, this->close_code will be null
80
+     */
81
+    const STATUS_CLOSED = 2;
82
+
83
+    /**
84
+     * Classified abandoned and no payment done.
85
+     * $this->close_code can be:
86
+     * - CLOSECODE_BADDEBT
87
+     * - CLOSECODE_ABANDONED
88
+     * - CLOSECODE_REPLACED
89
+     */
90
+    const STATUS_ABANDONED = 3;
91
+
92
+
93
+    /**
94
+     * 	Return remain amount to pay. Property ->id and ->total_ttc must be set.
95
+     *  This does not include open direct debit requests.
96
+     *
97
+     *  @param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
98
+     *	@return		double						Remain of amount to pay
99
+     */
100
+    function getRemainToPay($multicurrency=0)
101
+    {
102
+        $alreadypaid=0;
103
+        $alreadypaid+=$this->getSommePaiement($multicurrency);
104
+        $alreadypaid+=$this->getSumDepositsUsed($multicurrency);
105
+        $alreadypaid+=$this->getSumCreditNotesUsed($multicurrency);
106
+        return $this->total_ttc - $alreadypaid;
107
+    }
108
+
109
+    /**
110
+     * 	Return amount of payments already done
111
+     *
112
+     *  @param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
113
+     *	@return		int						Amount of payment already done, <0 if KO
114
+     */
115
+    function getSommePaiement($multicurrency=0)
116
+    {
117
+        $table='paiement_facture';
118
+        $field='fk_facture';
119
+        if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
120
+        {
121
+            $table='paiementfourn_facturefourn';
122
+            $field='fk_facturefourn';
123
+        }
124
+
125
+        $sql = 'SELECT sum(amount) as amount, sum(multicurrency_amount) as multicurrency_amount';
126
+        $sql.= ' FROM '.MAIN_DB_PREFIX.$table;
127
+        $sql.= ' WHERE '.$field.' = '.$this->id;
128
+
129
+        dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG);
130
+        $resql=$this->db->query($sql);
131
+        if ($resql)
132
+        {
133
+            $obj = $this->db->fetch_object($resql);
134
+            $this->db->free($resql);
135
+            if ($multicurrency) return $obj->multicurrency_amount;
136
+            else return $obj->amount;
137
+        }
138
+        else
139
+        {
140
+            $this->error=$this->db->lasterror();
141
+            return -1;
142
+        }
143
+    }
144
+
145
+    /**
146
+     *    	Return amount (with tax) of all deposits invoices used by invoice.
147 147
      *      Should always be empty, except if option FACTURE_DEPOSITS_ARE_JUST_PAYMENTS is on (not recommended).
148
-	 *
149
-	 * 		@param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
150
-	 *		@return		int						<0 if KO, Sum of deposits amount otherwise
151
-	 */
152
-	function getSumDepositsUsed($multicurrency=0)
153
-	{
154
-		if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
155
-	    {
156
-	        // TODO
157
-	       return 0;
158
-	    }
159
-
160
-	    require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
161
-
162
-	    $discountstatic=new DiscountAbsolute($this->db);
163
-	    $result=$discountstatic->getSumDepositsUsed($this, $multicurrency);
164
-	    if ($result >= 0)
165
-	    {
166
-	        return $result;
167
-	    }
168
-	    else
169
-	    {
170
-	        $this->error=$discountstatic->error;
171
-	        return -1;
172
-	    }
173
-	}
174
-
175
-	/**
176
-	 *    	Return amount (with tax) of all credit notes invoices + excess received used by invoice
177
-	 *
178
-	 * 		@param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
179
-	 *		@return		int						<0 if KO, Sum of credit notes and deposits amount otherwise
180
-	 */
181
-	function getSumCreditNotesUsed($multicurrency=0)
182
-	{
183
-	    require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
184
-
185
-	    $discountstatic=new DiscountAbsolute($this->db);
186
-	    $result=$discountstatic->getSumCreditNotesUsed($this, $multicurrency);
187
-	    if ($result >= 0)
188
-	    {
189
-	        return $result;
190
-	    }
191
-	    else
192
-	    {
193
-	        $this->error=$discountstatic->error;
194
-	        return -1;
195
-	    }
196
-	}
197
-
198
-	/**
199
-	 *	Renvoie tableau des ids de facture avoir issus de la facture
200
-	 *
201
-	 *	@return		array		Tableau d'id de factures avoirs
202
-	 */
203
-	function getListIdAvoirFromInvoice()
204
-	{
205
-		$idarray=array();
206
-
207
-		$sql = 'SELECT rowid';
208
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
209
-		$sql.= ' WHERE fk_facture_source = '.$this->id;
210
-		$sql.= ' AND type = 2';
211
-		$resql=$this->db->query($sql);
212
-		if ($resql)
213
-		{
214
-			$num = $this->db->num_rows($resql);
215
-			$i = 0;
216
-			while ($i < $num)
217
-			{
218
-				$row = $this->db->fetch_row($resql);
219
-				$idarray[]=$row[0];
220
-				$i++;
221
-			}
222
-		}
223
-		else
224
-		{
225
-			dol_print_error($this->db);
226
-		}
227
-		return $idarray;
228
-	}
229
-
230
-	/**
231
-	 *	Renvoie l'id de la facture qui la remplace
232
-	 *
233
-	 *	@param		string	$option		filtre sur statut ('', 'validated', ...)
234
-	 *	@return		int					<0 si KO, 0 si aucune facture ne remplace, id facture sinon
235
-	 */
236
-	function getIdReplacingInvoice($option='')
237
-	{
238
-		$sql = 'SELECT rowid';
239
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
240
-		$sql.= ' WHERE fk_facture_source = '.$this->id;
241
-		$sql.= ' AND type < 2';
242
-		if ($option == 'validated') $sql.= ' AND fk_statut = 1';
243
-		// PROTECTION BAD DATA
244
-		// Au cas ou base corrompue et qu'il y a une facture de remplacement validee
245
-		// et une autre non, on donne priorite a la validee.
246
-		// Ne devrait pas arriver (sauf si acces concurrentiel et que 2 personnes
247
-		// ont cree en meme temps une facture de remplacement pour la meme facture)
248
-		$sql.= ' ORDER BY fk_statut DESC';
249
-
250
-		$resql=$this->db->query($sql);
251
-		if ($resql)
252
-		{
253
-			$obj = $this->db->fetch_object($resql);
254
-			if ($obj)
255
-			{
256
-				// Si il y en a
257
-				return $obj->rowid;
258
-			}
259
-			else
260
-			{
261
-				// Si aucune facture ne remplace
262
-				return 0;
263
-			}
264
-		}
265
-		else
266
-		{
267
-			return -1;
268
-		}
269
-	}
270
-
271
-	/**
272
-	 *  Return list of payments
273
-	 *
274
-	 *	@param		string	$filtertype		1 to filter on type of payment == 'PRE'
275
-	 *  @return     array					Array with list of payments
276
-	 */
277
-	function getListOfPayments($filtertype='')
278
-	{
279
-		$retarray=array();
280
-
281
-		$table='paiement_facture';
282
-		$table2='paiement';
283
-		$field='fk_facture';
284
-		$field2='fk_paiement';
285
-		$sharedentity='facture';
286
-		if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
287
-		{
288
-			$table='paiementfourn_facturefourn';
289
-			$table2='paiementfourn';
290
-			$field='fk_facturefourn';
291
-			$field2='fk_paiementfourn';
292
-			$sharedentity='facture_fourn';
293
-		}
294
-
295
-		$sql = 'SELECT p.ref, pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code';
296
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$table.' as pf, '.MAIN_DB_PREFIX.$table2.' as p, '.MAIN_DB_PREFIX.'c_paiement as t';
297
-		$sql.= ' WHERE pf.'.$field.' = '.$this->id;
298
-		//$sql.= ' WHERE pf.'.$field.' = 1';
299
-		$sql.= ' AND pf.'.$field2.' = p.rowid';
300
-		$sql.= ' AND p.fk_paiement = t.id';
301
-		$sql.= ' AND p.entity IN (' . getEntity($sharedentity).')';
302
-		if ($filtertype) $sql.=" AND t.code='PRE'";
303
-
304
-		dol_syslog(get_class($this)."::getListOfPayments", LOG_DEBUG);
305
-		$resql=$this->db->query($sql);
306
-		if ($resql)
307
-		{
308
-			$num = $this->db->num_rows($resql);
309
-			$i=0;
310
-			while ($i < $num)
311
-			{
312
-				$obj = $this->db->fetch_object($resql);
313
-				$retarray[]=array('amount'=>$obj->amount,'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref);
314
-				$i++;
315
-			}
316
-			$this->db->free($resql);
317
-			return $retarray;
318
-		}
319
-		else
320
-		{
321
-			$this->error=$this->db->lasterror();
322
-			dol_print_error($this->db);
323
-			return array();
324
-		}
325
-	}
148
+     *
149
+     * 		@param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
150
+     *		@return		int						<0 if KO, Sum of deposits amount otherwise
151
+     */
152
+    function getSumDepositsUsed($multicurrency=0)
153
+    {
154
+        if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
155
+        {
156
+            // TODO
157
+            return 0;
158
+        }
159
+
160
+        require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
161
+
162
+        $discountstatic=new DiscountAbsolute($this->db);
163
+        $result=$discountstatic->getSumDepositsUsed($this, $multicurrency);
164
+        if ($result >= 0)
165
+        {
166
+            return $result;
167
+        }
168
+        else
169
+        {
170
+            $this->error=$discountstatic->error;
171
+            return -1;
172
+        }
173
+    }
174
+
175
+    /**
176
+     *    	Return amount (with tax) of all credit notes invoices + excess received used by invoice
177
+     *
178
+     * 		@param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
179
+     *		@return		int						<0 if KO, Sum of credit notes and deposits amount otherwise
180
+     */
181
+    function getSumCreditNotesUsed($multicurrency=0)
182
+    {
183
+        require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
184
+
185
+        $discountstatic=new DiscountAbsolute($this->db);
186
+        $result=$discountstatic->getSumCreditNotesUsed($this, $multicurrency);
187
+        if ($result >= 0)
188
+        {
189
+            return $result;
190
+        }
191
+        else
192
+        {
193
+            $this->error=$discountstatic->error;
194
+            return -1;
195
+        }
196
+    }
197
+
198
+    /**
199
+     *	Renvoie tableau des ids de facture avoir issus de la facture
200
+     *
201
+     *	@return		array		Tableau d'id de factures avoirs
202
+     */
203
+    function getListIdAvoirFromInvoice()
204
+    {
205
+        $idarray=array();
206
+
207
+        $sql = 'SELECT rowid';
208
+        $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
209
+        $sql.= ' WHERE fk_facture_source = '.$this->id;
210
+        $sql.= ' AND type = 2';
211
+        $resql=$this->db->query($sql);
212
+        if ($resql)
213
+        {
214
+            $num = $this->db->num_rows($resql);
215
+            $i = 0;
216
+            while ($i < $num)
217
+            {
218
+                $row = $this->db->fetch_row($resql);
219
+                $idarray[]=$row[0];
220
+                $i++;
221
+            }
222
+        }
223
+        else
224
+        {
225
+            dol_print_error($this->db);
226
+        }
227
+        return $idarray;
228
+    }
229
+
230
+    /**
231
+     *	Renvoie l'id de la facture qui la remplace
232
+     *
233
+     *	@param		string	$option		filtre sur statut ('', 'validated', ...)
234
+     *	@return		int					<0 si KO, 0 si aucune facture ne remplace, id facture sinon
235
+     */
236
+    function getIdReplacingInvoice($option='')
237
+    {
238
+        $sql = 'SELECT rowid';
239
+        $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
240
+        $sql.= ' WHERE fk_facture_source = '.$this->id;
241
+        $sql.= ' AND type < 2';
242
+        if ($option == 'validated') $sql.= ' AND fk_statut = 1';
243
+        // PROTECTION BAD DATA
244
+        // Au cas ou base corrompue et qu'il y a une facture de remplacement validee
245
+        // et une autre non, on donne priorite a la validee.
246
+        // Ne devrait pas arriver (sauf si acces concurrentiel et que 2 personnes
247
+        // ont cree en meme temps une facture de remplacement pour la meme facture)
248
+        $sql.= ' ORDER BY fk_statut DESC';
249
+
250
+        $resql=$this->db->query($sql);
251
+        if ($resql)
252
+        {
253
+            $obj = $this->db->fetch_object($resql);
254
+            if ($obj)
255
+            {
256
+                // Si il y en a
257
+                return $obj->rowid;
258
+            }
259
+            else
260
+            {
261
+                // Si aucune facture ne remplace
262
+                return 0;
263
+            }
264
+        }
265
+        else
266
+        {
267
+            return -1;
268
+        }
269
+    }
270
+
271
+    /**
272
+     *  Return list of payments
273
+     *
274
+     *	@param		string	$filtertype		1 to filter on type of payment == 'PRE'
275
+     *  @return     array					Array with list of payments
276
+     */
277
+    function getListOfPayments($filtertype='')
278
+    {
279
+        $retarray=array();
280
+
281
+        $table='paiement_facture';
282
+        $table2='paiement';
283
+        $field='fk_facture';
284
+        $field2='fk_paiement';
285
+        $sharedentity='facture';
286
+        if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
287
+        {
288
+            $table='paiementfourn_facturefourn';
289
+            $table2='paiementfourn';
290
+            $field='fk_facturefourn';
291
+            $field2='fk_paiementfourn';
292
+            $sharedentity='facture_fourn';
293
+        }
294
+
295
+        $sql = 'SELECT p.ref, pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code';
296
+        $sql.= ' FROM '.MAIN_DB_PREFIX.$table.' as pf, '.MAIN_DB_PREFIX.$table2.' as p, '.MAIN_DB_PREFIX.'c_paiement as t';
297
+        $sql.= ' WHERE pf.'.$field.' = '.$this->id;
298
+        //$sql.= ' WHERE pf.'.$field.' = 1';
299
+        $sql.= ' AND pf.'.$field2.' = p.rowid';
300
+        $sql.= ' AND p.fk_paiement = t.id';
301
+        $sql.= ' AND p.entity IN (' . getEntity($sharedentity).')';
302
+        if ($filtertype) $sql.=" AND t.code='PRE'";
303
+
304
+        dol_syslog(get_class($this)."::getListOfPayments", LOG_DEBUG);
305
+        $resql=$this->db->query($sql);
306
+        if ($resql)
307
+        {
308
+            $num = $this->db->num_rows($resql);
309
+            $i=0;
310
+            while ($i < $num)
311
+            {
312
+                $obj = $this->db->fetch_object($resql);
313
+                $retarray[]=array('amount'=>$obj->amount,'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref);
314
+                $i++;
315
+            }
316
+            $this->db->free($resql);
317
+            return $retarray;
318
+        }
319
+        else
320
+        {
321
+            $this->error=$this->db->lasterror();
322
+            dol_print_error($this->db);
323
+            return array();
324
+        }
325
+    }
326 326
 
327 327
 
328 328
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
329
-	/**
330
-	 *  Return if an invoice can be deleted
331
-	 *	Rule is:
332
-	 *  If invoice is draft and has a temporary ref -> yes (1)
333
-	 *  If hidden option INVOICE_CAN_NEVER_BE_REMOVED is on -> no (0)
334
-	 *  If invoice is dispatched in bookkeeping -> no (-1)
335
-	 *  If invoice has a definitive ref, is not last and INVOICE_CAN_ALWAYS_BE_REMOVED off -> no (-2)
336
-	 *  If invoice not last in a cycle -> no (-3)
337
-	 *  If there is payment -> no (-4)
338
-	 *  Otherwise -> yes (2)
339
-	 *
340
-	 *  @return    int         <=0 if no, >0 if yes
341
-	 */
342
-	function is_erasable()
343
-	{
329
+    /**
330
+     *  Return if an invoice can be deleted
331
+     *	Rule is:
332
+     *  If invoice is draft and has a temporary ref -> yes (1)
333
+     *  If hidden option INVOICE_CAN_NEVER_BE_REMOVED is on -> no (0)
334
+     *  If invoice is dispatched in bookkeeping -> no (-1)
335
+     *  If invoice has a definitive ref, is not last and INVOICE_CAN_ALWAYS_BE_REMOVED off -> no (-2)
336
+     *  If invoice not last in a cycle -> no (-3)
337
+     *  If there is payment -> no (-4)
338
+     *  Otherwise -> yes (2)
339
+     *
340
+     *  @return    int         <=0 if no, >0 if yes
341
+     */
342
+    function is_erasable()
343
+    {
344 344
         // phpcs:enable
345
-		global $conf;
346
-
347
-		// We check if invoice is a temporary number (PROVxxxx)
348
-		$tmppart = substr($this->ref, 1, 4);
349
-
350
-		if ($this->statut == self::STATUS_DRAFT && $tmppart === 'PROV') // If draft invoice and ref not yet defined
351
-		{
352
-			return 1;
353
-		}
354
-
355
-		if (! empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) return 0;
356
-
357
-		// If not a draft invoice and not temporary invoice
358
-		if ($tmppart !== 'PROV')
359
-		{
360
-			$ventilExportCompta = $this->getVentilExportCompta();
361
-			if ($ventilExportCompta != 0) return -1;
362
-
363
-			// Get last number of validated invoice
364
-			if ($this->element != 'invoice_supplier')
365
-			{
366
-				if (empty($this->thirdparty)) $this->fetch_thirdparty();	// We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag).
367
-				$maxref = $this->getNextNumRef($this->thirdparty,'last');
368
-
369
-				// If there is no invoice into the reset range and not already dispatched, we can delete
370
-				// If invoice to delete is last one and not already dispatched, we can delete
371
-				if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $maxref != '' && $maxref != $this->ref) return -2;
372
-
373
-				// TODO If there is payment in bookkeeping, check payment is not dispatched in accounting
374
-				// ...
375
-
376
-				if ($this->situation_cycle_ref && method_exists($this, 'is_last_in_cycle'))
377
-				{
378
-					$last = $this->is_last_in_cycle();
379
-					if (! $last) return -3;
380
-				}
381
-			}
382
-		}
383
-
384
-		// Test if there is at least one payment. If yes, refuse to delete.
385
-		if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $this->getSommePaiement() > 0) return -4;
386
-
387
-		return 2;
388
-	}
389
-
390
-	/**
391
-	 *	Return if an invoice was dispatched into bookkeeping
392
-	 *
393
-	 *	@return     int         <0 if KO, 0=no, 1=yes
394
-	 */
395
-	public function getVentilExportCompta()
396
-	{
397
-		$alreadydispatched = 0;
398
-
399
-		$type = 'customer_invoice';
400
-		if ($this->element == 'invoice_supplier') $type = 'supplier_invoice';
401
-
402
-		$sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id;
403
-		$resql = $this->db->query($sql);
404
-		if ($resql)
405
-		{
406
-			$obj = $this->db->fetch_object($resql);
407
-			if ($obj)
408
-			{
409
-				$alreadydispatched = $obj->nb;
410
-			}
411
-		}
412
-		else
413
-		{
414
-			$this->error = $this->db->lasterror();
415
-			return -1;
416
-		}
417
-
418
-		if ($alreadydispatched)
419
-		{
420
-			return 1;
421
-		}
422
-		return 0;
423
-	}
424
-
425
-
426
-	/**
427
-	 *	Return label of type of invoice
428
-	 *
429
-	 *	@return     string        Label of type of invoice
430
-	 */
431
-	function getLibType()
432
-	{
433
-		global $langs;
345
+        global $conf;
346
+
347
+        // We check if invoice is a temporary number (PROVxxxx)
348
+        $tmppart = substr($this->ref, 1, 4);
349
+
350
+        if ($this->statut == self::STATUS_DRAFT && $tmppart === 'PROV') // If draft invoice and ref not yet defined
351
+        {
352
+            return 1;
353
+        }
354
+
355
+        if (! empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) return 0;
356
+
357
+        // If not a draft invoice and not temporary invoice
358
+        if ($tmppart !== 'PROV')
359
+        {
360
+            $ventilExportCompta = $this->getVentilExportCompta();
361
+            if ($ventilExportCompta != 0) return -1;
362
+
363
+            // Get last number of validated invoice
364
+            if ($this->element != 'invoice_supplier')
365
+            {
366
+                if (empty($this->thirdparty)) $this->fetch_thirdparty();	// We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag).
367
+                $maxref = $this->getNextNumRef($this->thirdparty,'last');
368
+
369
+                // If there is no invoice into the reset range and not already dispatched, we can delete
370
+                // If invoice to delete is last one and not already dispatched, we can delete
371
+                if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $maxref != '' && $maxref != $this->ref) return -2;
372
+
373
+                // TODO If there is payment in bookkeeping, check payment is not dispatched in accounting
374
+                // ...
375
+
376
+                if ($this->situation_cycle_ref && method_exists($this, 'is_last_in_cycle'))
377
+                {
378
+                    $last = $this->is_last_in_cycle();
379
+                    if (! $last) return -3;
380
+                }
381
+            }
382
+        }
383
+
384
+        // Test if there is at least one payment. If yes, refuse to delete.
385
+        if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $this->getSommePaiement() > 0) return -4;
386
+
387
+        return 2;
388
+    }
389
+
390
+    /**
391
+     *	Return if an invoice was dispatched into bookkeeping
392
+     *
393
+     *	@return     int         <0 if KO, 0=no, 1=yes
394
+     */
395
+    public function getVentilExportCompta()
396
+    {
397
+        $alreadydispatched = 0;
398
+
399
+        $type = 'customer_invoice';
400
+        if ($this->element == 'invoice_supplier') $type = 'supplier_invoice';
401
+
402
+        $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id;
403
+        $resql = $this->db->query($sql);
404
+        if ($resql)
405
+        {
406
+            $obj = $this->db->fetch_object($resql);
407
+            if ($obj)
408
+            {
409
+                $alreadydispatched = $obj->nb;
410
+            }
411
+        }
412
+        else
413
+        {
414
+            $this->error = $this->db->lasterror();
415
+            return -1;
416
+        }
417
+
418
+        if ($alreadydispatched)
419
+        {
420
+            return 1;
421
+        }
422
+        return 0;
423
+    }
424
+
425
+
426
+    /**
427
+     *	Return label of type of invoice
428
+     *
429
+     *	@return     string        Label of type of invoice
430
+     */
431
+    function getLibType()
432
+    {
433
+        global $langs;
434 434
         if ($this->type == CommonInvoice::TYPE_STANDARD) return $langs->trans("InvoiceStandard");
435 435
         elseif ($this->type == CommonInvoice::TYPE_REPLACEMENT) return $langs->trans("InvoiceReplacement");
436 436
         elseif ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) return $langs->trans("InvoiceAvoir");
437 437
         elseif ($this->type == CommonInvoice::TYPE_DEPOSIT) return $langs->trans("InvoiceDeposit");
438 438
         elseif ($this->type == CommonInvoice::TYPE_PROFORMA) return $langs->trans("InvoiceProForma");           // Not used.
439 439
         elseif ($this->type == CommonInvoice::TYPE_SITUATION) return $langs->trans("InvoiceSituation");
440
-		return $langs->trans("Unknown");
441
-	}
442
-
443
-	/**
444
-	 *  Return label of object status
445
-	 *
446
-	 *  @param      int		$mode			0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto
447
-	 *  @param      integer	$alreadypaid    0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, 1 otherwise)
448
-	 *  @return     string			        Label of status
449
-	 */
450
-	function getLibStatut($mode=0, $alreadypaid=-1)
451
-	{
452
-		return $this->LibStatut($this->paye, $this->statut, $mode, $alreadypaid, $this->type);
453
-	}
440
+        return $langs->trans("Unknown");
441
+    }
442
+
443
+    /**
444
+     *  Return label of object status
445
+     *
446
+     *  @param      int		$mode			0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto
447
+     *  @param      integer	$alreadypaid    0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, 1 otherwise)
448
+     *  @return     string			        Label of status
449
+     */
450
+    function getLibStatut($mode=0, $alreadypaid=-1)
451
+    {
452
+        return $this->LibStatut($this->paye, $this->statut, $mode, $alreadypaid, $this->type);
453
+    }
454 454
 
455 455
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
456
-	/**
457
-	 *	Return label of a status
458
-	 *
459
-	 *	@param    	int  	$paye          	Status field paye
460
-	 *	@param      int		$status        	Id status
461
-	 *	@param      int		$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=long label + picto
462
-	 *	@param		integer	$alreadypaid	0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, -1 otherwise)
463
-	 *	@param		int		$type			Type invoice
464
-	 *	@return     string        			Label of status
465
-	 */
466
-	function LibStatut($paye, $status, $mode=0, $alreadypaid=-1, $type=0)
467
-	{
456
+    /**
457
+     *	Return label of a status
458
+     *
459
+     *	@param    	int  	$paye          	Status field paye
460
+     *	@param      int		$status        	Id status
461
+     *	@param      int		$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=long label + picto
462
+     *	@param		integer	$alreadypaid	0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, -1 otherwise)
463
+     *	@param		int		$type			Type invoice
464
+     *	@return     string        			Label of status
465
+     */
466
+    function LibStatut($paye, $status, $mode=0, $alreadypaid=-1, $type=0)
467
+    {
468 468
         // phpcs:enable
469
-		global $langs;
470
-		$langs->load('bills');
471
-
472
-		//print "$paye,$status,$mode,$alreadypaid,$type";
473
-		if ($mode == 0)
474
-		{
475
-			$prefix='';
476
-			if (! $paye)
477
-			{
478
-				if ($status == 0) return $langs->trans('Bill'.$prefix.'StatusDraft');
479
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusClosedUnpaid');
480
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
481
-				elseif ($alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusNotPaid');
482
-				else return $langs->trans('Bill'.$prefix.'StatusStarted');
483
-			}
484
-			else
485
-			{
486
-				if ($type == self::TYPE_CREDIT_NOTE) return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');       // credit note
487
-				elseif ($type == self::TYPE_DEPOSIT) return $langs->trans('Bill'.$prefix.'StatusConverted');             // deposit invoice
488
-				else return $langs->trans('Bill'.$prefix.'StatusPaid');
489
-			}
490
-		}
491
-		elseif ($mode == 1)
492
-		{
493
-			$prefix='Short';
494
-			if (! $paye)
495
-			{
496
-				if ($status == 0) return $langs->trans('Bill'.$prefix.'StatusDraft');
497
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusCanceled');
498
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
499
-				elseif ($alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusNotPaid');
500
-				else return $langs->trans('Bill'.$prefix.'StatusStarted');
501
-			}
502
-			else
503
-			{
504
-				if ($type == self::TYPE_CREDIT_NOTE) return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
505
-				elseif ($type == self::TYPE_DEPOSIT) return $langs->trans('Bill'.$prefix.'StatusConverted');
506
-				else return $langs->trans('Bill'.$prefix.'StatusPaid');
507
-			}
508
-		}
509
-		elseif ($mode == 2)
510
-		{
511
-			$prefix='Short';
512
-			if (! $paye)
513
-			{
514
-				if ($status == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0').' '.$langs->trans('Bill'.$prefix.'StatusDraft');
515
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('StatusCanceled'),'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
516
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
517
-				elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1').' '.$langs->trans('Bill'.$prefix.'StatusNotPaid');
518
-				else return img_picto($langs->trans('BillStatusStarted'),'statut3').' '.$langs->trans('Bill'.$prefix.'StatusStarted');
519
-			}
520
-			else
521
-			{
522
-				if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
523
-				elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusConverted');
524
-				else return img_picto($langs->trans('BillStatusPaid'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaid');
525
-			}
526
-		}
527
-		elseif ($mode == 3)
528
-		{
529
-			$prefix='Short';
530
-			if (! $paye)
531
-			{
532
-				if ($status == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0');
533
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('BillStatusCanceled'),'statut5');
534
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9');
535
-				elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1');
536
-				else return img_picto($langs->trans('BillStatusStarted'),'statut3');
537
-			}
538
-			else
539
-			{
540
-				if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6');
541
-				elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'),'statut6');
542
-				else return img_picto($langs->trans('BillStatusPaid'),'statut6');
543
-			}
544
-		}
545
-		elseif ($mode == 4)
546
-		{
547
-			$prefix='';
548
-			if (! $paye)
549
-			{
550
-				if ($status == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0').' '.$langs->trans('BillStatusDraft');
551
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('BillStatusCanceled'),'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
552
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
553
-				elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1').' '.$langs->trans('BillStatusNotPaid');
554
-				else return img_picto($langs->trans('BillStatusStarted'),'statut3').' '.$langs->trans('BillStatusStarted');
555
-			}
556
-			else
557
-			{
558
-				if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6').' '.$langs->trans('BillStatusPaidBackOrConverted');
559
-				elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'),'statut6').' '.$langs->trans('BillStatusConverted');
560
-				else return img_picto($langs->trans('BillStatusPaid'),'statut6').' '.$langs->trans('BillStatusPaid');
561
-			}
562
-		}
563
-		elseif ($mode == 5 || $mode == 6)
564
-		{
565
-			$prefix='';
566
-			if ($mode == 5) $prefix='Short';
567
-			if (! $paye)
568
-			{
569
-				if ($status == 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusDraft').' </span>'.img_picto($langs->trans('BillStatusDraft'),'statut0');
570
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusCanceled').' </span>'.img_picto($langs->trans('BillStatusCanceled'),'statut5');
571
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially').' </span>'.img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9');
572
-				elseif ($alreadypaid <= 0)
573
-				{
574
-				    if ($type == self::TYPE_CREDIT_NOTE) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusNotRefunded').' </span>'.img_picto($langs->trans('StatusNotRefunded'),'statut1');
575
-				    return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusNotPaid').' </span>'.img_picto($langs->trans('BillStatusNotPaid'),'statut1');
576
-				}
577
-				else return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusStarted').' </span>'.img_picto($langs->trans('BillStatusStarted'),'statut3');
578
-			}
579
-			else
580
-			{
581
-				if ($type == self::TYPE_CREDIT_NOTE) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted').' </span>'.img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6');
582
-				elseif ($type == self::TYPE_DEPOSIT) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusConverted').' </span>'.img_picto($langs->trans('BillStatusConverted'),'statut6');
583
-				else return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusPaid').' </span>'.img_picto($langs->trans('BillStatusPaid'),'statut6');
584
-			}
585
-		}
586
-	}
469
+        global $langs;
470
+        $langs->load('bills');
471
+
472
+        //print "$paye,$status,$mode,$alreadypaid,$type";
473
+        if ($mode == 0)
474
+        {
475
+            $prefix='';
476
+            if (! $paye)
477
+            {
478
+                if ($status == 0) return $langs->trans('Bill'.$prefix.'StatusDraft');
479
+                elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusClosedUnpaid');
480
+                elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
481
+                elseif ($alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusNotPaid');
482
+                else return $langs->trans('Bill'.$prefix.'StatusStarted');
483
+            }
484
+            else
485
+            {
486
+                if ($type == self::TYPE_CREDIT_NOTE) return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');       // credit note
487
+                elseif ($type == self::TYPE_DEPOSIT) return $langs->trans('Bill'.$prefix.'StatusConverted');             // deposit invoice
488
+                else return $langs->trans('Bill'.$prefix.'StatusPaid');
489
+            }
490
+        }
491
+        elseif ($mode == 1)
492
+        {
493
+            $prefix='Short';
494
+            if (! $paye)
495
+            {
496
+                if ($status == 0) return $langs->trans('Bill'.$prefix.'StatusDraft');
497
+                elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusCanceled');
498
+                elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
499
+                elseif ($alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusNotPaid');
500
+                else return $langs->trans('Bill'.$prefix.'StatusStarted');
501
+            }
502
+            else
503
+            {
504
+                if ($type == self::TYPE_CREDIT_NOTE) return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
505
+                elseif ($type == self::TYPE_DEPOSIT) return $langs->trans('Bill'.$prefix.'StatusConverted');
506
+                else return $langs->trans('Bill'.$prefix.'StatusPaid');
507
+            }
508
+        }
509
+        elseif ($mode == 2)
510
+        {
511
+            $prefix='Short';
512
+            if (! $paye)
513
+            {
514
+                if ($status == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0').' '.$langs->trans('Bill'.$prefix.'StatusDraft');
515
+                elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('StatusCanceled'),'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
516
+                elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
517
+                elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1').' '.$langs->trans('Bill'.$prefix.'StatusNotPaid');
518
+                else return img_picto($langs->trans('BillStatusStarted'),'statut3').' '.$langs->trans('Bill'.$prefix.'StatusStarted');
519
+            }
520
+            else
521
+            {
522
+                if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
523
+                elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusConverted');
524
+                else return img_picto($langs->trans('BillStatusPaid'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaid');
525
+            }
526
+        }
527
+        elseif ($mode == 3)
528
+        {
529
+            $prefix='Short';
530
+            if (! $paye)
531
+            {
532
+                if ($status == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0');
533
+                elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('BillStatusCanceled'),'statut5');
534
+                elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9');
535
+                elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1');
536
+                else return img_picto($langs->trans('BillStatusStarted'),'statut3');
537
+            }
538
+            else
539
+            {
540
+                if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6');
541
+                elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'),'statut6');
542
+                else return img_picto($langs->trans('BillStatusPaid'),'statut6');
543
+            }
544
+        }
545
+        elseif ($mode == 4)
546
+        {
547
+            $prefix='';
548
+            if (! $paye)
549
+            {
550
+                if ($status == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0').' '.$langs->trans('BillStatusDraft');
551
+                elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('BillStatusCanceled'),'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
552
+                elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
553
+                elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1').' '.$langs->trans('BillStatusNotPaid');
554
+                else return img_picto($langs->trans('BillStatusStarted'),'statut3').' '.$langs->trans('BillStatusStarted');
555
+            }
556
+            else
557
+            {
558
+                if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6').' '.$langs->trans('BillStatusPaidBackOrConverted');
559
+                elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'),'statut6').' '.$langs->trans('BillStatusConverted');
560
+                else return img_picto($langs->trans('BillStatusPaid'),'statut6').' '.$langs->trans('BillStatusPaid');
561
+            }
562
+        }
563
+        elseif ($mode == 5 || $mode == 6)
564
+        {
565
+            $prefix='';
566
+            if ($mode == 5) $prefix='Short';
567
+            if (! $paye)
568
+            {
569
+                if ($status == 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusDraft').' </span>'.img_picto($langs->trans('BillStatusDraft'),'statut0');
570
+                elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusCanceled').' </span>'.img_picto($langs->trans('BillStatusCanceled'),'statut5');
571
+                elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially').' </span>'.img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9');
572
+                elseif ($alreadypaid <= 0)
573
+                {
574
+                    if ($type == self::TYPE_CREDIT_NOTE) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusNotRefunded').' </span>'.img_picto($langs->trans('StatusNotRefunded'),'statut1');
575
+                    return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusNotPaid').' </span>'.img_picto($langs->trans('BillStatusNotPaid'),'statut1');
576
+                }
577
+                else return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusStarted').' </span>'.img_picto($langs->trans('BillStatusStarted'),'statut3');
578
+            }
579
+            else
580
+            {
581
+                if ($type == self::TYPE_CREDIT_NOTE) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted').' </span>'.img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6');
582
+                elseif ($type == self::TYPE_DEPOSIT) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusConverted').' </span>'.img_picto($langs->trans('BillStatusConverted'),'statut6');
583
+                else return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusPaid').' </span>'.img_picto($langs->trans('BillStatusPaid'),'statut6');
584
+            }
585
+        }
586
+    }
587 587
 
588 588
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
589
-	/**
590
-	 *	Renvoi une date limite de reglement de facture en fonction des
591
-	 *	conditions de reglements de la facture et date de facturation.
592
-	 *
593
-	 *	@param      integer	$cond_reglement   	Condition of payment (code or id) to use. If 0, we use current condition.
594
-	 *  @return     date     			       	Date limite de reglement si ok, <0 si ko
595
-	 */
596
-	function calculate_date_lim_reglement($cond_reglement=0)
597
-	{
589
+    /**
590
+     *	Renvoi une date limite de reglement de facture en fonction des
591
+     *	conditions de reglements de la facture et date de facturation.
592
+     *
593
+     *	@param      integer	$cond_reglement   	Condition of payment (code or id) to use. If 0, we use current condition.
594
+     *  @return     date     			       	Date limite de reglement si ok, <0 si ko
595
+     */
596
+    function calculate_date_lim_reglement($cond_reglement=0)
597
+    {
598 598
         // phpcs:enable
599
-		if (! $cond_reglement) $cond_reglement=$this->cond_reglement_code;
600
-		if (! $cond_reglement) $cond_reglement=$this->cond_reglement_id;
599
+        if (! $cond_reglement) $cond_reglement=$this->cond_reglement_code;
600
+        if (! $cond_reglement) $cond_reglement=$this->cond_reglement_id;
601 601
 
602
-		$cdr_nbjour=0;
602
+        $cdr_nbjour=0;
603 603
         $cdr_type=0;
604 604
         $cdr_decalage=0;
605 605
 
606
-		$sqltemp = 'SELECT c.type_cdr, c.nbjour, c.decalage';
607
-		$sqltemp.= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c';
608
-		if (is_numeric($cond_reglement)) $sqltemp.= " WHERE c.rowid=".$cond_reglement;
609
-		else {
610
-			$sqltemp.= " WHERE c.entity IN (".getEntity('c_payment_term').")";
611
-			$sqltemp.= " AND c.code='".$this->db->escape($cond_reglement)."'";
612
-		}
613
-
614
-		dol_syslog(get_class($this).'::calculate_date_lim_reglement', LOG_DEBUG);
615
-		$resqltemp=$this->db->query($sqltemp);
616
-		if ($resqltemp)
617
-		{
618
-			if ($this->db->num_rows($resqltemp))
619
-			{
620
-				$obj = $this->db->fetch_object($resqltemp);
621
-				$cdr_nbjour = $obj->nbjour;
622
-				$cdr_type = $obj->type_cdr;
623
-				$cdr_decalage = $obj->decalage;
624
-			}
625
-		}
626
-		else
627
-		{
628
-			$this->error=$this->db->error();
629
-			return -1;
630
-		}
631
-		$this->db->free($resqltemp);
632
-
633
-		/* Definition de la date limite */
634
-
635
-		// 0 : ajout du nombre de jours
636
-		if ($cdr_type == 0)
637
-		{
638
-			$datelim = $this->date + ($cdr_nbjour * 3600 * 24);
639
-
640
-			$datelim += ($cdr_decalage * 3600 * 24);
641
-		}
642
-		// 1 : application de la regle "fin de mois"
643
-		elseif ($cdr_type == 1)
644
-		{
645
-			$datelim = $this->date + ($cdr_nbjour * 3600 * 24);
646
-
647
-			$mois=date('m', $datelim);
648
-			$annee=date('Y', $datelim);
649
-			if ($mois == 12)
650
-			{
651
-				$mois = 1;
652
-				$annee += 1;
653
-			}
654
-			else
655
-			{
656
-				$mois += 1;
657
-			}
658
-			// On se deplace au debut du mois suivant, et on retire un jour
659
-			$datelim=dol_mktime(12,0,0,$mois,1,$annee);
660
-			$datelim -= (3600 * 24);
661
-
662
-			$datelim += ($cdr_decalage * 3600 * 24);
663
-		}
664
-		// 2 : application de la règle, le N du mois courant ou suivant
665
-		elseif ($cdr_type == 2 && !empty($cdr_decalage))
666
-		{
667
-			$datelim = $this->date + ($cdr_nbjour * 3600 * 24);
668
-
669
-			$date_piece = dol_mktime(0, 0, 0, date('m', $datelim),date('d', $datelim),date('Y', $datelim)); // Sans les heures minutes et secondes
670
-			$date_lim_current = dol_mktime(0, 0, 0, date('m', $datelim), $cdr_decalage, date('Y', $datelim)); // Sans les heures minutes et secondes
671
-			$date_lim_next = dol_time_plus_duree($date_lim_current, 1, 'm');	// Add 1 month
672
-
673
-			$diff = $date_piece - $date_lim_current;
674
-
675
-			if ($diff < 0) $datelim = $date_lim_current;
676
-			else $datelim = $date_lim_next;
677
-		}
678
-		else return 'Bad value for type_cdr in database for record cond_reglement = '.$cond_reglement;
679
-
680
-		return $datelim;
681
-	}
606
+        $sqltemp = 'SELECT c.type_cdr, c.nbjour, c.decalage';
607
+        $sqltemp.= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c';
608
+        if (is_numeric($cond_reglement)) $sqltemp.= " WHERE c.rowid=".$cond_reglement;
609
+        else {
610
+            $sqltemp.= " WHERE c.entity IN (".getEntity('c_payment_term').")";
611
+            $sqltemp.= " AND c.code='".$this->db->escape($cond_reglement)."'";
612
+        }
613
+
614
+        dol_syslog(get_class($this).'::calculate_date_lim_reglement', LOG_DEBUG);
615
+        $resqltemp=$this->db->query($sqltemp);
616
+        if ($resqltemp)
617
+        {
618
+            if ($this->db->num_rows($resqltemp))
619
+            {
620
+                $obj = $this->db->fetch_object($resqltemp);
621
+                $cdr_nbjour = $obj->nbjour;
622
+                $cdr_type = $obj->type_cdr;
623
+                $cdr_decalage = $obj->decalage;
624
+            }
625
+        }
626
+        else
627
+        {
628
+            $this->error=$this->db->error();
629
+            return -1;
630
+        }
631
+        $this->db->free($resqltemp);
632
+
633
+        /* Definition de la date limite */
634
+
635
+        // 0 : ajout du nombre de jours
636
+        if ($cdr_type == 0)
637
+        {
638
+            $datelim = $this->date + ($cdr_nbjour * 3600 * 24);
639
+
640
+            $datelim += ($cdr_decalage * 3600 * 24);
641
+        }
642
+        // 1 : application de la regle "fin de mois"
643
+        elseif ($cdr_type == 1)
644
+        {
645
+            $datelim = $this->date + ($cdr_nbjour * 3600 * 24);
646
+
647
+            $mois=date('m', $datelim);
648
+            $annee=date('Y', $datelim);
649
+            if ($mois == 12)
650
+            {
651
+                $mois = 1;
652
+                $annee += 1;
653
+            }
654
+            else
655
+            {
656
+                $mois += 1;
657
+            }
658
+            // On se deplace au debut du mois suivant, et on retire un jour
659
+            $datelim=dol_mktime(12,0,0,$mois,1,$annee);
660
+            $datelim -= (3600 * 24);
661
+
662
+            $datelim += ($cdr_decalage * 3600 * 24);
663
+        }
664
+        // 2 : application de la règle, le N du mois courant ou suivant
665
+        elseif ($cdr_type == 2 && !empty($cdr_decalage))
666
+        {
667
+            $datelim = $this->date + ($cdr_nbjour * 3600 * 24);
668
+
669
+            $date_piece = dol_mktime(0, 0, 0, date('m', $datelim),date('d', $datelim),date('Y', $datelim)); // Sans les heures minutes et secondes
670
+            $date_lim_current = dol_mktime(0, 0, 0, date('m', $datelim), $cdr_decalage, date('Y', $datelim)); // Sans les heures minutes et secondes
671
+            $date_lim_next = dol_time_plus_duree($date_lim_current, 1, 'm');	// Add 1 month
672
+
673
+            $diff = $date_piece - $date_lim_current;
674
+
675
+            if ($diff < 0) $datelim = $date_lim_current;
676
+            else $datelim = $date_lim_next;
677
+        }
678
+        else return 'Bad value for type_cdr in database for record cond_reglement = '.$cond_reglement;
679
+
680
+        return $datelim;
681
+    }
682 682
 }
683 683
 
684 684
 
@@ -690,105 +690,105 @@  discard block
 block discarded – undo
690 690
  */
691 691
 abstract class CommonInvoiceLine extends CommonObjectLine
692 692
 {
693
-	/**
694
-	 * Quantity
695
-	 * @var double
696
-	 */
697
-	public $qty;
698
-
699
-	/**
700
-	 * Unit price before taxes
701
-	 * @var float
702
-	 */
703
-	public $subprice;
704
-
705
-	/**
706
-	 * Type of the product. 0 for product 1 for service
707
-	 * @var int
708
-	 */
709
-	public $product_type = 0;
710
-
711
-	/**
712
-	 * Id of corresponding product
713
-	 * @var int
714
-	 */
715
-	public $fk_product;
716
-
717
-	/**
718
-	 * VAT code
719
-	 * @var string
720
-	 */
721
-	public $vat_src_code;
722
-
723
-	/**
724
-	 * VAT %
725
-	 * @var float
726
-	 */
727
-	public $tva_tx;
728
-
729
-	/**
730
-	 * Local tax 1 %
731
-	 * @var float
732
-	 */
733
-	public $localtax1_tx;
734
-
735
-	/**
736
-	 * Local tax 2 %
737
-	 * @var float
738
-	 */
739
-	public $localtax2_tx;
740
-
741
-	/**
742
-	 * Percent of discount
743
-	 * @var float
744
-	 */
745
-	public $remise_percent;
746
-
747
-	/**
748
-	 * Total amount before taxes
749
-	 * @var float
750
-	 */
751
-	public $total_ht;
752
-
753
-	/**
754
-	 * Total VAT amount
755
-	 * @var float
756
-	 */
757
-	public $total_tva;
758
-
759
-	/**
760
-	 * Total local tax 1 amount
761
-	 * @var float
762
-	 */
763
-	public $total_localtax1;
764
-
765
-	/**
766
-	 * Total local tax 2 amount
767
-	 * @var float
768
-	 */
769
-	public $total_localtax2;
770
-
771
-	/**
772
-	 * Total amount with taxes
773
-	 * @var float
774
-	 */
775
-	public $total_ttc;
776
-
777
-	/**
778
-	 * Liste d'options cumulables:
779
-	 * Bit 0:	0 si TVA normal - 1 si TVA NPR
780
-	 * Bit 1:	0 si ligne normal - 1 si bit discount (link to line into llx_remise_except)
781
-	 * @var int
782
-	 */
783
-	public $info_bits = 0;
784
-
785
-	/**
786
-	 *  Constructor
787
-	 *
788
-	 *  @param	DoliDB		$db		Database handler
789
-	 */
790
-	public function __construct(DoliDB $db)
791
-	{
792
-		$this->db = $db;
793
-	}
693
+    /**
694
+     * Quantity
695
+     * @var double
696
+     */
697
+    public $qty;
698
+
699
+    /**
700
+     * Unit price before taxes
701
+     * @var float
702
+     */
703
+    public $subprice;
704
+
705
+    /**
706
+     * Type of the product. 0 for product 1 for service
707
+     * @var int
708
+     */
709
+    public $product_type = 0;
710
+
711
+    /**
712
+     * Id of corresponding product
713
+     * @var int
714
+     */
715
+    public $fk_product;
716
+
717
+    /**
718
+     * VAT code
719
+     * @var string
720
+     */
721
+    public $vat_src_code;
722
+
723
+    /**
724
+     * VAT %
725
+     * @var float
726
+     */
727
+    public $tva_tx;
728
+
729
+    /**
730
+     * Local tax 1 %
731
+     * @var float
732
+     */
733
+    public $localtax1_tx;
734
+
735
+    /**
736
+     * Local tax 2 %
737
+     * @var float
738
+     */
739
+    public $localtax2_tx;
740
+
741
+    /**
742
+     * Percent of discount
743
+     * @var float
744
+     */
745
+    public $remise_percent;
746
+
747
+    /**
748
+     * Total amount before taxes
749
+     * @var float
750
+     */
751
+    public $total_ht;
752
+
753
+    /**
754
+     * Total VAT amount
755
+     * @var float
756
+     */
757
+    public $total_tva;
758
+
759
+    /**
760
+     * Total local tax 1 amount
761
+     * @var float
762
+     */
763
+    public $total_localtax1;
764
+
765
+    /**
766
+     * Total local tax 2 amount
767
+     * @var float
768
+     */
769
+    public $total_localtax2;
770
+
771
+    /**
772
+     * Total amount with taxes
773
+     * @var float
774
+     */
775
+    public $total_ttc;
776
+
777
+    /**
778
+     * Liste d'options cumulables:
779
+     * Bit 0:	0 si TVA normal - 1 si TVA NPR
780
+     * Bit 1:	0 si ligne normal - 1 si bit discount (link to line into llx_remise_except)
781
+     * @var int
782
+     */
783
+    public $info_bits = 0;
784
+
785
+    /**
786
+     *  Constructor
787
+     *
788
+     *  @param	DoliDB		$db		Database handler
789
+     */
790
+    public function __construct(DoliDB $db)
791
+    {
792
+        $this->db = $db;
793
+    }
794 794
 }
Please login to merge, or discard this patch.
Spacing   +131 added lines, -131 removed lines patch added patch discarded remove patch
@@ -23,7 +23,7 @@  discard block
 block discarded – undo
23 23
  *       \brief      File of the superclass of invoices classes (customer and supplier)
24 24
  */
25 25
 
26
-require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
26
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
27 27
 
28 28
 /**
29 29
  * 	Superclass for invoices classes
@@ -97,12 +97,12 @@  discard block
 block discarded – undo
97 97
 	 *  @param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
98 98
 	 *	@return		double						Remain of amount to pay
99 99
 	 */
100
-	function getRemainToPay($multicurrency=0)
100
+	function getRemainToPay($multicurrency = 0)
101 101
 	{
102
-	    $alreadypaid=0;
103
-	    $alreadypaid+=$this->getSommePaiement($multicurrency);
104
-	    $alreadypaid+=$this->getSumDepositsUsed($multicurrency);
105
-	    $alreadypaid+=$this->getSumCreditNotesUsed($multicurrency);
102
+	    $alreadypaid = 0;
103
+	    $alreadypaid += $this->getSommePaiement($multicurrency);
104
+	    $alreadypaid += $this->getSumDepositsUsed($multicurrency);
105
+	    $alreadypaid += $this->getSumCreditNotesUsed($multicurrency);
106 106
     	return $this->total_ttc - $alreadypaid;
107 107
 	}
108 108
 
@@ -112,22 +112,22 @@  discard block
 block discarded – undo
112 112
 	 *  @param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
113 113
 	 *	@return		int						Amount of payment already done, <0 if KO
114 114
 	 */
115
-	function getSommePaiement($multicurrency=0)
115
+	function getSommePaiement($multicurrency = 0)
116 116
 	{
117
-		$table='paiement_facture';
118
-		$field='fk_facture';
117
+		$table = 'paiement_facture';
118
+		$field = 'fk_facture';
119 119
 		if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
120 120
 		{
121
-			$table='paiementfourn_facturefourn';
122
-			$field='fk_facturefourn';
121
+			$table = 'paiementfourn_facturefourn';
122
+			$field = 'fk_facturefourn';
123 123
 		}
124 124
 
125 125
 		$sql = 'SELECT sum(amount) as amount, sum(multicurrency_amount) as multicurrency_amount';
126
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$table;
127
-		$sql.= ' WHERE '.$field.' = '.$this->id;
126
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$table;
127
+		$sql .= ' WHERE '.$field.' = '.$this->id;
128 128
 
129 129
 		dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG);
130
-		$resql=$this->db->query($sql);
130
+		$resql = $this->db->query($sql);
131 131
 		if ($resql)
132 132
 		{
133 133
 			$obj = $this->db->fetch_object($resql);
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 		}
138 138
 		else
139 139
 		{
140
-			$this->error=$this->db->lasterror();
140
+			$this->error = $this->db->lasterror();
141 141
 			return -1;
142 142
 		}
143 143
 	}
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
 	 * 		@param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
150 150
 	 *		@return		int						<0 if KO, Sum of deposits amount otherwise
151 151
 	 */
152
-	function getSumDepositsUsed($multicurrency=0)
152
+	function getSumDepositsUsed($multicurrency = 0)
153 153
 	{
154 154
 		if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
155 155
 	    {
@@ -159,15 +159,15 @@  discard block
 block discarded – undo
159 159
 
160 160
 	    require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
161 161
 
162
-	    $discountstatic=new DiscountAbsolute($this->db);
163
-	    $result=$discountstatic->getSumDepositsUsed($this, $multicurrency);
162
+	    $discountstatic = new DiscountAbsolute($this->db);
163
+	    $result = $discountstatic->getSumDepositsUsed($this, $multicurrency);
164 164
 	    if ($result >= 0)
165 165
 	    {
166 166
 	        return $result;
167 167
 	    }
168 168
 	    else
169 169
 	    {
170
-	        $this->error=$discountstatic->error;
170
+	        $this->error = $discountstatic->error;
171 171
 	        return -1;
172 172
 	    }
173 173
 	}
@@ -178,19 +178,19 @@  discard block
 block discarded – undo
178 178
 	 * 		@param 		int 	$multicurrency 	Return multicurrency_amount instead of amount
179 179
 	 *		@return		int						<0 if KO, Sum of credit notes and deposits amount otherwise
180 180
 	 */
181
-	function getSumCreditNotesUsed($multicurrency=0)
181
+	function getSumCreditNotesUsed($multicurrency = 0)
182 182
 	{
183 183
 	    require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
184 184
 
185
-	    $discountstatic=new DiscountAbsolute($this->db);
186
-	    $result=$discountstatic->getSumCreditNotesUsed($this, $multicurrency);
185
+	    $discountstatic = new DiscountAbsolute($this->db);
186
+	    $result = $discountstatic->getSumCreditNotesUsed($this, $multicurrency);
187 187
 	    if ($result >= 0)
188 188
 	    {
189 189
 	        return $result;
190 190
 	    }
191 191
 	    else
192 192
 	    {
193
-	        $this->error=$discountstatic->error;
193
+	        $this->error = $discountstatic->error;
194 194
 	        return -1;
195 195
 	    }
196 196
 	}
@@ -202,13 +202,13 @@  discard block
 block discarded – undo
202 202
 	 */
203 203
 	function getListIdAvoirFromInvoice()
204 204
 	{
205
-		$idarray=array();
205
+		$idarray = array();
206 206
 
207 207
 		$sql = 'SELECT rowid';
208
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
209
-		$sql.= ' WHERE fk_facture_source = '.$this->id;
210
-		$sql.= ' AND type = 2';
211
-		$resql=$this->db->query($sql);
208
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
209
+		$sql .= ' WHERE fk_facture_source = '.$this->id;
210
+		$sql .= ' AND type = 2';
211
+		$resql = $this->db->query($sql);
212 212
 		if ($resql)
213 213
 		{
214 214
 			$num = $this->db->num_rows($resql);
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 			while ($i < $num)
217 217
 			{
218 218
 				$row = $this->db->fetch_row($resql);
219
-				$idarray[]=$row[0];
219
+				$idarray[] = $row[0];
220 220
 				$i++;
221 221
 			}
222 222
 		}
@@ -233,21 +233,21 @@  discard block
 block discarded – undo
233 233
 	 *	@param		string	$option		filtre sur statut ('', 'validated', ...)
234 234
 	 *	@return		int					<0 si KO, 0 si aucune facture ne remplace, id facture sinon
235 235
 	 */
236
-	function getIdReplacingInvoice($option='')
236
+	function getIdReplacingInvoice($option = '')
237 237
 	{
238 238
 		$sql = 'SELECT rowid';
239
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
240
-		$sql.= ' WHERE fk_facture_source = '.$this->id;
241
-		$sql.= ' AND type < 2';
242
-		if ($option == 'validated') $sql.= ' AND fk_statut = 1';
239
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
240
+		$sql .= ' WHERE fk_facture_source = '.$this->id;
241
+		$sql .= ' AND type < 2';
242
+		if ($option == 'validated') $sql .= ' AND fk_statut = 1';
243 243
 		// PROTECTION BAD DATA
244 244
 		// Au cas ou base corrompue et qu'il y a une facture de remplacement validee
245 245
 		// et une autre non, on donne priorite a la validee.
246 246
 		// Ne devrait pas arriver (sauf si acces concurrentiel et que 2 personnes
247 247
 		// ont cree en meme temps une facture de remplacement pour la meme facture)
248
-		$sql.= ' ORDER BY fk_statut DESC';
248
+		$sql .= ' ORDER BY fk_statut DESC';
249 249
 
250
-		$resql=$this->db->query($sql);
250
+		$resql = $this->db->query($sql);
251 251
 		if ($resql)
252 252
 		{
253 253
 			$obj = $this->db->fetch_object($resql);
@@ -274,43 +274,43 @@  discard block
 block discarded – undo
274 274
 	 *	@param		string	$filtertype		1 to filter on type of payment == 'PRE'
275 275
 	 *  @return     array					Array with list of payments
276 276
 	 */
277
-	function getListOfPayments($filtertype='')
277
+	function getListOfPayments($filtertype = '')
278 278
 	{
279
-		$retarray=array();
279
+		$retarray = array();
280 280
 
281
-		$table='paiement_facture';
282
-		$table2='paiement';
283
-		$field='fk_facture';
284
-		$field2='fk_paiement';
285
-		$sharedentity='facture';
281
+		$table = 'paiement_facture';
282
+		$table2 = 'paiement';
283
+		$field = 'fk_facture';
284
+		$field2 = 'fk_paiement';
285
+		$sharedentity = 'facture';
286 286
 		if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
287 287
 		{
288
-			$table='paiementfourn_facturefourn';
289
-			$table2='paiementfourn';
290
-			$field='fk_facturefourn';
291
-			$field2='fk_paiementfourn';
292
-			$sharedentity='facture_fourn';
288
+			$table = 'paiementfourn_facturefourn';
289
+			$table2 = 'paiementfourn';
290
+			$field = 'fk_facturefourn';
291
+			$field2 = 'fk_paiementfourn';
292
+			$sharedentity = 'facture_fourn';
293 293
 		}
294 294
 
295 295
 		$sql = 'SELECT p.ref, pf.amount, pf.multicurrency_amount, p.fk_paiement, p.datep, p.num_paiement as num, t.code';
296
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$table.' as pf, '.MAIN_DB_PREFIX.$table2.' as p, '.MAIN_DB_PREFIX.'c_paiement as t';
297
-		$sql.= ' WHERE pf.'.$field.' = '.$this->id;
296
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$table.' as pf, '.MAIN_DB_PREFIX.$table2.' as p, '.MAIN_DB_PREFIX.'c_paiement as t';
297
+		$sql .= ' WHERE pf.'.$field.' = '.$this->id;
298 298
 		//$sql.= ' WHERE pf.'.$field.' = 1';
299
-		$sql.= ' AND pf.'.$field2.' = p.rowid';
300
-		$sql.= ' AND p.fk_paiement = t.id';
301
-		$sql.= ' AND p.entity IN (' . getEntity($sharedentity).')';
302
-		if ($filtertype) $sql.=" AND t.code='PRE'";
299
+		$sql .= ' AND pf.'.$field2.' = p.rowid';
300
+		$sql .= ' AND p.fk_paiement = t.id';
301
+		$sql .= ' AND p.entity IN ('.getEntity($sharedentity).')';
302
+		if ($filtertype) $sql .= " AND t.code='PRE'";
303 303
 
304 304
 		dol_syslog(get_class($this)."::getListOfPayments", LOG_DEBUG);
305
-		$resql=$this->db->query($sql);
305
+		$resql = $this->db->query($sql);
306 306
 		if ($resql)
307 307
 		{
308 308
 			$num = $this->db->num_rows($resql);
309
-			$i=0;
309
+			$i = 0;
310 310
 			while ($i < $num)
311 311
 			{
312 312
 				$obj = $this->db->fetch_object($resql);
313
-				$retarray[]=array('amount'=>$obj->amount,'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref);
313
+				$retarray[] = array('amount'=>$obj->amount, 'type'=>$obj->code, 'date'=>$obj->datep, 'num'=>$obj->num, 'ref'=>$obj->ref);
314 314
 				$i++;
315 315
 			}
316 316
 			$this->db->free($resql);
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 		}
319 319
 		else
320 320
 		{
321
-			$this->error=$this->db->lasterror();
321
+			$this->error = $this->db->lasterror();
322 322
 			dol_print_error($this->db);
323 323
 			return array();
324 324
 		}
@@ -352,7 +352,7 @@  discard block
 block discarded – undo
352 352
 			return 1;
353 353
 		}
354 354
 
355
-		if (! empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) return 0;
355
+		if (!empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) return 0;
356 356
 
357 357
 		// If not a draft invoice and not temporary invoice
358 358
 		if ($tmppart !== 'PROV')
@@ -363,8 +363,8 @@  discard block
 block discarded – undo
363 363
 			// Get last number of validated invoice
364 364
 			if ($this->element != 'invoice_supplier')
365 365
 			{
366
-				if (empty($this->thirdparty)) $this->fetch_thirdparty();	// We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag).
367
-				$maxref = $this->getNextNumRef($this->thirdparty,'last');
366
+				if (empty($this->thirdparty)) $this->fetch_thirdparty(); // We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag).
367
+				$maxref = $this->getNextNumRef($this->thirdparty, 'last');
368 368
 
369 369
 				// If there is no invoice into the reset range and not already dispatched, we can delete
370 370
 				// If invoice to delete is last one and not already dispatched, we can delete
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
 				if ($this->situation_cycle_ref && method_exists($this, 'is_last_in_cycle'))
377 377
 				{
378 378
 					$last = $this->is_last_in_cycle();
379
-					if (! $last) return -3;
379
+					if (!$last) return -3;
380 380
 				}
381 381
 			}
382 382
 		}
@@ -435,7 +435,7 @@  discard block
 block discarded – undo
435 435
         elseif ($this->type == CommonInvoice::TYPE_REPLACEMENT) return $langs->trans("InvoiceReplacement");
436 436
         elseif ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) return $langs->trans("InvoiceAvoir");
437 437
         elseif ($this->type == CommonInvoice::TYPE_DEPOSIT) return $langs->trans("InvoiceDeposit");
438
-        elseif ($this->type == CommonInvoice::TYPE_PROFORMA) return $langs->trans("InvoiceProForma");           // Not used.
438
+        elseif ($this->type == CommonInvoice::TYPE_PROFORMA) return $langs->trans("InvoiceProForma"); // Not used.
439 439
         elseif ($this->type == CommonInvoice::TYPE_SITUATION) return $langs->trans("InvoiceSituation");
440 440
 		return $langs->trans("Unknown");
441 441
 	}
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
 	 *  @param      integer	$alreadypaid    0=No payment already done, >0=Some payments were already done (we recommand to put here amount payed if you have it, 1 otherwise)
448 448
 	 *  @return     string			        Label of status
449 449
 	 */
450
-	function getLibStatut($mode=0, $alreadypaid=-1)
450
+	function getLibStatut($mode = 0, $alreadypaid = -1)
451 451
 	{
452 452
 		return $this->LibStatut($this->paye, $this->statut, $mode, $alreadypaid, $this->type);
453 453
 	}
@@ -463,7 +463,7 @@  discard block
 block discarded – undo
463 463
 	 *	@param		int		$type			Type invoice
464 464
 	 *	@return     string        			Label of status
465 465
 	 */
466
-	function LibStatut($paye, $status, $mode=0, $alreadypaid=-1, $type=0)
466
+	function LibStatut($paye, $status, $mode = 0, $alreadypaid = -1, $type = 0)
467 467
 	{
468 468
         // phpcs:enable
469 469
 		global $langs;
@@ -472,8 +472,8 @@  discard block
 block discarded – undo
472 472
 		//print "$paye,$status,$mode,$alreadypaid,$type";
473 473
 		if ($mode == 0)
474 474
 		{
475
-			$prefix='';
476
-			if (! $paye)
475
+			$prefix = '';
476
+			if (!$paye)
477 477
 			{
478 478
 				if ($status == 0) return $langs->trans('Bill'.$prefix.'StatusDraft');
479 479
 				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusClosedUnpaid');
@@ -483,15 +483,15 @@  discard block
 block discarded – undo
483 483
 			}
484 484
 			else
485 485
 			{
486
-				if ($type == self::TYPE_CREDIT_NOTE) return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');       // credit note
487
-				elseif ($type == self::TYPE_DEPOSIT) return $langs->trans('Bill'.$prefix.'StatusConverted');             // deposit invoice
486
+				if ($type == self::TYPE_CREDIT_NOTE) return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted'); // credit note
487
+				elseif ($type == self::TYPE_DEPOSIT) return $langs->trans('Bill'.$prefix.'StatusConverted'); // deposit invoice
488 488
 				else return $langs->trans('Bill'.$prefix.'StatusPaid');
489 489
 			}
490 490
 		}
491 491
 		elseif ($mode == 1)
492 492
 		{
493
-			$prefix='Short';
494
-			if (! $paye)
493
+			$prefix = 'Short';
494
+			if (!$paye)
495 495
 			{
496 496
 				if ($status == 0) return $langs->trans('Bill'.$prefix.'StatusDraft');
497 497
 				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusCanceled');
@@ -508,79 +508,79 @@  discard block
 block discarded – undo
508 508
 		}
509 509
 		elseif ($mode == 2)
510 510
 		{
511
-			$prefix='Short';
512
-			if (! $paye)
511
+			$prefix = 'Short';
512
+			if (!$paye)
513 513
 			{
514
-				if ($status == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0').' '.$langs->trans('Bill'.$prefix.'StatusDraft');
515
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('StatusCanceled'),'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
516
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
517
-				elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1').' '.$langs->trans('Bill'.$prefix.'StatusNotPaid');
518
-				else return img_picto($langs->trans('BillStatusStarted'),'statut3').' '.$langs->trans('Bill'.$prefix.'StatusStarted');
514
+				if ($status == 0) return img_picto($langs->trans('BillStatusDraft'), 'statut0').' '.$langs->trans('Bill'.$prefix.'StatusDraft');
515
+				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('StatusCanceled'), 'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
516
+				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'), 'statut9').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
517
+				elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'), 'statut1').' '.$langs->trans('Bill'.$prefix.'StatusNotPaid');
518
+				else return img_picto($langs->trans('BillStatusStarted'), 'statut3').' '.$langs->trans('Bill'.$prefix.'StatusStarted');
519 519
 			}
520 520
 			else
521 521
 			{
522
-				if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
523
-				elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusConverted');
524
-				else return img_picto($langs->trans('BillStatusPaid'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaid');
522
+				if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'), 'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
523
+				elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'), 'statut6').' '.$langs->trans('Bill'.$prefix.'StatusConverted');
524
+				else return img_picto($langs->trans('BillStatusPaid'), 'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaid');
525 525
 			}
526 526
 		}
527 527
 		elseif ($mode == 3)
528 528
 		{
529
-			$prefix='Short';
530
-			if (! $paye)
529
+			$prefix = 'Short';
530
+			if (!$paye)
531 531
 			{
532
-				if ($status == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0');
533
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('BillStatusCanceled'),'statut5');
534
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9');
535
-				elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1');
536
-				else return img_picto($langs->trans('BillStatusStarted'),'statut3');
532
+				if ($status == 0) return img_picto($langs->trans('BillStatusDraft'), 'statut0');
533
+				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('BillStatusCanceled'), 'statut5');
534
+				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'), 'statut9');
535
+				elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'), 'statut1');
536
+				else return img_picto($langs->trans('BillStatusStarted'), 'statut3');
537 537
 			}
538 538
 			else
539 539
 			{
540
-				if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6');
541
-				elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'),'statut6');
542
-				else return img_picto($langs->trans('BillStatusPaid'),'statut6');
540
+				if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'), 'statut6');
541
+				elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'), 'statut6');
542
+				else return img_picto($langs->trans('BillStatusPaid'), 'statut6');
543 543
 			}
544 544
 		}
545 545
 		elseif ($mode == 4)
546 546
 		{
547
-			$prefix='';
548
-			if (! $paye)
547
+			$prefix = '';
548
+			if (!$paye)
549 549
 			{
550
-				if ($status == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0').' '.$langs->trans('BillStatusDraft');
551
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('BillStatusCanceled'),'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
552
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
553
-				elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1').' '.$langs->trans('BillStatusNotPaid');
554
-				else return img_picto($langs->trans('BillStatusStarted'),'statut3').' '.$langs->trans('BillStatusStarted');
550
+				if ($status == 0) return img_picto($langs->trans('BillStatusDraft'), 'statut0').' '.$langs->trans('BillStatusDraft');
551
+				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('BillStatusCanceled'), 'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
552
+				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'), 'statut9').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
553
+				elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'), 'statut1').' '.$langs->trans('BillStatusNotPaid');
554
+				else return img_picto($langs->trans('BillStatusStarted'), 'statut3').' '.$langs->trans('BillStatusStarted');
555 555
 			}
556 556
 			else
557 557
 			{
558
-				if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6').' '.$langs->trans('BillStatusPaidBackOrConverted');
559
-				elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'),'statut6').' '.$langs->trans('BillStatusConverted');
560
-				else return img_picto($langs->trans('BillStatusPaid'),'statut6').' '.$langs->trans('BillStatusPaid');
558
+				if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'), 'statut6').' '.$langs->trans('BillStatusPaidBackOrConverted');
559
+				elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'), 'statut6').' '.$langs->trans('BillStatusConverted');
560
+				else return img_picto($langs->trans('BillStatusPaid'), 'statut6').' '.$langs->trans('BillStatusPaid');
561 561
 			}
562 562
 		}
563 563
 		elseif ($mode == 5 || $mode == 6)
564 564
 		{
565
-			$prefix='';
566
-			if ($mode == 5) $prefix='Short';
567
-			if (! $paye)
565
+			$prefix = '';
566
+			if ($mode == 5) $prefix = 'Short';
567
+			if (!$paye)
568 568
 			{
569
-				if ($status == 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusDraft').' </span>'.img_picto($langs->trans('BillStatusDraft'),'statut0');
570
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusCanceled').' </span>'.img_picto($langs->trans('BillStatusCanceled'),'statut5');
571
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially').' </span>'.img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9');
569
+				if ($status == 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusDraft').' </span>'.img_picto($langs->trans('BillStatusDraft'), 'statut0');
570
+				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusCanceled').' </span>'.img_picto($langs->trans('BillStatusCanceled'), 'statut5');
571
+				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially').' </span>'.img_picto($langs->trans('BillStatusClosedPaidPartially'), 'statut9');
572 572
 				elseif ($alreadypaid <= 0)
573 573
 				{
574
-				    if ($type == self::TYPE_CREDIT_NOTE) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusNotRefunded').' </span>'.img_picto($langs->trans('StatusNotRefunded'),'statut1');
575
-				    return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusNotPaid').' </span>'.img_picto($langs->trans('BillStatusNotPaid'),'statut1');
574
+				    if ($type == self::TYPE_CREDIT_NOTE) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusNotRefunded').' </span>'.img_picto($langs->trans('StatusNotRefunded'), 'statut1');
575
+				    return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusNotPaid').' </span>'.img_picto($langs->trans('BillStatusNotPaid'), 'statut1');
576 576
 				}
577
-				else return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusStarted').' </span>'.img_picto($langs->trans('BillStatusStarted'),'statut3');
577
+				else return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusStarted').' </span>'.img_picto($langs->trans('BillStatusStarted'), 'statut3');
578 578
 			}
579 579
 			else
580 580
 			{
581
-				if ($type == self::TYPE_CREDIT_NOTE) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted').' </span>'.img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6');
582
-				elseif ($type == self::TYPE_DEPOSIT) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusConverted').' </span>'.img_picto($langs->trans('BillStatusConverted'),'statut6');
583
-				else return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusPaid').' </span>'.img_picto($langs->trans('BillStatusPaid'),'statut6');
581
+				if ($type == self::TYPE_CREDIT_NOTE) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted').' </span>'.img_picto($langs->trans('BillStatusPaidBackOrConverted'), 'statut6');
582
+				elseif ($type == self::TYPE_DEPOSIT) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusConverted').' </span>'.img_picto($langs->trans('BillStatusConverted'), 'statut6');
583
+				else return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusPaid').' </span>'.img_picto($langs->trans('BillStatusPaid'), 'statut6');
584 584
 			}
585 585
 		}
586 586
 	}
@@ -593,26 +593,26 @@  discard block
 block discarded – undo
593 593
 	 *	@param      integer	$cond_reglement   	Condition of payment (code or id) to use. If 0, we use current condition.
594 594
 	 *  @return     date     			       	Date limite de reglement si ok, <0 si ko
595 595
 	 */
596
-	function calculate_date_lim_reglement($cond_reglement=0)
596
+	function calculate_date_lim_reglement($cond_reglement = 0)
597 597
 	{
598 598
         // phpcs:enable
599
-		if (! $cond_reglement) $cond_reglement=$this->cond_reglement_code;
600
-		if (! $cond_reglement) $cond_reglement=$this->cond_reglement_id;
599
+		if (!$cond_reglement) $cond_reglement = $this->cond_reglement_code;
600
+		if (!$cond_reglement) $cond_reglement = $this->cond_reglement_id;
601 601
 
602
-		$cdr_nbjour=0;
603
-        $cdr_type=0;
604
-        $cdr_decalage=0;
602
+		$cdr_nbjour = 0;
603
+        $cdr_type = 0;
604
+        $cdr_decalage = 0;
605 605
 
606 606
 		$sqltemp = 'SELECT c.type_cdr, c.nbjour, c.decalage';
607
-		$sqltemp.= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c';
608
-		if (is_numeric($cond_reglement)) $sqltemp.= " WHERE c.rowid=".$cond_reglement;
607
+		$sqltemp .= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c';
608
+		if (is_numeric($cond_reglement)) $sqltemp .= " WHERE c.rowid=".$cond_reglement;
609 609
 		else {
610
-			$sqltemp.= " WHERE c.entity IN (".getEntity('c_payment_term').")";
611
-			$sqltemp.= " AND c.code='".$this->db->escape($cond_reglement)."'";
610
+			$sqltemp .= " WHERE c.entity IN (".getEntity('c_payment_term').")";
611
+			$sqltemp .= " AND c.code='".$this->db->escape($cond_reglement)."'";
612 612
 		}
613 613
 
614 614
 		dol_syslog(get_class($this).'::calculate_date_lim_reglement', LOG_DEBUG);
615
-		$resqltemp=$this->db->query($sqltemp);
615
+		$resqltemp = $this->db->query($sqltemp);
616 616
 		if ($resqltemp)
617 617
 		{
618 618
 			if ($this->db->num_rows($resqltemp))
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
 		}
626 626
 		else
627 627
 		{
628
-			$this->error=$this->db->error();
628
+			$this->error = $this->db->error();
629 629
 			return -1;
630 630
 		}
631 631
 		$this->db->free($resqltemp);
@@ -644,8 +644,8 @@  discard block
 block discarded – undo
644 644
 		{
645 645
 			$datelim = $this->date + ($cdr_nbjour * 3600 * 24);
646 646
 
647
-			$mois=date('m', $datelim);
648
-			$annee=date('Y', $datelim);
647
+			$mois = date('m', $datelim);
648
+			$annee = date('Y', $datelim);
649 649
 			if ($mois == 12)
650 650
 			{
651 651
 				$mois = 1;
@@ -656,7 +656,7 @@  discard block
 block discarded – undo
656 656
 				$mois += 1;
657 657
 			}
658 658
 			// On se deplace au debut du mois suivant, et on retire un jour
659
-			$datelim=dol_mktime(12,0,0,$mois,1,$annee);
659
+			$datelim = dol_mktime(12, 0, 0, $mois, 1, $annee);
660 660
 			$datelim -= (3600 * 24);
661 661
 
662 662
 			$datelim += ($cdr_decalage * 3600 * 24);
@@ -666,9 +666,9 @@  discard block
 block discarded – undo
666 666
 		{
667 667
 			$datelim = $this->date + ($cdr_nbjour * 3600 * 24);
668 668
 
669
-			$date_piece = dol_mktime(0, 0, 0, date('m', $datelim),date('d', $datelim),date('Y', $datelim)); // Sans les heures minutes et secondes
669
+			$date_piece = dol_mktime(0, 0, 0, date('m', $datelim), date('d', $datelim), date('Y', $datelim)); // Sans les heures minutes et secondes
670 670
 			$date_lim_current = dol_mktime(0, 0, 0, date('m', $datelim), $cdr_decalage, date('Y', $datelim)); // Sans les heures minutes et secondes
671
-			$date_lim_next = dol_time_plus_duree($date_lim_current, 1, 'm');	// Add 1 month
671
+			$date_lim_next = dol_time_plus_duree($date_lim_current, 1, 'm'); // Add 1 month
672 672
 
673 673
 			$diff = $date_piece - $date_lim_current;
674 674
 
@@ -683,7 +683,7 @@  discard block
 block discarded – undo
683 683
 
684 684
 
685 685
 
686
-require_once DOL_DOCUMENT_ROOT .'/core/class/commonobjectline.class.php';
686
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
687 687
 
688 688
 /**
689 689
  *	Parent class of all other business classes for details of elements (invoices, contracts, proposals, orders, ...)
Please login to merge, or discard this patch.
Braces   +204 added lines, -117 removed lines patch added patch discarded remove patch
@@ -132,10 +132,12 @@  discard block
 block discarded – undo
132 132
 		{
133 133
 			$obj = $this->db->fetch_object($resql);
134 134
 			$this->db->free($resql);
135
-			if ($multicurrency) return $obj->multicurrency_amount;
136
-			else return $obj->amount;
137
-		}
138
-		else
135
+			if ($multicurrency) {
136
+			    return $obj->multicurrency_amount;
137
+			} else {
138
+			    return $obj->amount;
139
+			}
140
+		} else
139 141
 		{
140 142
 			$this->error=$this->db->lasterror();
141 143
 			return -1;
@@ -164,8 +166,7 @@  discard block
 block discarded – undo
164 166
 	    if ($result >= 0)
165 167
 	    {
166 168
 	        return $result;
167
-	    }
168
-	    else
169
+	    } else
169 170
 	    {
170 171
 	        $this->error=$discountstatic->error;
171 172
 	        return -1;
@@ -187,8 +188,7 @@  discard block
 block discarded – undo
187 188
 	    if ($result >= 0)
188 189
 	    {
189 190
 	        return $result;
190
-	    }
191
-	    else
191
+	    } else
192 192
 	    {
193 193
 	        $this->error=$discountstatic->error;
194 194
 	        return -1;
@@ -219,8 +219,7 @@  discard block
 block discarded – undo
219 219
 				$idarray[]=$row[0];
220 220
 				$i++;
221 221
 			}
222
-		}
223
-		else
222
+		} else
224 223
 		{
225 224
 			dol_print_error($this->db);
226 225
 		}
@@ -239,7 +238,9 @@  discard block
 block discarded – undo
239 238
 		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
240 239
 		$sql.= ' WHERE fk_facture_source = '.$this->id;
241 240
 		$sql.= ' AND type < 2';
242
-		if ($option == 'validated') $sql.= ' AND fk_statut = 1';
241
+		if ($option == 'validated') {
242
+		    $sql.= ' AND fk_statut = 1';
243
+		}
243 244
 		// PROTECTION BAD DATA
244 245
 		// Au cas ou base corrompue et qu'il y a une facture de remplacement validee
245 246
 		// et une autre non, on donne priorite a la validee.
@@ -255,14 +256,12 @@  discard block
 block discarded – undo
255 256
 			{
256 257
 				// Si il y en a
257 258
 				return $obj->rowid;
258
-			}
259
-			else
259
+			} else
260 260
 			{
261 261
 				// Si aucune facture ne remplace
262 262
 				return 0;
263 263
 			}
264
-		}
265
-		else
264
+		} else
266 265
 		{
267 266
 			return -1;
268 267
 		}
@@ -299,7 +298,9 @@  discard block
 block discarded – undo
299 298
 		$sql.= ' AND pf.'.$field2.' = p.rowid';
300 299
 		$sql.= ' AND p.fk_paiement = t.id';
301 300
 		$sql.= ' AND p.entity IN (' . getEntity($sharedentity).')';
302
-		if ($filtertype) $sql.=" AND t.code='PRE'";
301
+		if ($filtertype) {
302
+		    $sql.=" AND t.code='PRE'";
303
+		}
303 304
 
304 305
 		dol_syslog(get_class($this)."::getListOfPayments", LOG_DEBUG);
305 306
 		$resql=$this->db->query($sql);
@@ -315,8 +316,7 @@  discard block
 block discarded – undo
315 316
 			}
316 317
 			$this->db->free($resql);
317 318
 			return $retarray;
318
-		}
319
-		else
319
+		} else
320 320
 		{
321 321
 			$this->error=$this->db->lasterror();
322 322
 			dol_print_error($this->db);
@@ -347,28 +347,39 @@  discard block
 block discarded – undo
347 347
 		// We check if invoice is a temporary number (PROVxxxx)
348 348
 		$tmppart = substr($this->ref, 1, 4);
349 349
 
350
-		if ($this->statut == self::STATUS_DRAFT && $tmppart === 'PROV') // If draft invoice and ref not yet defined
350
+		if ($this->statut == self::STATUS_DRAFT && $tmppart === 'PROV') {
351
+		    // If draft invoice and ref not yet defined
351 352
 		{
352 353
 			return 1;
353 354
 		}
355
+		}
354 356
 
355
-		if (! empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) return 0;
357
+		if (! empty($conf->global->INVOICE_CAN_NEVER_BE_REMOVED)) {
358
+		    return 0;
359
+		}
356 360
 
357 361
 		// If not a draft invoice and not temporary invoice
358 362
 		if ($tmppart !== 'PROV')
359 363
 		{
360 364
 			$ventilExportCompta = $this->getVentilExportCompta();
361
-			if ($ventilExportCompta != 0) return -1;
365
+			if ($ventilExportCompta != 0) {
366
+			    return -1;
367
+			}
362 368
 
363 369
 			// Get last number of validated invoice
364 370
 			if ($this->element != 'invoice_supplier')
365 371
 			{
366
-				if (empty($this->thirdparty)) $this->fetch_thirdparty();	// We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag).
372
+				if (empty($this->thirdparty)) {
373
+				    $this->fetch_thirdparty();
374
+				}
375
+				// We need to have this->thirdparty defined, in case of numbering rule use tags that depend on thirdparty (like {t} tag).
367 376
 				$maxref = $this->getNextNumRef($this->thirdparty,'last');
368 377
 
369 378
 				// If there is no invoice into the reset range and not already dispatched, we can delete
370 379
 				// If invoice to delete is last one and not already dispatched, we can delete
371
-				if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $maxref != '' && $maxref != $this->ref) return -2;
380
+				if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $maxref != '' && $maxref != $this->ref) {
381
+				    return -2;
382
+				}
372 383
 
373 384
 				// TODO If there is payment in bookkeeping, check payment is not dispatched in accounting
374 385
 				// ...
@@ -376,13 +387,17 @@  discard block
 block discarded – undo
376 387
 				if ($this->situation_cycle_ref && method_exists($this, 'is_last_in_cycle'))
377 388
 				{
378 389
 					$last = $this->is_last_in_cycle();
379
-					if (! $last) return -3;
390
+					if (! $last) {
391
+					    return -3;
392
+					}
380 393
 				}
381 394
 			}
382 395
 		}
383 396
 
384 397
 		// Test if there is at least one payment. If yes, refuse to delete.
385
-		if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $this->getSommePaiement() > 0) return -4;
398
+		if (empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $this->getSommePaiement() > 0) {
399
+		    return -4;
400
+		}
386 401
 
387 402
 		return 2;
388 403
 	}
@@ -397,7 +412,9 @@  discard block
 block discarded – undo
397 412
 		$alreadydispatched = 0;
398 413
 
399 414
 		$type = 'customer_invoice';
400
-		if ($this->element == 'invoice_supplier') $type = 'supplier_invoice';
415
+		if ($this->element == 'invoice_supplier') {
416
+		    $type = 'supplier_invoice';
417
+		}
401 418
 
402 419
 		$sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id;
403 420
 		$resql = $this->db->query($sql);
@@ -408,8 +425,7 @@  discard block
 block discarded – undo
408 425
 			{
409 426
 				$alreadydispatched = $obj->nb;
410 427
 			}
411
-		}
412
-		else
428
+		} else
413 429
 		{
414 430
 			$this->error = $this->db->lasterror();
415 431
 			return -1;
@@ -431,12 +447,21 @@  discard block
 block discarded – undo
431 447
 	function getLibType()
432 448
 	{
433 449
 		global $langs;
434
-        if ($this->type == CommonInvoice::TYPE_STANDARD) return $langs->trans("InvoiceStandard");
435
-        elseif ($this->type == CommonInvoice::TYPE_REPLACEMENT) return $langs->trans("InvoiceReplacement");
436
-        elseif ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) return $langs->trans("InvoiceAvoir");
437
-        elseif ($this->type == CommonInvoice::TYPE_DEPOSIT) return $langs->trans("InvoiceDeposit");
438
-        elseif ($this->type == CommonInvoice::TYPE_PROFORMA) return $langs->trans("InvoiceProForma");           // Not used.
439
-        elseif ($this->type == CommonInvoice::TYPE_SITUATION) return $langs->trans("InvoiceSituation");
450
+        if ($this->type == CommonInvoice::TYPE_STANDARD) {
451
+            return $langs->trans("InvoiceStandard");
452
+        } elseif ($this->type == CommonInvoice::TYPE_REPLACEMENT) {
453
+            return $langs->trans("InvoiceReplacement");
454
+        } elseif ($this->type == CommonInvoice::TYPE_CREDIT_NOTE) {
455
+            return $langs->trans("InvoiceAvoir");
456
+        } elseif ($this->type == CommonInvoice::TYPE_DEPOSIT) {
457
+            return $langs->trans("InvoiceDeposit");
458
+        } elseif ($this->type == CommonInvoice::TYPE_PROFORMA) {
459
+            return $langs->trans("InvoiceProForma");
460
+        }
461
+        // Not used.
462
+        elseif ($this->type == CommonInvoice::TYPE_SITUATION) {
463
+            return $langs->trans("InvoiceSituation");
464
+        }
440 465
 		return $langs->trans("Unknown");
441 466
 	}
442 467
 
@@ -475,112 +500,167 @@  discard block
 block discarded – undo
475 500
 			$prefix='';
476 501
 			if (! $paye)
477 502
 			{
478
-				if ($status == 0) return $langs->trans('Bill'.$prefix.'StatusDraft');
479
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusClosedUnpaid');
480
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
481
-				elseif ($alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusNotPaid');
482
-				else return $langs->trans('Bill'.$prefix.'StatusStarted');
483
-			}
484
-			else
503
+				if ($status == 0) {
504
+				    return $langs->trans('Bill'.$prefix.'StatusDraft');
505
+				} elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) {
506
+				    return $langs->trans('Bill'.$prefix.'StatusClosedUnpaid');
507
+				} elseif (($status == 3 || $status == 2) && $alreadypaid > 0) {
508
+				    return $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
509
+				} elseif ($alreadypaid <= 0) {
510
+				    return $langs->trans('Bill'.$prefix.'StatusNotPaid');
511
+				} else {
512
+				    return $langs->trans('Bill'.$prefix.'StatusStarted');
513
+				}
514
+			} else
485 515
 			{
486
-				if ($type == self::TYPE_CREDIT_NOTE) return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');       // credit note
487
-				elseif ($type == self::TYPE_DEPOSIT) return $langs->trans('Bill'.$prefix.'StatusConverted');             // deposit invoice
488
-				else return $langs->trans('Bill'.$prefix.'StatusPaid');
516
+				if ($type == self::TYPE_CREDIT_NOTE) {
517
+				    return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
518
+				}
519
+				// credit note
520
+				elseif ($type == self::TYPE_DEPOSIT) {
521
+				    return $langs->trans('Bill'.$prefix.'StatusConverted');
522
+				}
523
+				// deposit invoice
524
+				else {
525
+				    return $langs->trans('Bill'.$prefix.'StatusPaid');
526
+				}
489 527
 			}
490
-		}
491
-		elseif ($mode == 1)
528
+		} elseif ($mode == 1)
492 529
 		{
493 530
 			$prefix='Short';
494 531
 			if (! $paye)
495 532
 			{
496
-				if ($status == 0) return $langs->trans('Bill'.$prefix.'StatusDraft');
497
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusCanceled');
498
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
499
-				elseif ($alreadypaid <= 0) return $langs->trans('Bill'.$prefix.'StatusNotPaid');
500
-				else return $langs->trans('Bill'.$prefix.'StatusStarted');
501
-			}
502
-			else
533
+				if ($status == 0) {
534
+				    return $langs->trans('Bill'.$prefix.'StatusDraft');
535
+				} elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) {
536
+				    return $langs->trans('Bill'.$prefix.'StatusCanceled');
537
+				} elseif (($status == 3 || $status == 2) && $alreadypaid > 0) {
538
+				    return $langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
539
+				} elseif ($alreadypaid <= 0) {
540
+				    return $langs->trans('Bill'.$prefix.'StatusNotPaid');
541
+				} else {
542
+				    return $langs->trans('Bill'.$prefix.'StatusStarted');
543
+				}
544
+			} else
503 545
 			{
504
-				if ($type == self::TYPE_CREDIT_NOTE) return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
505
-				elseif ($type == self::TYPE_DEPOSIT) return $langs->trans('Bill'.$prefix.'StatusConverted');
506
-				else return $langs->trans('Bill'.$prefix.'StatusPaid');
546
+				if ($type == self::TYPE_CREDIT_NOTE) {
547
+				    return $langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
548
+				} elseif ($type == self::TYPE_DEPOSIT) {
549
+				    return $langs->trans('Bill'.$prefix.'StatusConverted');
550
+				} else {
551
+				    return $langs->trans('Bill'.$prefix.'StatusPaid');
552
+				}
507 553
 			}
508
-		}
509
-		elseif ($mode == 2)
554
+		} elseif ($mode == 2)
510 555
 		{
511 556
 			$prefix='Short';
512 557
 			if (! $paye)
513 558
 			{
514
-				if ($status == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0').' '.$langs->trans('Bill'.$prefix.'StatusDraft');
515
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('StatusCanceled'),'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
516
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
517
-				elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1').' '.$langs->trans('Bill'.$prefix.'StatusNotPaid');
518
-				else return img_picto($langs->trans('BillStatusStarted'),'statut3').' '.$langs->trans('Bill'.$prefix.'StatusStarted');
519
-			}
520
-			else
559
+				if ($status == 0) {
560
+				    return img_picto($langs->trans('BillStatusDraft'),'statut0').' '.$langs->trans('Bill'.$prefix.'StatusDraft');
561
+				} elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) {
562
+				    return img_picto($langs->trans('StatusCanceled'),'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
563
+				} elseif (($status == 3 || $status == 2) && $alreadypaid > 0) {
564
+				    return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
565
+				} elseif ($alreadypaid <= 0) {
566
+				    return img_picto($langs->trans('BillStatusNotPaid'),'statut1').' '.$langs->trans('Bill'.$prefix.'StatusNotPaid');
567
+				} else {
568
+				    return img_picto($langs->trans('BillStatusStarted'),'statut3').' '.$langs->trans('Bill'.$prefix.'StatusStarted');
569
+				}
570
+			} else
521 571
 			{
522
-				if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
523
-				elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusConverted');
524
-				else return img_picto($langs->trans('BillStatusPaid'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaid');
572
+				if ($type == self::TYPE_CREDIT_NOTE) {
573
+				    return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted');
574
+				} elseif ($type == self::TYPE_DEPOSIT) {
575
+				    return img_picto($langs->trans('BillStatusConverted'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusConverted');
576
+				} else {
577
+				    return img_picto($langs->trans('BillStatusPaid'),'statut6').' '.$langs->trans('Bill'.$prefix.'StatusPaid');
578
+				}
525 579
 			}
526
-		}
527
-		elseif ($mode == 3)
580
+		} elseif ($mode == 3)
528 581
 		{
529 582
 			$prefix='Short';
530 583
 			if (! $paye)
531 584
 			{
532
-				if ($status == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0');
533
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('BillStatusCanceled'),'statut5');
534
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9');
535
-				elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1');
536
-				else return img_picto($langs->trans('BillStatusStarted'),'statut3');
537
-			}
538
-			else
585
+				if ($status == 0) {
586
+				    return img_picto($langs->trans('BillStatusDraft'),'statut0');
587
+				} elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) {
588
+				    return img_picto($langs->trans('BillStatusCanceled'),'statut5');
589
+				} elseif (($status == 3 || $status == 2) && $alreadypaid > 0) {
590
+				    return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9');
591
+				} elseif ($alreadypaid <= 0) {
592
+				    return img_picto($langs->trans('BillStatusNotPaid'),'statut1');
593
+				} else {
594
+				    return img_picto($langs->trans('BillStatusStarted'),'statut3');
595
+				}
596
+			} else
539 597
 			{
540
-				if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6');
541
-				elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'),'statut6');
542
-				else return img_picto($langs->trans('BillStatusPaid'),'statut6');
598
+				if ($type == self::TYPE_CREDIT_NOTE) {
599
+				    return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6');
600
+				} elseif ($type == self::TYPE_DEPOSIT) {
601
+				    return img_picto($langs->trans('BillStatusConverted'),'statut6');
602
+				} else {
603
+				    return img_picto($langs->trans('BillStatusPaid'),'statut6');
604
+				}
543 605
 			}
544
-		}
545
-		elseif ($mode == 4)
606
+		} elseif ($mode == 4)
546 607
 		{
547 608
 			$prefix='';
548 609
 			if (! $paye)
549 610
 			{
550
-				if ($status == 0) return img_picto($langs->trans('BillStatusDraft'),'statut0').' '.$langs->trans('BillStatusDraft');
551
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return img_picto($langs->trans('BillStatusCanceled'),'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
552
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
553
-				elseif ($alreadypaid <= 0) return img_picto($langs->trans('BillStatusNotPaid'),'statut1').' '.$langs->trans('BillStatusNotPaid');
554
-				else return img_picto($langs->trans('BillStatusStarted'),'statut3').' '.$langs->trans('BillStatusStarted');
555
-			}
556
-			else
611
+				if ($status == 0) {
612
+				    return img_picto($langs->trans('BillStatusDraft'),'statut0').' '.$langs->trans('BillStatusDraft');
613
+				} elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) {
614
+				    return img_picto($langs->trans('BillStatusCanceled'),'statut5').' '.$langs->trans('Bill'.$prefix.'StatusCanceled');
615
+				} elseif (($status == 3 || $status == 2) && $alreadypaid > 0) {
616
+				    return img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9').' '.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially');
617
+				} elseif ($alreadypaid <= 0) {
618
+				    return img_picto($langs->trans('BillStatusNotPaid'),'statut1').' '.$langs->trans('BillStatusNotPaid');
619
+				} else {
620
+				    return img_picto($langs->trans('BillStatusStarted'),'statut3').' '.$langs->trans('BillStatusStarted');
621
+				}
622
+			} else
557 623
 			{
558
-				if ($type == self::TYPE_CREDIT_NOTE) return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6').' '.$langs->trans('BillStatusPaidBackOrConverted');
559
-				elseif ($type == self::TYPE_DEPOSIT) return img_picto($langs->trans('BillStatusConverted'),'statut6').' '.$langs->trans('BillStatusConverted');
560
-				else return img_picto($langs->trans('BillStatusPaid'),'statut6').' '.$langs->trans('BillStatusPaid');
624
+				if ($type == self::TYPE_CREDIT_NOTE) {
625
+				    return img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6').' '.$langs->trans('BillStatusPaidBackOrConverted');
626
+				} elseif ($type == self::TYPE_DEPOSIT) {
627
+				    return img_picto($langs->trans('BillStatusConverted'),'statut6').' '.$langs->trans('BillStatusConverted');
628
+				} else {
629
+				    return img_picto($langs->trans('BillStatusPaid'),'statut6').' '.$langs->trans('BillStatusPaid');
630
+				}
561 631
 			}
562
-		}
563
-		elseif ($mode == 5 || $mode == 6)
632
+		} elseif ($mode == 5 || $mode == 6)
564 633
 		{
565 634
 			$prefix='';
566
-			if ($mode == 5) $prefix='Short';
635
+			if ($mode == 5) {
636
+			    $prefix='Short';
637
+			}
567 638
 			if (! $paye)
568 639
 			{
569
-				if ($status == 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusDraft').' </span>'.img_picto($langs->trans('BillStatusDraft'),'statut0');
570
-				elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusCanceled').' </span>'.img_picto($langs->trans('BillStatusCanceled'),'statut5');
571
-				elseif (($status == 3 || $status == 2) && $alreadypaid > 0) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially').' </span>'.img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9');
572
-				elseif ($alreadypaid <= 0)
640
+				if ($status == 0) {
641
+				    return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusDraft').' </span>'.img_picto($langs->trans('BillStatusDraft'),'statut0');
642
+				} elseif (($status == 3 || $status == 2) && $alreadypaid <= 0) {
643
+				    return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusCanceled').' </span>'.img_picto($langs->trans('BillStatusCanceled'),'statut5');
644
+				} elseif (($status == 3 || $status == 2) && $alreadypaid > 0) {
645
+				    return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusClosedPaidPartially').' </span>'.img_picto($langs->trans('BillStatusClosedPaidPartially'),'statut9');
646
+				} elseif ($alreadypaid <= 0)
573 647
 				{
574
-				    if ($type == self::TYPE_CREDIT_NOTE) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusNotRefunded').' </span>'.img_picto($langs->trans('StatusNotRefunded'),'statut1');
648
+				    if ($type == self::TYPE_CREDIT_NOTE) {
649
+				        return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusNotRefunded').' </span>'.img_picto($langs->trans('StatusNotRefunded'),'statut1');
650
+				    }
575 651
 				    return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusNotPaid').' </span>'.img_picto($langs->trans('BillStatusNotPaid'),'statut1');
652
+				} else {
653
+				    return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusStarted').' </span>'.img_picto($langs->trans('BillStatusStarted'),'statut3');
576 654
 				}
577
-				else return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusStarted').' </span>'.img_picto($langs->trans('BillStatusStarted'),'statut3');
578
-			}
579
-			else
655
+			} else
580 656
 			{
581
-				if ($type == self::TYPE_CREDIT_NOTE) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted').' </span>'.img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6');
582
-				elseif ($type == self::TYPE_DEPOSIT) return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusConverted').' </span>'.img_picto($langs->trans('BillStatusConverted'),'statut6');
583
-				else return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusPaid').' </span>'.img_picto($langs->trans('BillStatusPaid'),'statut6');
657
+				if ($type == self::TYPE_CREDIT_NOTE) {
658
+				    return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusPaidBackOrConverted').' </span>'.img_picto($langs->trans('BillStatusPaidBackOrConverted'),'statut6');
659
+				} elseif ($type == self::TYPE_DEPOSIT) {
660
+				    return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusConverted').' </span>'.img_picto($langs->trans('BillStatusConverted'),'statut6');
661
+				} else {
662
+				    return '<span class="xhideonsmartphone">'.$langs->trans('Bill'.$prefix.'StatusPaid').' </span>'.img_picto($langs->trans('BillStatusPaid'),'statut6');
663
+				}
584 664
 			}
585 665
 		}
586 666
 	}
@@ -596,8 +676,12 @@  discard block
 block discarded – undo
596 676
 	function calculate_date_lim_reglement($cond_reglement=0)
597 677
 	{
598 678
         // phpcs:enable
599
-		if (! $cond_reglement) $cond_reglement=$this->cond_reglement_code;
600
-		if (! $cond_reglement) $cond_reglement=$this->cond_reglement_id;
679
+		if (! $cond_reglement) {
680
+		    $cond_reglement=$this->cond_reglement_code;
681
+		}
682
+		if (! $cond_reglement) {
683
+		    $cond_reglement=$this->cond_reglement_id;
684
+		}
601 685
 
602 686
 		$cdr_nbjour=0;
603 687
         $cdr_type=0;
@@ -605,8 +689,9 @@  discard block
 block discarded – undo
605 689
 
606 690
 		$sqltemp = 'SELECT c.type_cdr, c.nbjour, c.decalage';
607 691
 		$sqltemp.= ' FROM '.MAIN_DB_PREFIX.'c_payment_term as c';
608
-		if (is_numeric($cond_reglement)) $sqltemp.= " WHERE c.rowid=".$cond_reglement;
609
-		else {
692
+		if (is_numeric($cond_reglement)) {
693
+		    $sqltemp.= " WHERE c.rowid=".$cond_reglement;
694
+		} else {
610 695
 			$sqltemp.= " WHERE c.entity IN (".getEntity('c_payment_term').")";
611 696
 			$sqltemp.= " AND c.code='".$this->db->escape($cond_reglement)."'";
612 697
 		}
@@ -622,8 +707,7 @@  discard block
 block discarded – undo
622 707
 				$cdr_type = $obj->type_cdr;
623 708
 				$cdr_decalage = $obj->decalage;
624 709
 			}
625
-		}
626
-		else
710
+		} else
627 711
 		{
628 712
 			$this->error=$this->db->error();
629 713
 			return -1;
@@ -650,8 +734,7 @@  discard block
 block discarded – undo
650 734
 			{
651 735
 				$mois = 1;
652 736
 				$annee += 1;
653
-			}
654
-			else
737
+			} else
655 738
 			{
656 739
 				$mois += 1;
657 740
 			}
@@ -672,10 +755,14 @@  discard block
 block discarded – undo
672 755
 
673 756
 			$diff = $date_piece - $date_lim_current;
674 757
 
675
-			if ($diff < 0) $datelim = $date_lim_current;
676
-			else $datelim = $date_lim_next;
758
+			if ($diff < 0) {
759
+			    $datelim = $date_lim_current;
760
+			} else {
761
+			    $datelim = $date_lim_next;
762
+			}
763
+		} else {
764
+		    return 'Bad value for type_cdr in database for record cond_reglement = '.$cond_reglement;
677 765
 		}
678
-		else return 'Bad value for type_cdr in database for record cond_reglement = '.$cond_reglement;
679 766
 
680 767
 		return $datelim;
681 768
 	}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.form.class.php 3 patches
Indentation   +6816 added lines, -6816 removed lines patch added patch discarded remove patch
@@ -51,564 +51,564 @@  discard block
 block discarded – undo
51 51
  */
52 52
 class Form
53 53
 {
54
-	/**
54
+    /**
55 55
      * @var DoliDB Database handler.
56 56
      */
57 57
     public $db;
58 58
 
59
-	/**
60
-	 * @var string Error code (or message)
61
-	 */
62
-	public $error='';
59
+    /**
60
+     * @var string Error code (or message)
61
+     */
62
+    public $error='';
63 63
 
64 64
     /**
65 65
      * @var string[]    Array of error strings
66 66
      */
67 67
     public $errors = array();
68 68
 
69
-	public $num;
70
-
71
-	// Cache arrays
72
-	public $cache_types_paiements=array();
73
-	public $cache_conditions_paiements=array();
74
-	public $cache_availability=array();
75
-	public $cache_demand_reason=array();
76
-	public $cache_types_fees=array();
77
-	public $cache_vatrates=array();
78
-
79
-
80
-	/**
81
-	 * Constructor
82
-	 *
83
-	 * @param		DoliDB		$db      Database handler
84
-	 */
85
-	public function __construct($db)
86
-	{
87
-		$this->db = $db;
88
-	}
89
-
90
-	/**
91
-	 * Output key field for an editable field
92
-	 *
93
-	 * @param   string	$text			Text of label or key to translate
94
-	 * @param   string	$htmlname		Name of select field ('edit' prefix will be added)
95
-	 * @param   string	$preselected    Value to show/edit (not used in this function)
96
-	 * @param	object	$object			Object
97
-	 * @param	boolean	$perm			Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
98
-	 * @param	string	$typeofdata		Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
99
-	 * @param	string	$moreparam		More param to add on a href URL.
100
-	 * @param   int     $fieldrequired  1 if we want to show field as mandatory using the "fieldrequired" CSS.
101
-	 * @param   int     $notabletag     1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' '
102
-	 * @param	string	$paramid		Key of parameter for id ('id', 'socid')
103
-	 * @return	string					HTML edit field
104
-	 */
105
-	function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0, $paramid='id')
106
-	{
107
-		global $conf,$langs;
108
-
109
-		$ret='';
110
-
111
-		// TODO change for compatibility
112
-		if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata))
113
-		{
114
-			if (! empty($perm))
115
-			{
116
-				$tmp=explode(':',$typeofdata);
117
-				$ret.= '<div class="editkey_'.$tmp[0].(! empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
118
-				if ($fieldrequired) $ret.='<span class="fieldrequired">';
119
-				$ret.= $langs->trans($text);
120
-				if ($fieldrequired) $ret.='</span>';
121
-				$ret.= '</div>'."\n";
122
-			}
123
-			else
124
-			{
125
-				if ($fieldrequired) $ret.='<span class="fieldrequired">';
126
-				$ret.= $langs->trans($text);
127
-				if ($fieldrequired) $ret.='</span>';
128
-			}
129
-		}
130
-		else
131
-		{
132
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
133
-			if ($fieldrequired) $ret.='<span class="fieldrequired">';
134
-			$ret.=$langs->trans($text);
135
-			if ($fieldrequired) $ret.='</span>';
136
-			if (! empty($notabletag)) $ret.=' ';
137
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
138
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<td align="right">';
139
-			if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
140
-			if (! empty($notabletag) && $notabletag == 1) $ret.=' : ';
141
-			if (! empty($notabletag) && $notabletag == 3) $ret.=' ';
142
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
143
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</tr></table>';
144
-		}
145
-
146
-		return $ret;
147
-	}
148
-
149
-	/**
150
-	 * Output value of a field for an editable field
151
-	 *
152
-	 * @param	string	$text			Text of label (not used in this function)
153
-	 * @param	string	$htmlname		Name of select field
154
-	 * @param	string	$value			Value to show/edit
155
-	 * @param	object	$object			Object
156
-	 * @param	boolean	$perm			Permission to allow button to edit parameter
157
-	 * @param	string	$typeofdata		Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...)
158
-	 * @param	string	$editvalue		When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value
159
-	 * @param	object	$extObject		External object
160
-	 * @param	mixed	$custommsg		String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
161
-	 * @param	string	$moreparam		More param to add on the form action href URL
162
-	 * @param   int     $notabletag     Do no output table tags
163
-	 * @param	string	$formatfunc		Call a specific function to output field
164
-	 * @param	string	$paramid		Key of parameter for id ('id', 'socid')
165
-	 * @return  string					HTML edit field
166
-	 */
167
-	function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0, $formatfunc='', $paramid='id')
168
-	{
169
-		global $conf,$langs,$db;
170
-
171
-		$ret='';
172
-
173
-		// Check parameters
174
-		if (empty($typeofdata)) return 'ErrorBadParameter';
175
-
176
-		// When option to edit inline is activated
177
-		if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker
178
-		{
179
-			$ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
180
-		}
181
-		else
182
-		{
183
-			if (GETPOST('action','aZ09') == 'edit'.$htmlname)
184
-			{
185
-				$ret.="\n";
186
-				$ret.='<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam?'?'.$moreparam:'').'">';
187
-				$ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
188
-				$ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
189
-				$ret.='<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
190
-				if (empty($notabletag)) $ret.='<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
191
-				if (empty($notabletag)) $ret.='<tr><td>';
192
-				if (preg_match('/^(string|email)/',$typeofdata))
193
-				{
194
-					$tmp=explode(':',$typeofdata);
195
-					$ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue?$editvalue:$value).'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
196
-				}
197
-				else if (preg_match('/^(numeric|amount)/',$typeofdata))
198
-				{
199
-					$tmp=explode(':',$typeofdata);
200
-					$valuetoshow=price2num($editvalue?$editvalue:$value);
201
-					$ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow!=''?price($valuetoshow):'').'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
202
-				}
203
-				else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))
204
-				{
205
-					$tmp=explode(':',$typeofdata);
206
-					$cols=$tmp[2];
207
-					$morealt='';
208
-					if (preg_match('/%/',$cols))
209
-					{
210
-						$morealt=' style="width: '.$cols.'"';
211
-						$cols='';
212
-					}
69
+    public $num;
213 70
 
214
-					$valuetoshow = ($editvalue?$editvalue:$value);
215
-
216
-					$ret.='<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1]?$tmp[1]:'20').'"'.($cols?' cols="'.$cols.'"':'class="quatrevingtpercent"').$morealt.'">';
217
-					$ret.=dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
218
-					$ret.='</textarea>';
219
-				}
220
-				else if ($typeofdata == 'day' || $typeofdata == 'datepicker')
221
-				{
222
-					$ret.=$this->selectDate($value,$htmlname,0,0,1,'form'.$htmlname,1,0);
223
-				}
224
-				else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
225
-				{
226
-					$ret.=$this->selectDate($value,$htmlname,1,1,1,'form'.$htmlname,1,0);
227
-				}
228
-				else if (preg_match('/^select;/',$typeofdata))
229
-				{
230
-					 $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
231
-					 foreach($arraydata as $val)
232
-					 {
233
-						 $tmp=explode(':',$val);
234
-						 $arraylist[$tmp[0]]=$tmp[1];
235
-					 }
236
-					 $ret.=$this->selectarray($htmlname,$arraylist,$value);
237
-				}
238
-				else if (preg_match('/^ckeditor/',$typeofdata))
239
-				{
240
-					$tmp=explode(':',$typeofdata);		// Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols
241
-					require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
242
-					$doleditor=new DolEditor($htmlname, ($editvalue?$editvalue:$value), ($tmp[2]?$tmp[2]:''), ($tmp[3]?$tmp[3]:'100'), ($tmp[1]?$tmp[1]:'dolibarr_notes'), 'In', ($tmp[5]?$tmp[5]:0), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100'));
243
-					$ret.=$doleditor->Create(1);
244
-				}
245
-				if (empty($notabletag)) $ret.='</td>';
246
-
247
-				if (empty($notabletag)) $ret.='<td align="left">';
248
-				//else $ret.='<div class="clearboth"></div>';
249
-			   	$ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="modify" value="'.$langs->trans("Modify").'">';
250
-			   	if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='<br>'."\n";
251
-			   	$ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
252
-			   	if (empty($notabletag)) $ret.='</td>';
253
-
254
-			   	if (empty($notabletag)) $ret.='</tr></table>'."\n";
255
-				$ret.='</form>'."\n";
256
-			}
257
-			else
258
-			{
259
-				if (preg_match('/^(email)/',$typeofdata))              $ret.=dol_print_email($value,0,0,0,0,1);
260
-				elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');
261
-				elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))  $ret.=dol_htmlentitiesbr($value);
262
-				elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');
263
-				elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour');
264
-				else if (preg_match('/^select;/',$typeofdata))
265
-				{
266
-					$arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
267
-					foreach($arraydata as $val)
268
-					{
269
-						$tmp=explode(':',$val);
270
-						$arraylist[$tmp[0]]=$tmp[1];
271
-					}
272
-					$ret.=$arraylist[$value];
273
-				}
274
-				else if (preg_match('/^ckeditor/',$typeofdata))
275
-				{
276
-					$tmpcontent=dol_htmlentitiesbr($value);
277
-					if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
278
-					{
279
-						$firstline=preg_replace('/<br>.*/','',$tmpcontent);
280
-						$firstline=preg_replace('/[\n\r].*/','',$firstline);
281
-						$tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');
282
-					}
283
-					$ret.=$tmpcontent;
284
-				}
285
-				else $ret.=$value;
286
-
287
-				if ($formatfunc && method_exists($object, $formatfunc))
288
-				{
289
-					$ret=$object->$formatfunc($ret);
290
-				}
291
-			}
292
-		}
293
-		return $ret;
294
-	}
295
-
296
-	/**
297
-	 * Output edit in place form
298
-	 *
299
-	 * @param	object	$object			Object
300
-	 * @param	string	$value			Value to show/edit
301
-	 * @param	string	$htmlname		DIV ID (field name)
302
-	 * @param	int		$condition		Condition to edit
303
-	 * @param	string	$inputType		Type of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx')
304
-	 * @param	string	$editvalue		When in edit mode, use this value as $value instead of value
305
-	 * @param	object	$extObject		External object
306
-	 * @param	mixed	$custommsg		String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
307
-	 * @return	string   		      	HTML edit in place
308
-	 */
309
-	private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)
310
-	{
311
-		global $conf;
312
-
313
-		$out='';
314
-
315
-		// Check parameters
316
-		if (preg_match('/^text/',$inputType)) $value = dol_nl2br($value);
317
-		else if (preg_match('/^numeric/',$inputType)) $value = price($value);
318
-		else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');
319
-
320
-		if ($condition)
321
-		{
322
-			$element		= false;
323
-			$table_element	= false;
324
-			$fk_element		= false;
325
-			$loadmethod		= false;
326
-			$savemethod		= false;
327
-			$ext_element	= false;
328
-			$button_only	= false;
329
-			$inputOption    = '';
330
-
331
-			if (is_object($object))
332
-			{
333
-				$element = $object->element;
334
-				$table_element = $object->table_element;
335
-				$fk_element = $object->id;
336
-			}
337
-
338
-			if (is_object($extObject))
339
-			{
340
-				$ext_element = $extObject->element;
341
-			}
342
-
343
-			if (preg_match('/^(string|email|numeric)/',$inputType))
344
-			{
345
-				$tmp=explode(':',$inputType);
346
-				$inputType=$tmp[0];
347
-				if (! empty($tmp[1])) $inputOption=$tmp[1];
348
-				if (! empty($tmp[2])) $savemethod=$tmp[2];
349
-				$out.= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
350
-			}
351
-			else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))
352
-			{
353
-				$tmp=explode(':',$inputType);
354
-				$inputType=$tmp[0];
355
-				if (! empty($tmp[1])) $inputOption=$tmp[1];
356
-				if (! empty($tmp[2])) $savemethod=$tmp[2];
357
-
358
-				$out.= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
359
-			}
360
-			else if (preg_match('/^(select|autocomplete)/',$inputType))
361
-			{
362
-				$tmp=explode(':',$inputType);
363
-				$inputType=$tmp[0]; $loadmethod=$tmp[1];
364
-				if (! empty($tmp[2])) $savemethod=$tmp[2];
365
-				if (! empty($tmp[3])) $button_only=true;
366
-			}
367
-			else if (preg_match('/^textarea/',$inputType))
368
-			{
369
-				$tmp=explode(':',$inputType);
370
-				$inputType=$tmp[0];
371
-				$rows=(empty($tmp[1])?'8':$tmp[1]);
372
-				$cols=(empty($tmp[2])?'80':$tmp[2]);
373
-			}
374
-			else if (preg_match('/^ckeditor/',$inputType))
375
-			{
376
-				$tmp=explode(':',$inputType);
377
-				$inputType=$tmp[0]; $toolbar=$tmp[1];
378
-				if (! empty($tmp[2])) $width=$tmp[2];
379
-				if (! empty($tmp[3])) $heigth=$tmp[3];
380
-				if (! empty($tmp[4])) $savemethod=$tmp[4];
381
-
382
-				if (! empty($conf->fckeditor->enabled))
383
-				{
384
-					$out.= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
385
-				}
386
-				else
387
-				{
388
-					$inputType = 'textarea';
389
-				}
390
-			}
391
-
392
-			$out.= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
393
-			$out.= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
394
-			$out.= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
395
-			$out.= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
396
-			if (! empty($savemethod))	$out.= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
397
-			if (! empty($ext_element))	$out.= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
398
-			if (! empty($custommsg))
399
-			{
400
-				if (is_array($custommsg))
401
-				{
402
-					if (!empty($custommsg['success']))
403
-						$out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
404
-					if (!empty($custommsg['error']))
405
-						$out.= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
406
-				}
407
-				else
408
-					$out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
409
-			}
410
-			if ($inputType == 'textarea') {
411
-				$out.= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
412
-				$out.= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
413
-			}
414
-			$out.= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
415
-			$out.= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(! empty($editvalue) ? $editvalue : $value).'</span>'."\n";
416
-		}
417
-		else
418
-		{
419
-			$out = $value;
420
-		}
421
-
422
-		return $out;
423
-	}
424
-
425
-	/**
426
-	 *	Show a text and picto with tooltip on text or picto.
427
-	 *  Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
428
-	 *
429
-	 *	@param	string		$text				Text to show
430
-	 *	@param	string		$htmltext			HTML content of tooltip. Must be HTML/UTF8 encoded.
431
-	 *	@param	int			$tooltipon			1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
432
-	 *	@param	int			$direction			-1=image is before, 0=no image, 1=image is after
433
-	 *	@param	string		$img				Html code for image (use img_xxx() function to get it)
434
-	 *	@param	string		$extracss			Add a CSS style to td tags
435
-	 *	@param	int			$notabs				0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
436
-	 *	@param	string		$incbefore			Include code before the text
437
-	 *	@param	int			$noencodehtmltext	Do not encode into html entity the htmltext
438
-	 *  @param  string      $tooltiptrigger		''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
439
-	 *  @param	int			$forcenowrap		Force no wrap between text and picto (works with notabs=2 only)
440
-	 *	@return	string							Code html du tooltip (texte+picto)
441
-	 *	@see	Use function textwithpicto if you can.
442
-	 *  TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip
443
-	 */
444
-	function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='', $forcenowrap=0)
445
-	{
446
-		global $conf;
447
-
448
-		if ($incbefore) $text = $incbefore.$text;
449
-		if (! $htmltext) return $text;
450
-
451
-		$tag='td';
452
-		if ($notabs == 2) $tag='div';
453
-		if ($notabs == 3) $tag='span';
454
-		// Sanitize tooltip
455
-		$htmltext=str_replace("\\","\\\\",$htmltext);
456
-		$htmltext=str_replace("\r","",$htmltext);
457
-		$htmltext=str_replace("\n","",$htmltext);
458
-
459
-		$extrastyle='';
460
-		if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; }
461
-		if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; }
462
-
463
-		$classfortooltip='classfortooltip';
464
-
465
-		$s='';$textfordialog='';
466
-
467
-		if ($tooltiptrigger == '')
468
-		{
469
-			$htmltext=str_replace('"',"&quot;",$htmltext);
470
-		}
471
-		else
472
-		{
473
-			$classfortooltip='classfortooltiponclick';
474
-			$textfordialog.='<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
475
-		}
476
-		if ($tooltipon == 2 || $tooltipon == 3)
477
-		{
478
-			$paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"';
479
-			if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip
480
-			else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"';
481
-		}
482
-		else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
483
-		if ($tooltipon == 1 || $tooltipon == 3)
484
-		{
485
-			$paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" ';
486
-			if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip
487
-			else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"';
488
-		}
489
-		else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
490
-		if (empty($notabs)) $s.='<table class="nobordernopadding" summary=""><tr style="height: auto;">';
491
-		elseif ($notabs == 2) $s.='<div class="inline-block'.($forcenowrap?' nowrap':'').'">';
492
-		// Define value if value is before
493
-		if ($direction < 0) {
494
-			$s.='<'.$tag.$paramfortooltipimg;
495
-			if ($tag == 'td') {
496
-				$s .= ' valign="top" width="14"';
497
-			}
498
-			$s.= '>'.$textfordialog.$img.'</'.$tag.'>';
499
-		}
500
-		// Use another method to help avoid having a space in value in order to use this value with jquery
501
-		// Define label
502
-		if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
503
-		// Define value if value is after
504
-		if ($direction > 0) {
505
-			$s.='<'.$tag.$paramfortooltipimg;
506
-			if ($tag == 'td') $s .= ' valign="middle" width="14"';
507
-			$s.= '>'.$textfordialog.$img.'</'.$tag.'>';
508
-		}
509
-		if (empty($notabs)) $s.='</tr></table>';
510
-		elseif ($notabs == 2) $s.='</div>';
511
-
512
-		return $s;
513
-	}
514
-
515
-	/**
516
-	 *	Show a text with a picto and a tooltip on picto
517
-	 *
518
-	 *	@param	string	$text				Text to show
519
-	 *	@param  string	$htmltext	     	Content of tooltip
520
-	 *	@param	int		$direction			1=Icon is after text, -1=Icon is before text, 0=no icon
521
-	 * 	@param	string	$type				Type of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath
522
-	 *  @param  string	$extracss           Add a CSS style to td, div or span tag
523
-	 *  @param  int		$noencodehtmltext   Do not encode into html entity the htmltext
524
-	 *  @param	int		$notabs				0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
525
-	 *  @param  string  $tooltiptrigger     ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
526
-	 *  @param	int		$forcenowrap		Force no wrap between text and picto (works with notabs=2 only)
527
-	 * 	@return	string						HTML code of text, picto, tooltip
528
-	 */
529
-	function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='', $forcenowrap=0)
530
-	{
531
-		global $conf, $langs;
532
-
533
-		$alt = '';
534
-		if ($tooltiptrigger) $alt=$langs->transnoentitiesnoconv("ClickToShowHelp");
535
-
536
-		//For backwards compatibility
537
-		if ($type == '0') $type = 'info';
538
-		elseif ($type == '1') $type = 'help';
539
-
540
-		// If info or help with no javascript, show only text
541
-		if (empty($conf->use_javascript_ajax))
542
-		{
543
-			if ($type == 'info' || $type == 'help')	return $text;
544
-			else
545
-			{
546
-				$alt = $htmltext;
547
-				$htmltext = '';
548
-			}
549
-		}
550
-
551
-		// If info or help with smartphone, show only text (tooltip hover can't works)
552
-		if (! empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))
553
-		{
554
-			if ($type == 'info' || $type == 'help') return $text;
555
-		}
556
-		// If info or help with smartphone, show only text (tooltip on lick does not works with dialog on smaprtphone)
557
-		if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
558
-		{
559
-			if ($type == 'info' || $type == 'help') return $text;
560
-		}
561
-
562
-		if ($type == 'info') $img = img_help(0, $alt);
563
-		elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
564
-		elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');
565
-		elseif ($type == 'admin') $img = img_picto($alt, 'star');
566
-		elseif ($type == 'warning') $img = img_warning($alt);
567
-		else $img = img_picto($alt, $type);
568
-
569
-		return $this->textwithtooltip($text, $htmltext, (($tooltiptrigger && ! $img)?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
570
-	}
571
-
572
-	/**
573
-	 * Generate select HTML to choose massaction
574
-	 *
575
-	 * @param	string	$selected		Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
576
-	 * @param	int		$arrayofaction	array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
577
-	 * @param   int     $alwaysvisible  1=select button always visible
578
-	 * @return	string					Select list
579
-	 */
580
-	function selectMassAction($selected, $arrayofaction, $alwaysvisible=0)
581
-	{
582
-		global $conf,$langs,$hookmanager;
583
-
584
-		if (count($arrayofaction) == 0) return;
585
-
586
-		$disabled=0;
587
-		$ret='<div class="centpercent center">';
588
-		$ret.='<select class="flat'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionselect" name="massaction"'.($disabled?' disabled="disabled"':'').'>';
589
-
590
-		// Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks.
591
-		$parameters=array();
592
-		$reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters);    // Note that $action and $object may have been modified by hook
593
-		if (empty($reshook))
594
-		{
595
-			$ret.='<option value="0"'.($disabled?' disabled="disabled"':'').'>-- '.$langs->trans("SelectAction").' --</option>';
596
-			foreach($arrayofaction as $code => $label)
597
-			{
598
-				$ret.='<option value="'.$code.'"'.($disabled?' disabled="disabled"':'').'>'.$label.'</option>';
599
-			}
600
-		}
601
-		$ret.=$hookmanager->resPrint;
602
-
603
-		$ret.='</select>';
604
-		// Warning: if you set submit button to disabled, post using 'Enter' will no more work if there is no another input submit. So we add a hidden button
605
-		$ret.='<input type="submit" name="confirmmassactioninvisible" style="display: none" tabindex="-1">';	// Hidden button BEFORE so it is the one used when we submit with ENTER.
606
-		$ret.='<input type="submit" disabled name="confirmmassaction" class="button'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionconfirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
607
-		$ret.='</div>';
608
-
609
-		if (! empty($conf->use_javascript_ajax))
610
-		{
611
-			$ret.='<!-- JS CODE TO ENABLE mass action select -->
71
+    // Cache arrays
72
+    public $cache_types_paiements=array();
73
+    public $cache_conditions_paiements=array();
74
+    public $cache_availability=array();
75
+    public $cache_demand_reason=array();
76
+    public $cache_types_fees=array();
77
+    public $cache_vatrates=array();
78
+
79
+
80
+    /**
81
+     * Constructor
82
+     *
83
+     * @param		DoliDB		$db      Database handler
84
+     */
85
+    public function __construct($db)
86
+    {
87
+        $this->db = $db;
88
+    }
89
+
90
+    /**
91
+     * Output key field for an editable field
92
+     *
93
+     * @param   string	$text			Text of label or key to translate
94
+     * @param   string	$htmlname		Name of select field ('edit' prefix will be added)
95
+     * @param   string	$preselected    Value to show/edit (not used in this function)
96
+     * @param	object	$object			Object
97
+     * @param	boolean	$perm			Permission to allow button to edit parameter. Set it to 0 to have a not edited field.
98
+     * @param	string	$typeofdata		Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols', 'datepicker' ('day' do not work, don't know why), 'ckeditor:dolibarr_zzz:width:height:savemethod:1:rows:cols', 'select;xxx[:class]'...)
99
+     * @param	string	$moreparam		More param to add on a href URL.
100
+     * @param   int     $fieldrequired  1 if we want to show field as mandatory using the "fieldrequired" CSS.
101
+     * @param   int     $notabletag     1=Do not output table tags but output a ':', 2=Do not output table tags and no ':', 3=Do not output table tags but output a ' '
102
+     * @param	string	$paramid		Key of parameter for id ('id', 'socid')
103
+     * @return	string					HTML edit field
104
+     */
105
+    function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0, $paramid='id')
106
+    {
107
+        global $conf,$langs;
108
+
109
+        $ret='';
110
+
111
+        // TODO change for compatibility
112
+        if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata))
113
+        {
114
+            if (! empty($perm))
115
+            {
116
+                $tmp=explode(':',$typeofdata);
117
+                $ret.= '<div class="editkey_'.$tmp[0].(! empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
118
+                if ($fieldrequired) $ret.='<span class="fieldrequired">';
119
+                $ret.= $langs->trans($text);
120
+                if ($fieldrequired) $ret.='</span>';
121
+                $ret.= '</div>'."\n";
122
+            }
123
+            else
124
+            {
125
+                if ($fieldrequired) $ret.='<span class="fieldrequired">';
126
+                $ret.= $langs->trans($text);
127
+                if ($fieldrequired) $ret.='</span>';
128
+            }
129
+        }
130
+        else
131
+        {
132
+            if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
133
+            if ($fieldrequired) $ret.='<span class="fieldrequired">';
134
+            $ret.=$langs->trans($text);
135
+            if ($fieldrequired) $ret.='</span>';
136
+            if (! empty($notabletag)) $ret.=' ';
137
+            if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
138
+            if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<td align="right">';
139
+            if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
140
+            if (! empty($notabletag) && $notabletag == 1) $ret.=' : ';
141
+            if (! empty($notabletag) && $notabletag == 3) $ret.=' ';
142
+            if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
143
+            if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</tr></table>';
144
+        }
145
+
146
+        return $ret;
147
+    }
148
+
149
+    /**
150
+     * Output value of a field for an editable field
151
+     *
152
+     * @param	string	$text			Text of label (not used in this function)
153
+     * @param	string	$htmlname		Name of select field
154
+     * @param	string	$value			Value to show/edit
155
+     * @param	object	$object			Object
156
+     * @param	boolean	$perm			Permission to allow button to edit parameter
157
+     * @param	string	$typeofdata		Type of data ('string' by default, 'email', 'amount:99', 'numeric:99', 'text' or 'textarea:rows:cols%', 'datepicker' ('day' do not work, don't know why), 'dayhour' or 'datepickerhour', 'ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols', 'select:xxx'...)
158
+     * @param	string	$editvalue		When in edit mode, use this value as $value instead of value (for example, you can provide here a formated price instead of value). Use '' to use same than $value
159
+     * @param	object	$extObject		External object
160
+     * @param	mixed	$custommsg		String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
161
+     * @param	string	$moreparam		More param to add on the form action href URL
162
+     * @param   int     $notabletag     Do no output table tags
163
+     * @param	string	$formatfunc		Call a specific function to output field
164
+     * @param	string	$paramid		Key of parameter for id ('id', 'socid')
165
+     * @return  string					HTML edit field
166
+     */
167
+    function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0, $formatfunc='', $paramid='id')
168
+    {
169
+        global $conf,$langs,$db;
170
+
171
+        $ret='';
172
+
173
+        // Check parameters
174
+        if (empty($typeofdata)) return 'ErrorBadParameter';
175
+
176
+        // When option to edit inline is activated
177
+        if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker
178
+        {
179
+            $ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
180
+        }
181
+        else
182
+        {
183
+            if (GETPOST('action','aZ09') == 'edit'.$htmlname)
184
+            {
185
+                $ret.="\n";
186
+                $ret.='<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam?'?'.$moreparam:'').'">';
187
+                $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
188
+                $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
189
+                $ret.='<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
190
+                if (empty($notabletag)) $ret.='<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
191
+                if (empty($notabletag)) $ret.='<tr><td>';
192
+                if (preg_match('/^(string|email)/',$typeofdata))
193
+                {
194
+                    $tmp=explode(':',$typeofdata);
195
+                    $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue?$editvalue:$value).'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
196
+                }
197
+                else if (preg_match('/^(numeric|amount)/',$typeofdata))
198
+                {
199
+                    $tmp=explode(':',$typeofdata);
200
+                    $valuetoshow=price2num($editvalue?$editvalue:$value);
201
+                    $ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow!=''?price($valuetoshow):'').'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
202
+                }
203
+                else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))
204
+                {
205
+                    $tmp=explode(':',$typeofdata);
206
+                    $cols=$tmp[2];
207
+                    $morealt='';
208
+                    if (preg_match('/%/',$cols))
209
+                    {
210
+                        $morealt=' style="width: '.$cols.'"';
211
+                        $cols='';
212
+                    }
213
+
214
+                    $valuetoshow = ($editvalue?$editvalue:$value);
215
+
216
+                    $ret.='<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1]?$tmp[1]:'20').'"'.($cols?' cols="'.$cols.'"':'class="quatrevingtpercent"').$morealt.'">';
217
+                    $ret.=dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
218
+                    $ret.='</textarea>';
219
+                }
220
+                else if ($typeofdata == 'day' || $typeofdata == 'datepicker')
221
+                {
222
+                    $ret.=$this->selectDate($value,$htmlname,0,0,1,'form'.$htmlname,1,0);
223
+                }
224
+                else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
225
+                {
226
+                    $ret.=$this->selectDate($value,$htmlname,1,1,1,'form'.$htmlname,1,0);
227
+                }
228
+                else if (preg_match('/^select;/',$typeofdata))
229
+                {
230
+                        $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
231
+                        foreach($arraydata as $val)
232
+                        {
233
+                            $tmp=explode(':',$val);
234
+                            $arraylist[$tmp[0]]=$tmp[1];
235
+                        }
236
+                        $ret.=$this->selectarray($htmlname,$arraylist,$value);
237
+                }
238
+                else if (preg_match('/^ckeditor/',$typeofdata))
239
+                {
240
+                    $tmp=explode(':',$typeofdata);		// Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols
241
+                    require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
242
+                    $doleditor=new DolEditor($htmlname, ($editvalue?$editvalue:$value), ($tmp[2]?$tmp[2]:''), ($tmp[3]?$tmp[3]:'100'), ($tmp[1]?$tmp[1]:'dolibarr_notes'), 'In', ($tmp[5]?$tmp[5]:0), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100'));
243
+                    $ret.=$doleditor->Create(1);
244
+                }
245
+                if (empty($notabletag)) $ret.='</td>';
246
+
247
+                if (empty($notabletag)) $ret.='<td align="left">';
248
+                //else $ret.='<div class="clearboth"></div>';
249
+                    $ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="modify" value="'.$langs->trans("Modify").'">';
250
+                    if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='<br>'."\n";
251
+                    $ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
252
+                    if (empty($notabletag)) $ret.='</td>';
253
+
254
+                    if (empty($notabletag)) $ret.='</tr></table>'."\n";
255
+                $ret.='</form>'."\n";
256
+            }
257
+            else
258
+            {
259
+                if (preg_match('/^(email)/',$typeofdata))              $ret.=dol_print_email($value,0,0,0,0,1);
260
+                elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');
261
+                elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))  $ret.=dol_htmlentitiesbr($value);
262
+                elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');
263
+                elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour');
264
+                else if (preg_match('/^select;/',$typeofdata))
265
+                {
266
+                    $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
267
+                    foreach($arraydata as $val)
268
+                    {
269
+                        $tmp=explode(':',$val);
270
+                        $arraylist[$tmp[0]]=$tmp[1];
271
+                    }
272
+                    $ret.=$arraylist[$value];
273
+                }
274
+                else if (preg_match('/^ckeditor/',$typeofdata))
275
+                {
276
+                    $tmpcontent=dol_htmlentitiesbr($value);
277
+                    if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
278
+                    {
279
+                        $firstline=preg_replace('/<br>.*/','',$tmpcontent);
280
+                        $firstline=preg_replace('/[\n\r].*/','',$firstline);
281
+                        $tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');
282
+                    }
283
+                    $ret.=$tmpcontent;
284
+                }
285
+                else $ret.=$value;
286
+
287
+                if ($formatfunc && method_exists($object, $formatfunc))
288
+                {
289
+                    $ret=$object->$formatfunc($ret);
290
+                }
291
+            }
292
+        }
293
+        return $ret;
294
+    }
295
+
296
+    /**
297
+     * Output edit in place form
298
+     *
299
+     * @param	object	$object			Object
300
+     * @param	string	$value			Value to show/edit
301
+     * @param	string	$htmlname		DIV ID (field name)
302
+     * @param	int		$condition		Condition to edit
303
+     * @param	string	$inputType		Type of input ('string', 'numeric', 'datepicker' ('day' do not work, don't know why), 'textarea:rows:cols', 'ckeditor:dolibarr_zzz:width:height:?:1:rows:cols', 'select:xxx')
304
+     * @param	string	$editvalue		When in edit mode, use this value as $value instead of value
305
+     * @param	object	$extObject		External object
306
+     * @param	mixed	$custommsg		String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
307
+     * @return	string   		      	HTML edit in place
308
+     */
309
+    private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)
310
+    {
311
+        global $conf;
312
+
313
+        $out='';
314
+
315
+        // Check parameters
316
+        if (preg_match('/^text/',$inputType)) $value = dol_nl2br($value);
317
+        else if (preg_match('/^numeric/',$inputType)) $value = price($value);
318
+        else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');
319
+
320
+        if ($condition)
321
+        {
322
+            $element		= false;
323
+            $table_element	= false;
324
+            $fk_element		= false;
325
+            $loadmethod		= false;
326
+            $savemethod		= false;
327
+            $ext_element	= false;
328
+            $button_only	= false;
329
+            $inputOption    = '';
330
+
331
+            if (is_object($object))
332
+            {
333
+                $element = $object->element;
334
+                $table_element = $object->table_element;
335
+                $fk_element = $object->id;
336
+            }
337
+
338
+            if (is_object($extObject))
339
+            {
340
+                $ext_element = $extObject->element;
341
+            }
342
+
343
+            if (preg_match('/^(string|email|numeric)/',$inputType))
344
+            {
345
+                $tmp=explode(':',$inputType);
346
+                $inputType=$tmp[0];
347
+                if (! empty($tmp[1])) $inputOption=$tmp[1];
348
+                if (! empty($tmp[2])) $savemethod=$tmp[2];
349
+                $out.= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
350
+            }
351
+            else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))
352
+            {
353
+                $tmp=explode(':',$inputType);
354
+                $inputType=$tmp[0];
355
+                if (! empty($tmp[1])) $inputOption=$tmp[1];
356
+                if (! empty($tmp[2])) $savemethod=$tmp[2];
357
+
358
+                $out.= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
359
+            }
360
+            else if (preg_match('/^(select|autocomplete)/',$inputType))
361
+            {
362
+                $tmp=explode(':',$inputType);
363
+                $inputType=$tmp[0]; $loadmethod=$tmp[1];
364
+                if (! empty($tmp[2])) $savemethod=$tmp[2];
365
+                if (! empty($tmp[3])) $button_only=true;
366
+            }
367
+            else if (preg_match('/^textarea/',$inputType))
368
+            {
369
+                $tmp=explode(':',$inputType);
370
+                $inputType=$tmp[0];
371
+                $rows=(empty($tmp[1])?'8':$tmp[1]);
372
+                $cols=(empty($tmp[2])?'80':$tmp[2]);
373
+            }
374
+            else if (preg_match('/^ckeditor/',$inputType))
375
+            {
376
+                $tmp=explode(':',$inputType);
377
+                $inputType=$tmp[0]; $toolbar=$tmp[1];
378
+                if (! empty($tmp[2])) $width=$tmp[2];
379
+                if (! empty($tmp[3])) $heigth=$tmp[3];
380
+                if (! empty($tmp[4])) $savemethod=$tmp[4];
381
+
382
+                if (! empty($conf->fckeditor->enabled))
383
+                {
384
+                    $out.= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
385
+                }
386
+                else
387
+                {
388
+                    $inputType = 'textarea';
389
+                }
390
+            }
391
+
392
+            $out.= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
393
+            $out.= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
394
+            $out.= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
395
+            $out.= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
396
+            if (! empty($savemethod))	$out.= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
397
+            if (! empty($ext_element))	$out.= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
398
+            if (! empty($custommsg))
399
+            {
400
+                if (is_array($custommsg))
401
+                {
402
+                    if (!empty($custommsg['success']))
403
+                        $out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
404
+                    if (!empty($custommsg['error']))
405
+                        $out.= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
406
+                }
407
+                else
408
+                    $out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
409
+            }
410
+            if ($inputType == 'textarea') {
411
+                $out.= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
412
+                $out.= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
413
+            }
414
+            $out.= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
415
+            $out.= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(! empty($editvalue) ? $editvalue : $value).'</span>'."\n";
416
+        }
417
+        else
418
+        {
419
+            $out = $value;
420
+        }
421
+
422
+        return $out;
423
+    }
424
+
425
+    /**
426
+     *	Show a text and picto with tooltip on text or picto.
427
+     *  Can be called by an instancied $form->textwithtooltip or by a static call Form::textwithtooltip
428
+     *
429
+     *	@param	string		$text				Text to show
430
+     *	@param	string		$htmltext			HTML content of tooltip. Must be HTML/UTF8 encoded.
431
+     *	@param	int			$tooltipon			1=tooltip on text, 2=tooltip on image, 3=tooltip sur les 2
432
+     *	@param	int			$direction			-1=image is before, 0=no image, 1=image is after
433
+     *	@param	string		$img				Html code for image (use img_xxx() function to get it)
434
+     *	@param	string		$extracss			Add a CSS style to td tags
435
+     *	@param	int			$notabs				0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
436
+     *	@param	string		$incbefore			Include code before the text
437
+     *	@param	int			$noencodehtmltext	Do not encode into html entity the htmltext
438
+     *  @param  string      $tooltiptrigger		''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
439
+     *  @param	int			$forcenowrap		Force no wrap between text and picto (works with notabs=2 only)
440
+     *	@return	string							Code html du tooltip (texte+picto)
441
+     *	@see	Use function textwithpicto if you can.
442
+     *  TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip
443
+     */
444
+    function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='', $forcenowrap=0)
445
+    {
446
+        global $conf;
447
+
448
+        if ($incbefore) $text = $incbefore.$text;
449
+        if (! $htmltext) return $text;
450
+
451
+        $tag='td';
452
+        if ($notabs == 2) $tag='div';
453
+        if ($notabs == 3) $tag='span';
454
+        // Sanitize tooltip
455
+        $htmltext=str_replace("\\","\\\\",$htmltext);
456
+        $htmltext=str_replace("\r","",$htmltext);
457
+        $htmltext=str_replace("\n","",$htmltext);
458
+
459
+        $extrastyle='';
460
+        if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; }
461
+        if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; }
462
+
463
+        $classfortooltip='classfortooltip';
464
+
465
+        $s='';$textfordialog='';
466
+
467
+        if ($tooltiptrigger == '')
468
+        {
469
+            $htmltext=str_replace('"',"&quot;",$htmltext);
470
+        }
471
+        else
472
+        {
473
+            $classfortooltip='classfortooltiponclick';
474
+            $textfordialog.='<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
475
+        }
476
+        if ($tooltipon == 2 || $tooltipon == 3)
477
+        {
478
+            $paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"';
479
+            if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip
480
+            else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"';
481
+        }
482
+        else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
483
+        if ($tooltipon == 1 || $tooltipon == 3)
484
+        {
485
+            $paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" ';
486
+            if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip
487
+            else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"';
488
+        }
489
+        else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
490
+        if (empty($notabs)) $s.='<table class="nobordernopadding" summary=""><tr style="height: auto;">';
491
+        elseif ($notabs == 2) $s.='<div class="inline-block'.($forcenowrap?' nowrap':'').'">';
492
+        // Define value if value is before
493
+        if ($direction < 0) {
494
+            $s.='<'.$tag.$paramfortooltipimg;
495
+            if ($tag == 'td') {
496
+                $s .= ' valign="top" width="14"';
497
+            }
498
+            $s.= '>'.$textfordialog.$img.'</'.$tag.'>';
499
+        }
500
+        // Use another method to help avoid having a space in value in order to use this value with jquery
501
+        // Define label
502
+        if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
503
+        // Define value if value is after
504
+        if ($direction > 0) {
505
+            $s.='<'.$tag.$paramfortooltipimg;
506
+            if ($tag == 'td') $s .= ' valign="middle" width="14"';
507
+            $s.= '>'.$textfordialog.$img.'</'.$tag.'>';
508
+        }
509
+        if (empty($notabs)) $s.='</tr></table>';
510
+        elseif ($notabs == 2) $s.='</div>';
511
+
512
+        return $s;
513
+    }
514
+
515
+    /**
516
+     *	Show a text with a picto and a tooltip on picto
517
+     *
518
+     *	@param	string	$text				Text to show
519
+     *	@param  string	$htmltext	     	Content of tooltip
520
+     *	@param	int		$direction			1=Icon is after text, -1=Icon is before text, 0=no icon
521
+     * 	@param	string	$type				Type of picto ('info', 'help', 'warning', 'superadmin', 'mypicto@mymodule', ...) or image filepath
522
+     *  @param  string	$extracss           Add a CSS style to td, div or span tag
523
+     *  @param  int		$noencodehtmltext   Do not encode into html entity the htmltext
524
+     *  @param	int		$notabs				0=Include table and tr tags, 1=Do not include table and tr tags, 2=use div, 3=use span
525
+     *  @param  string  $tooltiptrigger     ''=Tooltip on hover, 'abc'=Tooltip on click (abc is a unique key)
526
+     *  @param	int		$forcenowrap		Force no wrap between text and picto (works with notabs=2 only)
527
+     * 	@return	string						HTML code of text, picto, tooltip
528
+     */
529
+    function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='', $forcenowrap=0)
530
+    {
531
+        global $conf, $langs;
532
+
533
+        $alt = '';
534
+        if ($tooltiptrigger) $alt=$langs->transnoentitiesnoconv("ClickToShowHelp");
535
+
536
+        //For backwards compatibility
537
+        if ($type == '0') $type = 'info';
538
+        elseif ($type == '1') $type = 'help';
539
+
540
+        // If info or help with no javascript, show only text
541
+        if (empty($conf->use_javascript_ajax))
542
+        {
543
+            if ($type == 'info' || $type == 'help')	return $text;
544
+            else
545
+            {
546
+                $alt = $htmltext;
547
+                $htmltext = '';
548
+            }
549
+        }
550
+
551
+        // If info or help with smartphone, show only text (tooltip hover can't works)
552
+        if (! empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))
553
+        {
554
+            if ($type == 'info' || $type == 'help') return $text;
555
+        }
556
+        // If info or help with smartphone, show only text (tooltip on lick does not works with dialog on smaprtphone)
557
+        if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
558
+        {
559
+            if ($type == 'info' || $type == 'help') return $text;
560
+        }
561
+
562
+        if ($type == 'info') $img = img_help(0, $alt);
563
+        elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
564
+        elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');
565
+        elseif ($type == 'admin') $img = img_picto($alt, 'star');
566
+        elseif ($type == 'warning') $img = img_warning($alt);
567
+        else $img = img_picto($alt, $type);
568
+
569
+        return $this->textwithtooltip($text, $htmltext, (($tooltiptrigger && ! $img)?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
570
+    }
571
+
572
+    /**
573
+     * Generate select HTML to choose massaction
574
+     *
575
+     * @param	string	$selected		Value auto selected when at least one record is selected. Not a preselected value. Use '0' by default.
576
+     * @param	int		$arrayofaction	array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
577
+     * @param   int     $alwaysvisible  1=select button always visible
578
+     * @return	string					Select list
579
+     */
580
+    function selectMassAction($selected, $arrayofaction, $alwaysvisible=0)
581
+    {
582
+        global $conf,$langs,$hookmanager;
583
+
584
+        if (count($arrayofaction) == 0) return;
585
+
586
+        $disabled=0;
587
+        $ret='<div class="centpercent center">';
588
+        $ret.='<select class="flat'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionselect" name="massaction"'.($disabled?' disabled="disabled"':'').'>';
589
+
590
+        // Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks.
591
+        $parameters=array();
592
+        $reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters);    // Note that $action and $object may have been modified by hook
593
+        if (empty($reshook))
594
+        {
595
+            $ret.='<option value="0"'.($disabled?' disabled="disabled"':'').'>-- '.$langs->trans("SelectAction").' --</option>';
596
+            foreach($arrayofaction as $code => $label)
597
+            {
598
+                $ret.='<option value="'.$code.'"'.($disabled?' disabled="disabled"':'').'>'.$label.'</option>';
599
+            }
600
+        }
601
+        $ret.=$hookmanager->resPrint;
602
+
603
+        $ret.='</select>';
604
+        // Warning: if you set submit button to disabled, post using 'Enter' will no more work if there is no another input submit. So we add a hidden button
605
+        $ret.='<input type="submit" name="confirmmassactioninvisible" style="display: none" tabindex="-1">';	// Hidden button BEFORE so it is the one used when we submit with ENTER.
606
+        $ret.='<input type="submit" disabled name="confirmmassaction" class="button'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionconfirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
607
+        $ret.='</div>';
608
+
609
+        if (! empty($conf->use_javascript_ajax))
610
+        {
611
+            $ret.='<!-- JS CODE TO ENABLE mass action select -->
612 612
     		<script type="text/javascript">
613 613
         		function initCheckForSelect(mode)	/* mode is 0 during init of page or click all, 1 when we click on 1 checkbox */
614 614
         		{
@@ -657,1266 +657,1266 @@  discard block
 block discarded – undo
657 657
         	});
658 658
     		</script>
659 659
         	';
660
-		}
660
+        }
661 661
 
662
-		return $ret;
663
-	}
662
+        return $ret;
663
+    }
664 664
 
665 665
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
666
-	/**
667
-	 *  Return combo list of activated countries, into language of user
668
-	 *
669
-	 *  @param	string	$selected       	Id or Code or Label of preselected country
670
-	 *  @param  string	$htmlname       	Name of html select object
671
-	 *  @param  string	$htmloption     	Options html on select object
672
-	 *  @param	integer	$maxlength			Max length for labels (0=no limit)
673
-	 *  @param	string	$morecss			More css class
674
-	 *  @param	string	$usecodeaskey		''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
675
-	 *  @param	int		$showempty			Show empty choice
676
-	 *  @param	int		$disablefavorites	1=Disable favorites,
677
-	 *  @param	int		$addspecialentries	1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
678
-	 *  @return string           			HTML string with select
679
-	 */
680
-	function select_country($selected='', $htmlname='country_id', $htmloption='', $maxlength=0, $morecss='minwidth300', $usecodeaskey='', $showempty=1, $disablefavorites=0, $addspecialentries=0)
681
-	{
666
+    /**
667
+     *  Return combo list of activated countries, into language of user
668
+     *
669
+     *  @param	string	$selected       	Id or Code or Label of preselected country
670
+     *  @param  string	$htmlname       	Name of html select object
671
+     *  @param  string	$htmloption     	Options html on select object
672
+     *  @param	integer	$maxlength			Max length for labels (0=no limit)
673
+     *  @param	string	$morecss			More css class
674
+     *  @param	string	$usecodeaskey		''=Use id as key (default), 'code3'=Use code on 3 alpha as key, 'code2"=Use code on 2 alpha as key
675
+     *  @param	int		$showempty			Show empty choice
676
+     *  @param	int		$disablefavorites	1=Disable favorites,
677
+     *  @param	int		$addspecialentries	1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
678
+     *  @return string           			HTML string with select
679
+     */
680
+    function select_country($selected='', $htmlname='country_id', $htmloption='', $maxlength=0, $morecss='minwidth300', $usecodeaskey='', $showempty=1, $disablefavorites=0, $addspecialentries=0)
681
+    {
682 682
         // phpcs:enable
683
-		global $conf,$langs,$mysoc;
684
-
685
-		$langs->load("dict");
686
-
687
-		$out='';
688
-		$countryArray=array();
689
-		$favorite=array();
690
-		$label=array();
691
-		$atleastonefavorite=0;
692
-
693
-		$sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
694
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_country";
695
-		$sql.= " WHERE active > 0";
696
-		//$sql.= " ORDER BY code ASC";
697
-
698
-		dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
699
-		$resql=$this->db->query($sql);
700
-		if ($resql)
701
-		{
702
-			$out.= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" '.$htmloption.'>';
703
-			$num = $this->db->num_rows($resql);
704
-			$i = 0;
705
-			if ($num)
706
-			{
707
-				$foundselected=false;
708
-
709
-				while ($i < $num)
710
-				{
711
-					$obj = $this->db->fetch_object($resql);
712
-					$countryArray[$i]['rowid'] 		= $obj->rowid;
713
-					$countryArray[$i]['code_iso'] 	= $obj->code_iso;
714
-					$countryArray[$i]['code_iso3'] 	= $obj->code_iso3;
715
-					$countryArray[$i]['label']		= ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso)!="Country".$obj->code_iso?$langs->transnoentitiesnoconv("Country".$obj->code_iso):($obj->label!='-'?$obj->label:''));
716
-					$countryArray[$i]['favorite']   = $obj->favorite;
717
-					$favorite[$i]					= $obj->favorite;
718
-					$label[$i] = dol_string_unaccent($countryArray[$i]['label']);
719
-					$i++;
720
-				}
721
-
722
-				if (empty($disablefavorites)) array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
723
-				else $countryArray = dol_sort_array($countryArray, 'label');
724
-
725
-				if ($showempty)
726
-				{
727
-					$out.='<option value="">&nbsp;</option>'."\n";
728
-				}
729
-
730
-				if ($addspecialentries)	// Add dedicated entries for groups of countries
731
-				{
732
-					//if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
733
-					$out.= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
734
-					$out.= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
735
-					if ($mysoc->isInEEC()) $out.= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
736
-					$out.= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
737
-					$out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
738
-				}
739
-
740
-				foreach ($countryArray as $row)
741
-				{
742
-					//if (empty($showempty) && empty($row['rowid'])) continue;
743
-					if (empty($row['rowid'])) continue;
744
-
745
-					if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) $atleastonefavorite++;
746
-					if (empty($row['favorite']) && $atleastonefavorite)
747
-					{
748
-						$atleastonefavorite=0;
749
-						$out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
750
-					}
751
-					if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) )
752
-					{
753
-						$foundselected=true;
754
-						$out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'" selected>';
755
-					}
756
-					else
757
-					{
758
-						$out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'">';
759
-					}
760
-					if ($row['label']) $out.= dol_trunc($row['label'],$maxlength,'middle');
761
-					else $out.= '&nbsp;';
762
-					if ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';
763
-					$out.= '</option>';
764
-				}
765
-			}
766
-			$out.= '</select>';
767
-		}
768
-		else
769
-		{
770
-			dol_print_error($this->db);
771
-		}
772
-
773
-		// Make select dynamic
774
-		include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
775
-		$out .= ajax_combobox('select'.$htmlname);
776
-
777
-		return $out;
778
-	}
683
+        global $conf,$langs,$mysoc;
684
+
685
+        $langs->load("dict");
686
+
687
+        $out='';
688
+        $countryArray=array();
689
+        $favorite=array();
690
+        $label=array();
691
+        $atleastonefavorite=0;
692
+
693
+        $sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
694
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_country";
695
+        $sql.= " WHERE active > 0";
696
+        //$sql.= " ORDER BY code ASC";
697
+
698
+        dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
699
+        $resql=$this->db->query($sql);
700
+        if ($resql)
701
+        {
702
+            $out.= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" '.$htmloption.'>';
703
+            $num = $this->db->num_rows($resql);
704
+            $i = 0;
705
+            if ($num)
706
+            {
707
+                $foundselected=false;
708
+
709
+                while ($i < $num)
710
+                {
711
+                    $obj = $this->db->fetch_object($resql);
712
+                    $countryArray[$i]['rowid'] 		= $obj->rowid;
713
+                    $countryArray[$i]['code_iso'] 	= $obj->code_iso;
714
+                    $countryArray[$i]['code_iso3'] 	= $obj->code_iso3;
715
+                    $countryArray[$i]['label']		= ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso)!="Country".$obj->code_iso?$langs->transnoentitiesnoconv("Country".$obj->code_iso):($obj->label!='-'?$obj->label:''));
716
+                    $countryArray[$i]['favorite']   = $obj->favorite;
717
+                    $favorite[$i]					= $obj->favorite;
718
+                    $label[$i] = dol_string_unaccent($countryArray[$i]['label']);
719
+                    $i++;
720
+                }
779 721
 
780
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
781
-	/**
782
-	 *  Return select list of incoterms
783
-	 *
784
-	 *  @param	string	$selected       		Id or Code of preselected incoterm
785
-	 *  @param	string	$location_incoterms     Value of input location
786
-	 *  @param	string	$page       			Defined the form action
787
-	 *  @param  string	$htmlname       		Name of html select object
788
-	 *  @param  string	$htmloption     		Options html on select object
789
-	 * 	@param	int		$forcecombo				Force to load all values and output a standard combobox (with no beautification)
790
-	 *  @param	array	$events					Event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
791
-	 *  @return string           				HTML string with select and input
792
-	 */
793
-	function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array())
794
-	{
795
-        // phpcs:enable
796
-		global $conf,$langs;
797
-
798
-		$langs->load("dict");
799
-
800
-		$out='';
801
-		$incotermArray=array();
802
-
803
-		$sql = "SELECT rowid, code";
804
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms";
805
-		$sql.= " WHERE active > 0";
806
-		$sql.= " ORDER BY code ASC";
807
-
808
-		dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
809
-		$resql=$this->db->query($sql);
810
-		if ($resql)
811
-		{
812
-			if ($conf->use_javascript_ajax && ! $forcecombo)
813
-			{
814
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
815
-				$out .= ajax_combobox($htmlname, $events);
816
-			}
817
-
818
-			if (!empty($page))
819
-			{
820
-				$out .= '<form method="post" action="'.$page.'">';
821
-				$out .= '<input type="hidden" name="action" value="set_incoterms">';
822
-				$out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
823
-			}
824
-
825
-			$out.= '<select id="'.$htmlname.'" class="flat selectincoterm minwidth100imp noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
826
-			$out.= '<option value="0">&nbsp;</option>';
827
-			$num = $this->db->num_rows($resql);
828
-			$i = 0;
829
-			if ($num)
830
-			{
831
-				$foundselected=false;
832
-
833
-				while ($i < $num)
834
-				{
835
-					$obj = $this->db->fetch_object($resql);
836
-					$incotermArray[$i]['rowid'] = $obj->rowid;
837
-					$incotermArray[$i]['code'] = $obj->code;
838
-					$i++;
839
-				}
840
-
841
-				foreach ($incotermArray as $row)
842
-				{
843
-					if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
844
-					{
845
-						$out.= '<option value="'.$row['rowid'].'" selected>';
846
-					}
847
-					else
848
-					{
849
-						$out.= '<option value="'.$row['rowid'].'">';
850
-					}
722
+                if (empty($disablefavorites)) array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
723
+                else $countryArray = dol_sort_array($countryArray, 'label');
851 724
 
852
-					if ($row['code']) $out.= $row['code'];
725
+                if ($showempty)
726
+                {
727
+                    $out.='<option value="">&nbsp;</option>'."\n";
728
+                }
853 729
 
854
-					$out.= '</option>';
855
-				}
856
-			}
857
-			$out.= '</select>';
730
+                if ($addspecialentries)	// Add dedicated entries for groups of countries
731
+                {
732
+                    //if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
733
+                    $out.= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
734
+                    $out.= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
735
+                    if ($mysoc->isInEEC()) $out.= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
736
+                    $out.= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
737
+                    $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
738
+                }
858 739
 
859
-			$out .= '<input id="location_incoterms" class="maxwidth100onsmartphone" name="location_incoterms" value="'.$location_incoterms.'">';
740
+                foreach ($countryArray as $row)
741
+                {
742
+                    //if (empty($showempty) && empty($row['rowid'])) continue;
743
+                    if (empty($row['rowid'])) continue;
860 744
 
861
-			if (!empty($page))
862
-			{
863
-				$out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'"></form>';
864
-			}
865
-		}
866
-		else
867
-		{
868
-			dol_print_error($this->db);
869
-		}
745
+                    if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) $atleastonefavorite++;
746
+                    if (empty($row['favorite']) && $atleastonefavorite)
747
+                    {
748
+                        $atleastonefavorite=0;
749
+                        $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
750
+                    }
751
+                    if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) )
752
+                    {
753
+                        $foundselected=true;
754
+                        $out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'" selected>';
755
+                    }
756
+                    else
757
+                    {
758
+                        $out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'">';
759
+                    }
760
+                    if ($row['label']) $out.= dol_trunc($row['label'],$maxlength,'middle');
761
+                    else $out.= '&nbsp;';
762
+                    if ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';
763
+                    $out.= '</option>';
764
+                }
765
+            }
766
+            $out.= '</select>';
767
+        }
768
+        else
769
+        {
770
+            dol_print_error($this->db);
771
+        }
870 772
 
871
-		return $out;
872
-	}
773
+        // Make select dynamic
774
+        include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
775
+        $out .= ajax_combobox('select'.$htmlname);
873 776
 
874
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
875
-	/**
876
-	 *	Return list of types of lines (product or service)
877
-	 * 	Example: 0=product, 1=service, 9=other (for external module)
878
-	 *
879
-	 *	@param  string	$selected       Preselected type
880
-	 *	@param  string	$htmlname       Name of field in html form
881
-	 * 	@param	int		$showempty		Add an empty field
882
-	 * 	@param	int		$hidetext		Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
883
-	 * 	@param	integer	$forceall		1=Force to show products and services in combo list, whatever are activated modules, 0=No force, 2=Force to show only Products, 3=Force to show only services, -1=Force none (and set hidden field to 'service')
884
-	 *  @return	void
885
-	 */
886
-	function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0)
887
-	{
888
-        // phpcs:enable
889
-		global $db,$langs,$user,$conf;
890
-
891
-		// If product & services are enabled or both disabled.
892
-		if ($forceall == 1 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled))
893
-		|| (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) )
894
-		{
895
-			if (empty($hidetext)) print $langs->trans("Type").': ';
896
-			print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
897
-			if ($showempty)
898
-			{
899
-				print '<option value="-1"';
900
-				if ($selected == -1) print ' selected';
901
-				print '>&nbsp;</option>';
902
-			}
903
-
904
-			print '<option value="0"';
905
-			if (0 == $selected) print ' selected';
906
-			print '>'.$langs->trans("Product");
907
-
908
-			print '<option value="1"';
909
-			if (1 == $selected) print ' selected';
910
-			print '>'.$langs->trans("Service");
911
-
912
-			print '</select>';
913
-			//if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
914
-		}
915
-		if ((empty($forceall) && empty($conf->product->enabled) && ! empty($conf->service->enabled)) || $forceall == 3)
916
-		{
917
-			print $langs->trans("Service");
918
-			print '<input type="hidden" name="'.$htmlname.'" value="1">';
919
-		}
920
-		if ((empty($forceall) && ! empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2)
921
-		{
922
-			print $langs->trans("Product");
923
-			print '<input type="hidden" name="'.$htmlname.'" value="0">';
924
-		}
925
-		if ($forceall < 0)	// This should happened only for contracts when both predefined product and service are disabled.
926
-		{
927
-			print '<input type="hidden" name="'.$htmlname.'" value="1">';	// By default we set on service for contract. If CONTRACT_SUPPORT_PRODUCTS is set, forceall should be 1 not -1
928
-		}
929
-	}
777
+        return $out;
778
+    }
930 779
 
931 780
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
932
-	/**
933
-	 *	Load into cache cache_types_fees, array of types of fees
934
-	 *
935
-	 *	@return     int             Nb of lines loaded, <0 if KO
936
-	 */
937
-	function load_cache_types_fees()
938
-	{
781
+    /**
782
+     *  Return select list of incoterms
783
+     *
784
+     *  @param	string	$selected       		Id or Code of preselected incoterm
785
+     *  @param	string	$location_incoterms     Value of input location
786
+     *  @param	string	$page       			Defined the form action
787
+     *  @param  string	$htmlname       		Name of html select object
788
+     *  @param  string	$htmloption     		Options html on select object
789
+     * 	@param	int		$forcecombo				Force to load all values and output a standard combobox (with no beautification)
790
+     *  @param	array	$events					Event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
791
+     *  @return string           				HTML string with select and input
792
+     */
793
+    function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array())
794
+    {
939 795
         // phpcs:enable
940
-		global $langs;
941
-
942
-		$num = count($this->cache_types_fees);
943
-		if ($num > 0) return 0;    // Cache already loaded
796
+        global $conf,$langs;
944 797
 
945
-		dol_syslog(__METHOD__, LOG_DEBUG);
798
+        $langs->load("dict");
946 799
 
947
-		$langs->load("trips");
800
+        $out='';
801
+        $incotermArray=array();
948 802
 
949
-		$sql = "SELECT c.code, c.label";
950
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
951
-		$sql.= " WHERE active > 0";
803
+        $sql = "SELECT rowid, code";
804
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms";
805
+        $sql.= " WHERE active > 0";
806
+        $sql.= " ORDER BY code ASC";
952 807
 
953
-		$resql=$this->db->query($sql);
954
-		if ($resql)
955
-		{
956
-			$num = $this->db->num_rows($resql);
957
-			$i = 0;
808
+        dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
809
+        $resql=$this->db->query($sql);
810
+        if ($resql)
811
+        {
812
+            if ($conf->use_javascript_ajax && ! $forcecombo)
813
+            {
814
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
815
+                $out .= ajax_combobox($htmlname, $events);
816
+            }
958 817
 
959
-			while ($i < $num)
960
-			{
961
-				$obj = $this->db->fetch_object($resql);
818
+            if (!empty($page))
819
+            {
820
+                $out .= '<form method="post" action="'.$page.'">';
821
+                $out .= '<input type="hidden" name="action" value="set_incoterms">';
822
+                $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
823
+            }
962 824
 
963
-				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
964
-				$label=($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
965
-				$this->cache_types_fees[$obj->code] = $label;
966
-				$i++;
967
-			}
825
+            $out.= '<select id="'.$htmlname.'" class="flat selectincoterm minwidth100imp noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
826
+            $out.= '<option value="0">&nbsp;</option>';
827
+            $num = $this->db->num_rows($resql);
828
+            $i = 0;
829
+            if ($num)
830
+            {
831
+                $foundselected=false;
832
+
833
+                while ($i < $num)
834
+                {
835
+                    $obj = $this->db->fetch_object($resql);
836
+                    $incotermArray[$i]['rowid'] = $obj->rowid;
837
+                    $incotermArray[$i]['code'] = $obj->code;
838
+                    $i++;
839
+                }
968 840
 
969
-			asort($this->cache_types_fees);
841
+                foreach ($incotermArray as $row)
842
+                {
843
+                    if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
844
+                    {
845
+                        $out.= '<option value="'.$row['rowid'].'" selected>';
846
+                    }
847
+                    else
848
+                    {
849
+                        $out.= '<option value="'.$row['rowid'].'">';
850
+                    }
970 851
 
971
-			return $num;
972
-		}
973
-		else
974
-		{
975
-			dol_print_error($this->db);
976
-			return -1;
977
-		}
978
-	}
852
+                    if ($row['code']) $out.= $row['code'];
979 853
 
980
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
981
-	/**
982
-	 *	Return list of types of notes
983
-	 *
984
-	 *	@param	string		$selected		Preselected type
985
-	 *	@param  string		$htmlname		Name of field in form
986
-	 * 	@param	int			$showempty		Add an empty field
987
-	 * 	@return	void
988
-	 */
989
-	function select_type_fees($selected='',$htmlname='type',$showempty=0)
990
-	{
991
-        // phpcs:enable
992
-		global $user, $langs;
854
+                    $out.= '</option>';
855
+                }
856
+            }
857
+            $out.= '</select>';
993 858
 
994
-		dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
859
+            $out .= '<input id="location_incoterms" class="maxwidth100onsmartphone" name="location_incoterms" value="'.$location_incoterms.'">';
995 860
 
996
-		$this->load_cache_types_fees();
861
+            if (!empty($page))
862
+            {
863
+                $out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'"></form>';
864
+            }
865
+        }
866
+        else
867
+        {
868
+            dol_print_error($this->db);
869
+        }
997 870
 
998
-		print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
999
-		if ($showempty)
1000
-		{
1001
-			print '<option value="-1"';
1002
-			if ($selected == -1) print ' selected';
1003
-			print '>&nbsp;</option>';
1004
-		}
871
+        return $out;
872
+    }
1005 873
 
1006
-		foreach($this->cache_types_fees as $key => $value)
1007
-		{
1008
-			print '<option value="'.$key.'"';
1009
-			if ($key == $selected) print ' selected';
1010
-			print '>';
1011
-			print $value;
1012
-			print '</option>';
1013
-		}
874
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
875
+    /**
876
+     *	Return list of types of lines (product or service)
877
+     * 	Example: 0=product, 1=service, 9=other (for external module)
878
+     *
879
+     *	@param  string	$selected       Preselected type
880
+     *	@param  string	$htmlname       Name of field in html form
881
+     * 	@param	int		$showempty		Add an empty field
882
+     * 	@param	int		$hidetext		Do not show label 'Type' before combo box (used only if there is at least 2 choices to select)
883
+     * 	@param	integer	$forceall		1=Force to show products and services in combo list, whatever are activated modules, 0=No force, 2=Force to show only Products, 3=Force to show only services, -1=Force none (and set hidden field to 'service')
884
+     *  @return	void
885
+     */
886
+    function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0)
887
+    {
888
+        // phpcs:enable
889
+        global $db,$langs,$user,$conf;
890
+
891
+        // If product & services are enabled or both disabled.
892
+        if ($forceall == 1 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled))
893
+        || (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) )
894
+        {
895
+            if (empty($hidetext)) print $langs->trans("Type").': ';
896
+            print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
897
+            if ($showempty)
898
+            {
899
+                print '<option value="-1"';
900
+                if ($selected == -1) print ' selected';
901
+                print '>&nbsp;</option>';
902
+            }
1014 903
 
1015
-		print '</select>';
1016
-		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
1017
-	}
904
+            print '<option value="0"';
905
+            if (0 == $selected) print ' selected';
906
+            print '>'.$langs->trans("Product");
1018 907
 
908
+            print '<option value="1"';
909
+            if (1 == $selected) print ' selected';
910
+            print '>'.$langs->trans("Service");
1019 911
 
1020
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1021
-	/**
1022
-	 *  Return HTML code to select a company.
1023
-	 *
1024
-	 *  @param		int			$selected				Preselected products
1025
-	 *  @param		string		$htmlname				Name of HTML select field (must be unique in page)
1026
-	 *  @param		int			$filter					Filter on thirdparty
1027
-	 *  @param		int			$limit					Limit on number of returned lines
1028
-	 *  @param		array		$ajaxoptions			Options for ajax_autocompleter
1029
-	 * 	@param		int			$forcecombo				Force to load all values and output a standard combobox (with no beautification)
1030
-	 *  @return		string								Return select box for thirdparty.
1031
-	 *  @deprecated	3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0)
1032
-	 */
1033
-	function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0)
1034
-	{
1035
-        // phpcs:enable
1036
-   		return $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0, $limit);
1037
-	}
912
+            print '</select>';
913
+            //if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
914
+        }
915
+        if ((empty($forceall) && empty($conf->product->enabled) && ! empty($conf->service->enabled)) || $forceall == 3)
916
+        {
917
+            print $langs->trans("Service");
918
+            print '<input type="hidden" name="'.$htmlname.'" value="1">';
919
+        }
920
+        if ((empty($forceall) && ! empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2)
921
+        {
922
+            print $langs->trans("Product");
923
+            print '<input type="hidden" name="'.$htmlname.'" value="0">';
924
+        }
925
+        if ($forceall < 0)	// This should happened only for contracts when both predefined product and service are disabled.
926
+        {
927
+            print '<input type="hidden" name="'.$htmlname.'" value="1">';	// By default we set on service for contract. If CONTRACT_SUPPORT_PRODUCTS is set, forceall should be 1 not -1
928
+        }
929
+    }
1038 930
 
1039 931
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1040
-	/**
1041
-	 *  Output html form to select a third party
1042
-	 *
1043
-	 *	@param	string	$selected       		Preselected type
1044
-	 *	@param  string	$htmlname       		Name of field in form
1045
-	 *  @param  string	$filter         		optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)')
1046
-	 *	@param	string	$showempty				Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
1047
-	 * 	@param	int		$showtype				Show third party type in combolist (customer, prospect or supplier)
1048
-	 * 	@param	int		$forcecombo				Force to load all values and output a standard combobox (with no beautification)
1049
-	 *  @param	array	$events					Ajax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1050
-	 *	@param	int		$limit					Maximum number of elements
1051
-	 *  @param	string	$morecss				Add more css styles to the SELECT component
1052
-	 *	@param  string	$moreparam      		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1053
-	 *	@param	string	$selected_input_value	Value of preselected input text (for use with ajax)
1054
-	 *  @param	int		$hidelabel				Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
1055
-	 *  @param	array	$ajaxoptions			Options for ajax_autocompleter
1056
-	 * 	@param  bool	$multiple				add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
1057
-	 * 	@return	string							HTML string with select box for thirdparty.
1058
-	 */
1059
-	function select_company($selected='', $htmlname='socid', $filter='', $showempty='', $showtype=0, $forcecombo=0, $events=array(), $limit=0, $morecss='minwidth100', $moreparam='', $selected_input_value='', $hidelabel=1, $ajaxoptions=array(), $multiple=false)
1060
-	{
932
+    /**
933
+     *	Load into cache cache_types_fees, array of types of fees
934
+     *
935
+     *	@return     int             Nb of lines loaded, <0 if KO
936
+     */
937
+    function load_cache_types_fees()
938
+    {
1061 939
         // phpcs:enable
1062
-		global $conf,$user,$langs;
1063
-
1064
-		$out='';
1065
-
1066
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo)
1067
-		{
1068
-			// No immediate load of all database
1069
-			$placeholder='';
1070
-			if ($selected && empty($selected_input_value))
1071
-			{
1072
-				require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1073
-				$societetmp = new Societe($this->db);
1074
-				$societetmp->fetch($selected);
1075
-				$selected_input_value=$societetmp->name;
1076
-				unset($societetmp);
1077
-			}
1078
-			// mode 1
1079
-			$urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:'');
1080
-			$out.=  ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1081
-			$out.='<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
1082
-			if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
1083
-			else if ($hidelabel > 1) {
1084
-				$placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
1085
-				if ($hidelabel == 2) {
1086
-					$out.=  img_picto($langs->trans("Search"), 'search');
1087
-				}
1088
-			}
1089
-			$out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
1090
-			if ($hidelabel == 3) {
1091
-				$out.=  img_picto($langs->trans("Search"), 'search');
1092
-			}
1093
-		}
1094
-		else
1095
-		{
1096
-			// Immediate load of all database
1097
-			$out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple);
1098
-		}
1099
-
1100
-		return $out;
1101
-	}
940
+        global $langs;
1102 941
 
1103
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1104
-	/**
1105
-	 *  Output html form to select a third party.
1106
-	 *  Note, you must use the select_company to get the component to select a third party. This function must only be called by select_company.
1107
-	 *
1108
-	 *	@param	string	$selected       Preselected type
1109
-	 *	@param  string	$htmlname       Name of field in form
1110
-	 *  @param  string	$filter         Optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')
1111
-	 *	@param	string	$showempty		Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
1112
-	 * 	@param	int		$showtype		Show third party type in combolist (customer, prospect or supplier)
1113
-	 * 	@param	int		$forcecombo		Force to use standard HTML select component without beautification
1114
-	 *  @param	array	$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1115
-	 *  @param	string	$filterkey		Filter on key value
1116
-	 *  @param	int		$outputmode		0=HTML select string, 1=Array
1117
-	 *  @param	int		$limit			Limit number of answers
1118
-	 *  @param	string	$morecss		Add more css styles to the SELECT component
1119
-	 *	@param  string	$moreparam      Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1120
-	 *	@param  bool	$multiple       add [] in the name of element and add 'multiple' attribut
1121
-	 * 	@return	string					HTML string with
1122
-	 */
1123
-	function select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='', $multiple=false)
1124
-	{
1125
-        // phpcs:enable
1126
-		global $conf,$user,$langs;
1127
-
1128
-		$out='';
1129
-		$num=0;
1130
-		$outarray=array();
1131
-
1132
-		if ($selected === '') $selected = array();
1133
-		else if (!is_array($selected)) $selected = array($selected);
1134
-
1135
-		// Clean $filter that may contains sql conditions so sql code
1136
-		if (function_exists('testSqlAndScriptInject')) {
1137
-			if (testSqlAndScriptInject($filter, 3)>0) {
1138
-				$filter ='';
1139
-			}
1140
-		}
1141
-
1142
-		// On recherche les societes
1143
-		$sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
1144
-
1145
-		if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1146
-			$sql .= " ,s.address, s.zip, s.town";
1147
-		 	$sql .= " , dictp.code as country_code";
1148
-		}
1149
-
1150
-		$sql.= " FROM (".MAIN_DB_PREFIX ."societe as s";
1151
-		if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1152
-		$sql.= " )";
1153
-		if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1154
-			$sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid=s.fk_pays";
1155
-		}
1156
-		$sql.= " WHERE s.entity IN (".getEntity('societe').")";
1157
-		if (! empty($user->socid)) $sql.= " AND s.rowid = ".$user->socid;
1158
-		if ($filter) $sql.= " AND (".$filter.")";
1159
-		if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
1160
-		if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0";
1161
-		// Add criteria
1162
-		if ($filterkey && $filterkey != '')
1163
-		{
1164
-			$sql.=" AND (";
1165
-			$prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
1166
-			// For natural search
1167
-			$scrit = explode(' ', $filterkey);
1168
-			$i=0;
1169
-			if (count($scrit) > 1) $sql.="(";
1170
-			foreach ($scrit as $crit) {
1171
-				if ($i > 0) $sql.=" AND ";
1172
-				$sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
1173
-				$i++;
1174
-			}
1175
-			if (count($scrit) > 1) $sql.=")";
1176
-			if (! empty($conf->barcode->enabled))
1177
-			{
1178
-				$sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1179
-			}
1180
-			$sql.= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1181
-			$sql.=")";
1182
-		}
1183
-		$sql.=$this->db->order("nom","ASC");
1184
-		$sql.=$this->db->plimit($limit, 0);
1185
-
1186
-		// Build output string
1187
-		dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
1188
-		$resql=$this->db->query($sql);
1189
-		if ($resql)
1190
-		{
1191
-		   	if (! $forcecombo)
1192
-			{
1193
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1194
-				$out .= ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);
1195
-			}
1196
-
1197
-			// Construct $out and $outarray
1198
-			$out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparam?' '.$moreparam:'').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
1199
-
1200
-			$textifempty='';
1201
-			// Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
1202
-			//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
1203
-			if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
1204
-			{
1205
-				if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
1206
-				else $textifempty.=$langs->trans("All");
1207
-			}
1208
-			if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
1209
-
1210
-			$num = $this->db->num_rows($resql);
1211
-			$i = 0;
1212
-			if ($num)
1213
-			{
1214
-				while ($i < $num)
1215
-				{
1216
-					$obj = $this->db->fetch_object($resql);
1217
-					$label='';
1218
-					if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
1219
-						if (($obj->client) && (!empty($obj->code_client))) {
1220
-							$label = $obj->code_client. ' - ';
1221
-						}
1222
-						if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
1223
-							$label .= $obj->code_fournisseur. ' - ';
1224
-						}
1225
-						$label.=' '.$obj->name;
1226
-					}
1227
-					else
1228
-					{
1229
-						$label=$obj->name;
1230
-					}
942
+        $num = count($this->cache_types_fees);
943
+        if ($num > 0) return 0;    // Cache already loaded
1231 944
 
1232
-					if(!empty($obj->name_alias)) {
1233
-						$label.=' ('.$obj->name_alias.')';
1234
-					}
945
+        dol_syslog(__METHOD__, LOG_DEBUG);
1235 946
 
1236
-					if ($showtype)
1237
-					{
1238
-						if ($obj->client || $obj->fournisseur) $label.=' (';
1239
-						if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer");
1240
-						if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect");
1241
-						if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier");
1242
-						if ($obj->client || $obj->fournisseur) $label.=')';
1243
-					}
947
+        $langs->load("trips");
1244 948
 
1245
-					if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1246
-						$label.='-'.$obj->address.'-'. $obj->zip.' '. $obj->town;
1247
-						if (!empty($obj->country_code)) {
1248
-							$label.= ' '. $langs->trans('Country'.$obj->country_code);
1249
-						}
1250
-					}
949
+        $sql = "SELECT c.code, c.label";
950
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
951
+        $sql.= " WHERE active > 0";
1251 952
 
1252
-					if (empty($outputmode))
1253
-					{
1254
-						if (in_array($obj->rowid,$selected))
1255
-						{
1256
-							$out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
1257
-						}
1258
-						else
1259
-						{
1260
-							$out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
1261
-						}
1262
-					}
1263
-					else
1264
-					{
1265
-						array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
1266
-					}
953
+        $resql=$this->db->query($sql);
954
+        if ($resql)
955
+        {
956
+            $num = $this->db->num_rows($resql);
957
+            $i = 0;
1267 958
 
1268
-					$i++;
1269
-					if (($i % 10) == 0) $out.="\n";
1270
-				}
1271
-			}
1272
-			$out.= '</select>'."\n";
1273
-		}
1274
-		else
1275
-		{
1276
-			dol_print_error($this->db);
1277
-		}
959
+            while ($i < $num)
960
+            {
961
+                $obj = $this->db->fetch_object($resql);
1278 962
 
1279
-		$this->result=array('nbofthirdparties'=>$num);
963
+                // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
964
+                $label=($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
965
+                $this->cache_types_fees[$obj->code] = $label;
966
+                $i++;
967
+            }
1280 968
 
1281
-		if ($outputmode) return $outarray;
1282
-		return $out;
1283
-	}
969
+            asort($this->cache_types_fees);
1284 970
 
971
+            return $num;
972
+        }
973
+        else
974
+        {
975
+            dol_print_error($this->db);
976
+            return -1;
977
+        }
978
+    }
1285 979
 
1286 980
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1287
-	/**
1288
-	 *    	Return HTML combo list of absolute discounts
1289
-	 *
1290
-	 *    	@param	string	$selected       Id remise fixe pre-selectionnee
1291
-	 *    	@param  string	$htmlname       Nom champ formulaire
1292
-	 *    	@param  string	$filter         Criteres optionnels de filtre
1293
-	 * 		@param	int		$socid			Id of thirdparty
1294
-	 * 		@param	int		$maxvalue		Max value for lines that can be selected
1295
-	 * 		@return	int						Return number of qualifed lines in list
1296
-	 */
1297
-	function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0)
1298
-	{
981
+    /**
982
+     *	Return list of types of notes
983
+     *
984
+     *	@param	string		$selected		Preselected type
985
+     *	@param  string		$htmlname		Name of field in form
986
+     * 	@param	int			$showempty		Add an empty field
987
+     * 	@return	void
988
+     */
989
+    function select_type_fees($selected='',$htmlname='type',$showempty=0)
990
+    {
1299 991
         // phpcs:enable
1300
-		global $langs,$conf;
1301
-
1302
-		// On recherche les remises
1303
-		$sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1304
-		$sql.= " re.description, re.fk_facture_source";
1305
-		$sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
1306
-		$sql.= " WHERE re.fk_soc = ".(int) $socid;
1307
-		$sql.= " AND re.entity = " . $conf->entity;
1308
-		if ($filter) $sql.= " AND ".$filter;
1309
-		$sql.= " ORDER BY re.description ASC";
1310
-
1311
-		dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
1312
-		$resql=$this->db->query($sql);
1313
-		if ($resql)
1314
-		{
1315
-			print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
1316
-			$num = $this->db->num_rows($resql);
1317
-
1318
-			$qualifiedlines=$num;
1319
-
1320
-			$i = 0;
1321
-			if ($num)
1322
-			{
1323
-				print '<option value="0">&nbsp;</option>';
1324
-				while ($i < $num)
1325
-				{
1326
-					$obj = $this->db->fetch_object($resql);
1327
-					$desc=dol_trunc($obj->description,40);
1328
-					if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
1329
-					if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
1330
-					if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
1331
-					if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc=preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
1332
-
1333
-					$selectstring='';
1334
-					if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected';
1335
-
1336
-					$disabled='';
1337
-					if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
1338
-					{
1339
-						$qualifiedlines--;
1340
-						$disabled=' disabled';
1341
-					}
992
+        global $user, $langs;
1342 993
 
1343
-					if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source))
1344
-					{
1345
-						$tmpfac = new Facture($this->db);
1346
-						if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc=$desc.' - '.$tmpfac->ref;
1347
-					}
994
+        dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
1348 995
 
1349
-					print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
1350
-					$i++;
1351
-				}
1352
-			}
1353
-			print '</select>';
1354
-			return $qualifiedlines;
1355
-		}
1356
-		else
1357
-		{
1358
-			dol_print_error($this->db);
1359
-			return -1;
1360
-		}
1361
-	}
996
+        $this->load_cache_types_fees();
1362 997
 
1363
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1364
-	/**
1365
-	 *	Return list of all contacts (for a third party or all)
1366
-	 *
1367
-	 *	@param	int		$socid      	Id ot third party or 0 for all
1368
-	 *	@param  string	$selected   	Id contact pre-selectionne
1369
-	 *	@param  string	$htmlname  	    Name of HTML field ('none' for a not editable field)
1370
-	 *	@param  int		$showempty      0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
1371
-	 *	@param  string	$exclude        List of contacts id to exclude
1372
-	 *	@param	string	$limitto		Disable answers that are not id in this array list
1373
-	 *	@param	integer	$showfunction   Add function into label
1374
-	 *	@param	string	$moreclass		Add more class to class style
1375
-	 *	@param	integer	$showsoc	    Add company into label
1376
-	 * 	@param	int		$forcecombo		Force to use combo box
1377
-	 *  @param	array	$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1378
-	 *  @param	bool	$options_only	Return options only (for ajax treatment)
1379
-	 *  @param	string	$moreparam		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1380
-	 *  @param	string	$htmlid			Html id to use instead of htmlname
1381
-	 *	@return	int						<0 if KO, Nb of contact in list if OK
1382
-	 *  @deprected						You can use selectcontacts directly (warning order of param was changed)
1383
-	 */
1384
-	function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false, $moreparam='', $htmlid='')
1385
-	{
1386
-        // phpcs:enable
1387
-		print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
1388
-		return $this->num;
1389
-	}
1390
-
1391
-	/**
1392
-	 *	Return HTML code of the SELECT of list of all contacts (for a third party or all).
1393
-	 *  This also set the number of contacts found into $this->num
1394
-	 *
1395
-	 * @since 9.0 Add afterSelectContactOptions hook
1396
-	 *
1397
-	 *	@param	int			$socid      	Id ot third party or 0 for all or -1 for empty list
1398
-	 *	@param  array|int	$selected   	Array of ID of pre-selected contact id
1399
-	 *	@param  string		$htmlname  	    Name of HTML field ('none' for a not editable field)
1400
-	 *	@param  int			$showempty     	0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
1401
-	 *	@param  string		$exclude        List of contacts id to exclude
1402
-	 *	@param	string		$limitto		Disable answers that are not id in this array list
1403
-	 *	@param	integer		$showfunction   Add function into label
1404
-	 *	@param	string		$moreclass		Add more class to class style
1405
-	 *	@param	bool		$options_only	Return options only (for ajax treatment)
1406
-	 *	@param	integer		$showsoc	    Add company into label
1407
-	 * 	@param	int			$forcecombo		Force to use combo box (so no ajax beautify effect)
1408
-	 *  @param	array		$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1409
-	 *  @param	string		$moreparam		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1410
-	 *  @param	string		$htmlid			Html id to use instead of htmlname
1411
-	 *  @param	bool		$multiple		add [] in the name of element and add 'multiple' attribut
1412
-	 *	@return	 int						<0 if KO, Nb of contact in list if OK
1413
-	 */
1414
-	function selectcontacts($socid, $selected='', $htmlname='contactid', $showempty=0, $exclude='', $limitto='', $showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array(), $moreparam='', $htmlid='', $multiple=false)
1415
-	{
1416
-		global $conf,$langs,$hookmanager,$action;
1417
-
1418
-		$langs->load('companies');
1419
-
1420
-		if (empty($htmlid)) $htmlid = $htmlname;
1421
-
1422
-		if ($selected === '') $selected = array();
1423
-		else if (!is_array($selected)) $selected = array($selected);
1424
-		$out='';
1425
-
1426
-		if (! is_object($hookmanager))
1427
-		{
1428
-			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1429
-			$hookmanager=new HookManager($this->db);
1430
-		}
1431
-
1432
-		// We search third parties
1433
-		$sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste";
1434
-		if ($showsoc > 0) $sql.= " , s.nom as company";
1435
-		$sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp";
1436
-		if ($showsoc > 0) $sql.= " LEFT OUTER JOIN  ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc";
1437
-		$sql.= " WHERE sp.entity IN (".getEntity('socpeople').")";
1438
-		if ($socid > 0 || $socid == -1) $sql.= " AND sp.fk_soc=".$socid;
1439
-		if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0";
1440
-		$sql.= " ORDER BY sp.lastname ASC";
1441
-
1442
-		dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
1443
-		$resql=$this->db->query($sql);
1444
-		if ($resql)
1445
-		{
1446
-			$num=$this->db->num_rows($resql);
1447
-
1448
-			if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only)
1449
-			{
1450
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1451
-				$out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
1452
-			}
1453
-
1454
-			if ($htmlname != 'none' || $options_only) $out.= '<select class="flat'.($moreclass?' '.$moreclass:'').'" id="'.$htmlid.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
1455
-			if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>&nbsp;</option>';
1456
-			if ($showempty == 2) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>'.$langs->trans("Internal").'</option>';
1457
-			$num = $this->db->num_rows($resql);
1458
-			$i = 0;
1459
-			if ($num)
1460
-			{
1461
-				include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1462
-				$contactstatic=new Contact($this->db);
1463
-
1464
-				while ($i < $num)
1465
-				{
1466
-					$obj = $this->db->fetch_object($resql);
1467
-
1468
-					$contactstatic->id=$obj->rowid;
1469
-					$contactstatic->lastname=$obj->lastname;
1470
-					$contactstatic->firstname=$obj->firstname;
1471
-					if ($obj->statut == 1){
1472
-					if ($htmlname != 'none')
1473
-					{
1474
-						$disabled=0;
1475
-						if (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;
1476
-						if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;
1477
-						if (!empty($selected) && in_array($obj->rowid, $selected))
1478
-						{
1479
-							$out.= '<option value="'.$obj->rowid.'"';
1480
-							if ($disabled) $out.= ' disabled';
1481
-							$out.= ' selected>';
1482
-							$out.= $contactstatic->getFullName($langs);
1483
-							if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1484
-							if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1485
-							$out.= '</option>';
1486
-						}
1487
-						else
1488
-						{
1489
-							$out.= '<option value="'.$obj->rowid.'"';
1490
-							if ($disabled) $out.= ' disabled';
1491
-							$out.= '>';
1492
-							$out.= $contactstatic->getFullName($langs);
1493
-							if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1494
-							if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1495
-							$out.= '</option>';
1496
-						}
1497
-					}
1498
-					else
1499
-					{
1500
-						if (in_array($obj->rowid, $selected))
1501
-						{
1502
-							$out.= $contactstatic->getFullName($langs);
1503
-							if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1504
-							if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1505
-						}
1506
-					}
1507
-				}
1508
-					$i++;
1509
-				}
1510
-			}
1511
-			else
1512
-			{
1513
-				$out.= '<option value="-1"'.(($showempty==2 || $multiple) ? '' : ' selected').' disabled>';
1514
-				$out.= ($socid != -1) ? ($langs->trans($socid?"NoContactDefinedForThirdParty":"NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
1515
-				$out.= '</option>';
1516
-			}
1517
-
1518
-			$parameters = array(
1519
-				'socid'=>$socid,
1520
-				'htmlname'=>$htmlname,
1521
-				'resql'=>$resql,
1522
-				'out'=>&$out,
1523
-				'showfunction'=>$showfunction,
1524
-				'showsoc'=>$showsoc,
1525
-			);
1526
-
1527
-			$reshook = $hookmanager->executeHooks( 'afterSelectContactOptions', $parameters, $this, $action );    // Note that $action and $object may have been modified by some hooks
1528
-
1529
-			if ($htmlname != 'none' || $options_only)
1530
-			{
1531
-				$out.= '</select>';
1532
-			}
1533
-
1534
-			$this->num = $num;
1535
-			return $out;
1536
-		}
1537
-		else
1538
-		{
1539
-			dol_print_error($this->db);
1540
-			return -1;
1541
-		}
1542
-	}
998
+        print '<select id="select_'.$htmlname.'" class="flat" name="'.$htmlname.'">';
999
+        if ($showempty)
1000
+        {
1001
+            print '<option value="-1"';
1002
+            if ($selected == -1) print ' selected';
1003
+            print '>&nbsp;</option>';
1004
+        }
1543 1005
 
1544
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1545
-	/**
1546
-	 *	Return select list of users
1547
-	 *
1548
-	 *  @param	string	$selected       Id user preselected
1549
-	 *  @param  string	$htmlname       Field name in form
1550
-	 *  @param  int		$show_empty     0=liste sans valeur nulle, 1=ajoute valeur inconnue
1551
-	 *  @param  array	$exclude        Array list of users id to exclude
1552
-	 * 	@param	int		$disabled		If select list must be disabled
1553
-	 *  @param  array	$include        Array list of users id to include
1554
-	 * 	@param	int		$enableonly		Array list of users id to be enabled. All other must be disabled
1555
-	 *  @param	string	$force_entity	'0' or Ids of environment to force
1556
-	 * 	@return	void
1557
-	 *  @deprecated		Use select_dolusers instead
1558
-	 *  @see select_dolusers()
1559
-	 */
1560
-	function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude=null,$disabled=0,$include='',$enableonly='',$force_entity='0')
1561
-	{
1562
-        // phpcs:enable
1563
-		print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity);
1564
-	}
1006
+        foreach($this->cache_types_fees as $key => $value)
1007
+        {
1008
+            print '<option value="'.$key.'"';
1009
+            if ($key == $selected) print ' selected';
1010
+            print '>';
1011
+            print $value;
1012
+            print '</option>';
1013
+        }
1565 1014
 
1566
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1567
-	/**
1568
-	 *	Return select list of users
1569
-	 *
1570
-	 *  @param	string	$selected       User id or user object of user preselected. If 0 or < -2, we use id of current user. If -1, keep unselected (if empty is allowed)
1571
-	 *  @param  string	$htmlname       Field name in form
1572
-	 *  @param  int		$show_empty     0=list with no empty value, 1=add also an empty value into list
1573
-	 *  @param  array	$exclude        Array list of users id to exclude
1574
-	 * 	@param	int		$disabled		If select list must be disabled
1575
-	 *  @param  array|string	$include        Array list of users id to include or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
1576
-	 * 	@param	array	$enableonly		Array list of users id to be enabled. If defined, it means that others will be disabled
1577
-	 *  @param	string	$force_entity	'0' or Ids of environment to force
1578
-	 *  @param	int		$maxlength		Maximum length of string into list (0=no limit)
1579
-	 *  @param	int		$showstatus		0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
1580
-	 *  @param	string	$morefilter		Add more filters into sql request (Example: 'employee = 1')
1581
-	 *  @param	integer	$show_every		0=default list, 1=add also a value "Everybody" at beginning of list
1582
-	 *  @param	string	$enableonlytext	If option $enableonlytext is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty.
1583
-	 *  @param	string	$morecss		More css
1584
-	 *  @param  int     $noactive       Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
1585
-	 *  @param  int		$outputmode     0=HTML select string, 1=Array
1586
-	 *  @param  bool	$multiple       add [] in the name of element and add 'multiple' attribut
1587
-	 * 	@return	string					HTML select string
1588
-	 *  @see select_dolgroups
1589
-	 */
1590
-	function select_dolusers($selected='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $show_every=0, $enableonlytext='', $morecss='', $noactive=0, $outputmode=0, $multiple=false)
1591
-	{
1015
+        print '</select>';
1016
+        if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
1017
+    }
1018
+
1019
+
1020
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1021
+    /**
1022
+     *  Return HTML code to select a company.
1023
+     *
1024
+     *  @param		int			$selected				Preselected products
1025
+     *  @param		string		$htmlname				Name of HTML select field (must be unique in page)
1026
+     *  @param		int			$filter					Filter on thirdparty
1027
+     *  @param		int			$limit					Limit on number of returned lines
1028
+     *  @param		array		$ajaxoptions			Options for ajax_autocompleter
1029
+     * 	@param		int			$forcecombo				Force to load all values and output a standard combobox (with no beautification)
1030
+     *  @return		string								Return select box for thirdparty.
1031
+     *  @deprecated	3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0)
1032
+     */
1033
+    function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0)
1034
+    {
1592 1035
         // phpcs:enable
1593
-		global $conf,$user,$langs;
1594
-
1595
-		// If no preselected user defined, we take current user
1596
-		if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;
1597
-
1598
-		if ($selected === '') $selected = array();
1599
-		else if (!is_array($selected)) $selected = array($selected);
1600
-
1601
-		$excludeUsers=null;
1602
-		$includeUsers=null;
1603
-
1604
-		// Permettre l'exclusion d'utilisateurs
1605
-		if (is_array($exclude))	$excludeUsers = implode(",",$exclude);
1606
-		// Permettre l'inclusion d'utilisateurs
1607
-		if (is_array($include))	$includeUsers = implode(",",$include);
1608
-		else if ($include == 'hierarchy')
1609
-		{
1610
-			// Build list includeUsers to have only hierarchy
1611
-			$includeUsers = implode(",",$user->getAllChildIds(0));
1612
-		}
1613
-		else if ($include == 'hierarchyme')
1614
-		{
1615
-			// Build list includeUsers to have only hierarchy and current user
1616
-			$includeUsers = implode(",",$user->getAllChildIds(1));
1617
-		}
1618
-
1619
-		$out='';
1620
-		$outarray = array();
1621
-
1622
-		// Forge request to select users
1623
-		$sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity";
1624
-		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
1625
-		{
1626
-			$sql.= ", e.label";
1627
-		}
1628
-		$sql.= " FROM ".MAIN_DB_PREFIX ."user as u";
1629
-		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
1630
-		{
1631
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity";
1632
-			if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")";
1633
-			else $sql.= " WHERE u.entity IS NOT NULL";
1634
-		}
1635
-		else
1636
-		{
1637
-			if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1638
-			{
1639
-				$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
1640
-				$sql.= " ON ug.fk_user = u.rowid";
1641
-				$sql.= " WHERE ug.entity = ".$conf->entity;
1642
-			}
1643
-			else
1644
-			{
1645
-				$sql.= " WHERE u.entity IN (0,".$conf->entity.")";
1646
-			}
1647
-		}
1648
-		if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id;
1649
-		if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")";
1650
-		if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")";
1651
-		if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0";
1652
-		if (! empty($morefilter)) $sql.=" ".$morefilter;
1653
-
1654
-		if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))	// MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
1655
-		{
1656
-			$sql.= " ORDER BY u.firstname ASC";
1657
-		}
1658
-		else
1659
-		{
1660
-			$sql.= " ORDER BY u.lastname ASC";
1661
-		}
1662
-
1663
-		dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
1664
-		$resql=$this->db->query($sql);
1665
-		if ($resql)
1666
-		{
1667
-			$num = $this->db->num_rows($resql);
1668
-			$i = 0;
1669
-			if ($num)
1670
-			{
1671
-		   		// Enhance with select2
1672
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1673
-				$out .= ajax_combobox($htmlname);
1674
-
1675
-				// do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
1676
-				$out.= '<select class="flat'.($morecss?' minwidth100 '.$morecss:' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
1677
-				if ($show_empty && !$multiple) $out.= '<option value="-1"'.((empty($selected) || in_array(-1,$selected))?' selected':'').'>&nbsp;</option>'."\n";
1678
-				if ($show_every) $out.= '<option value="-2"'.((in_array(-2,$selected))?' selected':'').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
1679
-
1680
-				$userstatic=new User($this->db);
1681
-
1682
-				while ($i < $num)
1683
-				{
1684
-					$obj = $this->db->fetch_object($resql);
1685
-
1686
-					$userstatic->id=$obj->rowid;
1687
-					$userstatic->lastname=$obj->lastname;
1688
-					$userstatic->firstname=$obj->firstname;
1689
-
1690
-					$disableline='';
1691
-					if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1');
1692
-
1693
-					if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && in_array($obj->rowid,$selected) ))
1694
-					{
1695
-						$out.= '<option value="'.$obj->rowid.'"';
1696
-						if ($disableline) $out.= ' disabled';
1697
-						$out.= ' selected>';
1698
-					}
1699
-					else
1700
-					{
1701
-						$out.= '<option value="'.$obj->rowid.'"';
1702
-						if ($disableline) $out.= ' disabled';
1703
-						$out.= '>';
1704
-					}
1036
+            return $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0, $limit);
1037
+    }
1705 1038
 
1706
-					// $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
1707
-					$fullNameMode = 0;
1708
-					if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))
1709
-					{
1710
-						$fullNameMode = 1; //Firstname+lastname
1711
-					}
1712
-					$out.= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
1713
-
1714
-					// Complete name with more info
1715
-					$moreinfo=0;
1716
-					if (! empty($conf->global->MAIN_SHOW_LOGIN))
1717
-					{
1718
-						$out.= ($moreinfo?' - ':' (').$obj->login;
1719
-						$moreinfo++;
1720
-					}
1721
-					if ($showstatus >= 0)
1722
-					{
1723
-						if ($obj->statut == 1 && $showstatus == 1)
1724
-						{
1725
-							$out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
1726
-							$moreinfo++;
1727
-						}
1728
-						if ($obj->statut == 0)
1729
-						{
1730
-							$out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
1731
-							$moreinfo++;
1732
-						}
1733
-					}
1734
-					if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity)
1735
-					{
1736
-						if (! $obj->entity)
1737
-						{
1738
-							$out.=($moreinfo?' - ':' (').$langs->trans("AllEntities");
1739
-							$moreinfo++;
1740
-						}
1741
-						else
1742
-						{
1743
-							$out.=($moreinfo?' - ':' (').($obj->label?$obj->label:$langs->trans("EntityNameNotDefined"));
1744
-							$moreinfo++;
1745
-					 	}
1746
-					}
1747
-					$out.=($moreinfo?')':'');
1748
-					if ($disableline && $disableline != '1')
1749
-					{
1750
-						$out.=' - '.$disableline;	// This is text from $enableonlytext parameter
1751
-					}
1752
-					$out.= '</option>';
1753
-					$outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
1754
-
1755
-					$i++;
1756
-				}
1757
-			}
1758
-			else
1759
-			{
1760
-				$out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
1761
-				$out.= '<option value="">'.$langs->trans("None").'</option>';
1762
-			}
1763
-			$out.= '</select>';
1764
-		}
1765
-		else
1766
-		{
1767
-			dol_print_error($this->db);
1768
-		}
1769
-
1770
-		if ($outputmode) return $outarray;
1771
-		return $out;
1772
-	}
1039
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1040
+    /**
1041
+     *  Output html form to select a third party
1042
+     *
1043
+     *	@param	string	$selected       		Preselected type
1044
+     *	@param  string	$htmlname       		Name of field in form
1045
+     *  @param  string	$filter         		optional filters criteras (example: 's.rowid <> x', 's.client IN (1,3)')
1046
+     *	@param	string	$showempty				Add an empty field (Can be '1' or text key to use on empty line like 'SelectThirdParty')
1047
+     * 	@param	int		$showtype				Show third party type in combolist (customer, prospect or supplier)
1048
+     * 	@param	int		$forcecombo				Force to load all values and output a standard combobox (with no beautification)
1049
+     *  @param	array	$events					Ajax event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1050
+     *	@param	int		$limit					Maximum number of elements
1051
+     *  @param	string	$morecss				Add more css styles to the SELECT component
1052
+     *	@param  string	$moreparam      		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1053
+     *	@param	string	$selected_input_value	Value of preselected input text (for use with ajax)
1054
+     *  @param	int		$hidelabel				Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
1055
+     *  @param	array	$ajaxoptions			Options for ajax_autocompleter
1056
+     * 	@param  bool	$multiple				add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
1057
+     * 	@return	string							HTML string with select box for thirdparty.
1058
+     */
1059
+    function select_company($selected='', $htmlname='socid', $filter='', $showempty='', $showtype=0, $forcecombo=0, $events=array(), $limit=0, $morecss='minwidth100', $moreparam='', $selected_input_value='', $hidelabel=1, $ajaxoptions=array(), $multiple=false)
1060
+    {
1061
+        // phpcs:enable
1062
+        global $conf,$user,$langs;
1063
+
1064
+        $out='';
1065
+
1066
+        if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo)
1067
+        {
1068
+            // No immediate load of all database
1069
+            $placeholder='';
1070
+            if ($selected && empty($selected_input_value))
1071
+            {
1072
+                require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1073
+                $societetmp = new Societe($this->db);
1074
+                $societetmp->fetch($selected);
1075
+                $selected_input_value=$societetmp->name;
1076
+                unset($societetmp);
1077
+            }
1078
+            // mode 1
1079
+            $urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:'');
1080
+            $out.=  ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1081
+            $out.='<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
1082
+            if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
1083
+            else if ($hidelabel > 1) {
1084
+                $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
1085
+                if ($hidelabel == 2) {
1086
+                    $out.=  img_picto($langs->trans("Search"), 'search');
1087
+                }
1088
+            }
1089
+            $out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
1090
+            if ($hidelabel == 3) {
1091
+                $out.=  img_picto($langs->trans("Search"), 'search');
1092
+            }
1093
+        }
1094
+        else
1095
+        {
1096
+            // Immediate load of all database
1097
+            $out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple);
1098
+        }
1099
+
1100
+        return $out;
1101
+    }
1102
+
1103
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1104
+    /**
1105
+     *  Output html form to select a third party.
1106
+     *  Note, you must use the select_company to get the component to select a third party. This function must only be called by select_company.
1107
+     *
1108
+     *	@param	string	$selected       Preselected type
1109
+     *	@param  string	$htmlname       Name of field in form
1110
+     *  @param  string	$filter         Optional filters criteras (example: 's.rowid <> x', 's.client in (1,3)')
1111
+     *	@param	string	$showempty		Add an empty field (Can be '1' or text to use on empty line like 'SelectThirdParty')
1112
+     * 	@param	int		$showtype		Show third party type in combolist (customer, prospect or supplier)
1113
+     * 	@param	int		$forcecombo		Force to use standard HTML select component without beautification
1114
+     *  @param	array	$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1115
+     *  @param	string	$filterkey		Filter on key value
1116
+     *  @param	int		$outputmode		0=HTML select string, 1=Array
1117
+     *  @param	int		$limit			Limit number of answers
1118
+     *  @param	string	$morecss		Add more css styles to the SELECT component
1119
+     *	@param  string	$moreparam      Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1120
+     *	@param  bool	$multiple       add [] in the name of element and add 'multiple' attribut
1121
+     * 	@return	string					HTML string with
1122
+     */
1123
+    function select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='', $multiple=false)
1124
+    {
1125
+        // phpcs:enable
1126
+        global $conf,$user,$langs;
1127
+
1128
+        $out='';
1129
+        $num=0;
1130
+        $outarray=array();
1131
+
1132
+        if ($selected === '') $selected = array();
1133
+        else if (!is_array($selected)) $selected = array($selected);
1134
+
1135
+        // Clean $filter that may contains sql conditions so sql code
1136
+        if (function_exists('testSqlAndScriptInject')) {
1137
+            if (testSqlAndScriptInject($filter, 3)>0) {
1138
+                $filter ='';
1139
+            }
1140
+        }
1141
+
1142
+        // On recherche les societes
1143
+        $sql = "SELECT s.rowid, s.nom as name, s.name_alias, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
1144
+
1145
+        if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1146
+            $sql .= " ,s.address, s.zip, s.town";
1147
+                $sql .= " , dictp.code as country_code";
1148
+        }
1149
+
1150
+        $sql.= " FROM (".MAIN_DB_PREFIX ."societe as s";
1151
+        if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1152
+        $sql.= " )";
1153
+        if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1154
+            $sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid=s.fk_pays";
1155
+        }
1156
+        $sql.= " WHERE s.entity IN (".getEntity('societe').")";
1157
+        if (! empty($user->socid)) $sql.= " AND s.rowid = ".$user->socid;
1158
+        if ($filter) $sql.= " AND (".$filter.")";
1159
+        if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
1160
+        if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0";
1161
+        // Add criteria
1162
+        if ($filterkey && $filterkey != '')
1163
+        {
1164
+            $sql.=" AND (";
1165
+            $prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
1166
+            // For natural search
1167
+            $scrit = explode(' ', $filterkey);
1168
+            $i=0;
1169
+            if (count($scrit) > 1) $sql.="(";
1170
+            foreach ($scrit as $crit) {
1171
+                if ($i > 0) $sql.=" AND ";
1172
+                $sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
1173
+                $i++;
1174
+            }
1175
+            if (count($scrit) > 1) $sql.=")";
1176
+            if (! empty($conf->barcode->enabled))
1177
+            {
1178
+                $sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1179
+            }
1180
+            $sql.= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1181
+            $sql.=")";
1182
+        }
1183
+        $sql.=$this->db->order("nom","ASC");
1184
+        $sql.=$this->db->plimit($limit, 0);
1185
+
1186
+        // Build output string
1187
+        dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
1188
+        $resql=$this->db->query($sql);
1189
+        if ($resql)
1190
+        {
1191
+                if (! $forcecombo)
1192
+            {
1193
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1194
+                $out .= ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);
1195
+            }
1196
+
1197
+            // Construct $out and $outarray
1198
+            $out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparam?' '.$moreparam:'').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
1199
+
1200
+            $textifempty='';
1201
+            // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
1202
+            //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
1203
+            if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
1204
+            {
1205
+                if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
1206
+                else $textifempty.=$langs->trans("All");
1207
+            }
1208
+            if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
1209
+
1210
+            $num = $this->db->num_rows($resql);
1211
+            $i = 0;
1212
+            if ($num)
1213
+            {
1214
+                while ($i < $num)
1215
+                {
1216
+                    $obj = $this->db->fetch_object($resql);
1217
+                    $label='';
1218
+                    if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
1219
+                        if (($obj->client) && (!empty($obj->code_client))) {
1220
+                            $label = $obj->code_client. ' - ';
1221
+                        }
1222
+                        if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
1223
+                            $label .= $obj->code_fournisseur. ' - ';
1224
+                        }
1225
+                        $label.=' '.$obj->name;
1226
+                    }
1227
+                    else
1228
+                    {
1229
+                        $label=$obj->name;
1230
+                    }
1231
+
1232
+                    if(!empty($obj->name_alias)) {
1233
+                        $label.=' ('.$obj->name_alias.')';
1234
+                    }
1235
+
1236
+                    if ($showtype)
1237
+                    {
1238
+                        if ($obj->client || $obj->fournisseur) $label.=' (';
1239
+                        if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer");
1240
+                        if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect");
1241
+                        if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier");
1242
+                        if ($obj->client || $obj->fournisseur) $label.=')';
1243
+                    }
1244
+
1245
+                    if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1246
+                        $label.='-'.$obj->address.'-'. $obj->zip.' '. $obj->town;
1247
+                        if (!empty($obj->country_code)) {
1248
+                            $label.= ' '. $langs->trans('Country'.$obj->country_code);
1249
+                        }
1250
+                    }
1251
+
1252
+                    if (empty($outputmode))
1253
+                    {
1254
+                        if (in_array($obj->rowid,$selected))
1255
+                        {
1256
+                            $out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
1257
+                        }
1258
+                        else
1259
+                        {
1260
+                            $out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
1261
+                        }
1262
+                    }
1263
+                    else
1264
+                    {
1265
+                        array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
1266
+                    }
1267
+
1268
+                    $i++;
1269
+                    if (($i % 10) == 0) $out.="\n";
1270
+                }
1271
+            }
1272
+            $out.= '</select>'."\n";
1273
+        }
1274
+        else
1275
+        {
1276
+            dol_print_error($this->db);
1277
+        }
1278
+
1279
+        $this->result=array('nbofthirdparties'=>$num);
1280
+
1281
+        if ($outputmode) return $outarray;
1282
+        return $out;
1283
+    }
1284
+
1285
+
1286
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1287
+    /**
1288
+     *    	Return HTML combo list of absolute discounts
1289
+     *
1290
+     *    	@param	string	$selected       Id remise fixe pre-selectionnee
1291
+     *    	@param  string	$htmlname       Nom champ formulaire
1292
+     *    	@param  string	$filter         Criteres optionnels de filtre
1293
+     * 		@param	int		$socid			Id of thirdparty
1294
+     * 		@param	int		$maxvalue		Max value for lines that can be selected
1295
+     * 		@return	int						Return number of qualifed lines in list
1296
+     */
1297
+    function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0)
1298
+    {
1299
+        // phpcs:enable
1300
+        global $langs,$conf;
1301
+
1302
+        // On recherche les remises
1303
+        $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1304
+        $sql.= " re.description, re.fk_facture_source";
1305
+        $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
1306
+        $sql.= " WHERE re.fk_soc = ".(int) $socid;
1307
+        $sql.= " AND re.entity = " . $conf->entity;
1308
+        if ($filter) $sql.= " AND ".$filter;
1309
+        $sql.= " ORDER BY re.description ASC";
1310
+
1311
+        dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
1312
+        $resql=$this->db->query($sql);
1313
+        if ($resql)
1314
+        {
1315
+            print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
1316
+            $num = $this->db->num_rows($resql);
1317
+
1318
+            $qualifiedlines=$num;
1319
+
1320
+            $i = 0;
1321
+            if ($num)
1322
+            {
1323
+                print '<option value="0">&nbsp;</option>';
1324
+                while ($i < $num)
1325
+                {
1326
+                    $obj = $this->db->fetch_object($resql);
1327
+                    $desc=dol_trunc($obj->description,40);
1328
+                    if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
1329
+                    if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
1330
+                    if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
1331
+                    if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc=preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
1332
+
1333
+                    $selectstring='';
1334
+                    if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected';
1335
+
1336
+                    $disabled='';
1337
+                    if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
1338
+                    {
1339
+                        $qualifiedlines--;
1340
+                        $disabled=' disabled';
1341
+                    }
1342
+
1343
+                    if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source))
1344
+                    {
1345
+                        $tmpfac = new Facture($this->db);
1346
+                        if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc=$desc.' - '.$tmpfac->ref;
1347
+                    }
1348
+
1349
+                    print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
1350
+                    $i++;
1351
+                }
1352
+            }
1353
+            print '</select>';
1354
+            return $qualifiedlines;
1355
+        }
1356
+        else
1357
+        {
1358
+            dol_print_error($this->db);
1359
+            return -1;
1360
+        }
1361
+    }
1362
+
1363
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1364
+    /**
1365
+     *	Return list of all contacts (for a third party or all)
1366
+     *
1367
+     *	@param	int		$socid      	Id ot third party or 0 for all
1368
+     *	@param  string	$selected   	Id contact pre-selectionne
1369
+     *	@param  string	$htmlname  	    Name of HTML field ('none' for a not editable field)
1370
+     *	@param  int		$showempty      0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
1371
+     *	@param  string	$exclude        List of contacts id to exclude
1372
+     *	@param	string	$limitto		Disable answers that are not id in this array list
1373
+     *	@param	integer	$showfunction   Add function into label
1374
+     *	@param	string	$moreclass		Add more class to class style
1375
+     *	@param	integer	$showsoc	    Add company into label
1376
+     * 	@param	int		$forcecombo		Force to use combo box
1377
+     *  @param	array	$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1378
+     *  @param	bool	$options_only	Return options only (for ajax treatment)
1379
+     *  @param	string	$moreparam		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1380
+     *  @param	string	$htmlid			Html id to use instead of htmlname
1381
+     *	@return	int						<0 if KO, Nb of contact in list if OK
1382
+     *  @deprected						You can use selectcontacts directly (warning order of param was changed)
1383
+     */
1384
+    function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false, $moreparam='', $htmlid='')
1385
+    {
1386
+        // phpcs:enable
1387
+        print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
1388
+        return $this->num;
1389
+    }
1390
+
1391
+    /**
1392
+     *	Return HTML code of the SELECT of list of all contacts (for a third party or all).
1393
+     *  This also set the number of contacts found into $this->num
1394
+     *
1395
+     * @since 9.0 Add afterSelectContactOptions hook
1396
+     *
1397
+     *	@param	int			$socid      	Id ot third party or 0 for all or -1 for empty list
1398
+     *	@param  array|int	$selected   	Array of ID of pre-selected contact id
1399
+     *	@param  string		$htmlname  	    Name of HTML field ('none' for a not editable field)
1400
+     *	@param  int			$showempty     	0=no empty value, 1=add an empty value, 2=add line 'Internal' (used by user edit), 3=add an empty value only if more than one record into list
1401
+     *	@param  string		$exclude        List of contacts id to exclude
1402
+     *	@param	string		$limitto		Disable answers that are not id in this array list
1403
+     *	@param	integer		$showfunction   Add function into label
1404
+     *	@param	string		$moreclass		Add more class to class style
1405
+     *	@param	bool		$options_only	Return options only (for ajax treatment)
1406
+     *	@param	integer		$showsoc	    Add company into label
1407
+     * 	@param	int			$forcecombo		Force to use combo box (so no ajax beautify effect)
1408
+     *  @param	array		$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
1409
+     *  @param	string		$moreparam		Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
1410
+     *  @param	string		$htmlid			Html id to use instead of htmlname
1411
+     *  @param	bool		$multiple		add [] in the name of element and add 'multiple' attribut
1412
+     *	@return	 int						<0 if KO, Nb of contact in list if OK
1413
+     */
1414
+    function selectcontacts($socid, $selected='', $htmlname='contactid', $showempty=0, $exclude='', $limitto='', $showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array(), $moreparam='', $htmlid='', $multiple=false)
1415
+    {
1416
+        global $conf,$langs,$hookmanager,$action;
1417
+
1418
+        $langs->load('companies');
1419
+
1420
+        if (empty($htmlid)) $htmlid = $htmlname;
1421
+
1422
+        if ($selected === '') $selected = array();
1423
+        else if (!is_array($selected)) $selected = array($selected);
1424
+        $out='';
1425
+
1426
+        if (! is_object($hookmanager))
1427
+        {
1428
+            include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1429
+            $hookmanager=new HookManager($this->db);
1430
+        }
1431
+
1432
+        // We search third parties
1433
+        $sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste";
1434
+        if ($showsoc > 0) $sql.= " , s.nom as company";
1435
+        $sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp";
1436
+        if ($showsoc > 0) $sql.= " LEFT OUTER JOIN  ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc";
1437
+        $sql.= " WHERE sp.entity IN (".getEntity('socpeople').")";
1438
+        if ($socid > 0 || $socid == -1) $sql.= " AND sp.fk_soc=".$socid;
1439
+        if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0";
1440
+        $sql.= " ORDER BY sp.lastname ASC";
1441
+
1442
+        dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
1443
+        $resql=$this->db->query($sql);
1444
+        if ($resql)
1445
+        {
1446
+            $num=$this->db->num_rows($resql);
1447
+
1448
+            if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only)
1449
+            {
1450
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1451
+                $out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
1452
+            }
1453
+
1454
+            if ($htmlname != 'none' || $options_only) $out.= '<select class="flat'.($moreclass?' '.$moreclass:'').'" id="'.$htmlid.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
1455
+            if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>&nbsp;</option>';
1456
+            if ($showempty == 2) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>'.$langs->trans("Internal").'</option>';
1457
+            $num = $this->db->num_rows($resql);
1458
+            $i = 0;
1459
+            if ($num)
1460
+            {
1461
+                include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1462
+                $contactstatic=new Contact($this->db);
1463
+
1464
+                while ($i < $num)
1465
+                {
1466
+                    $obj = $this->db->fetch_object($resql);
1467
+
1468
+                    $contactstatic->id=$obj->rowid;
1469
+                    $contactstatic->lastname=$obj->lastname;
1470
+                    $contactstatic->firstname=$obj->firstname;
1471
+                    if ($obj->statut == 1){
1472
+                    if ($htmlname != 'none')
1473
+                    {
1474
+                        $disabled=0;
1475
+                        if (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;
1476
+                        if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;
1477
+                        if (!empty($selected) && in_array($obj->rowid, $selected))
1478
+                        {
1479
+                            $out.= '<option value="'.$obj->rowid.'"';
1480
+                            if ($disabled) $out.= ' disabled';
1481
+                            $out.= ' selected>';
1482
+                            $out.= $contactstatic->getFullName($langs);
1483
+                            if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1484
+                            if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1485
+                            $out.= '</option>';
1486
+                        }
1487
+                        else
1488
+                        {
1489
+                            $out.= '<option value="'.$obj->rowid.'"';
1490
+                            if ($disabled) $out.= ' disabled';
1491
+                            $out.= '>';
1492
+                            $out.= $contactstatic->getFullName($langs);
1493
+                            if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1494
+                            if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1495
+                            $out.= '</option>';
1496
+                        }
1497
+                    }
1498
+                    else
1499
+                    {
1500
+                        if (in_array($obj->rowid, $selected))
1501
+                        {
1502
+                            $out.= $contactstatic->getFullName($langs);
1503
+                            if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1504
+                            if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1505
+                        }
1506
+                    }
1507
+                }
1508
+                    $i++;
1509
+                }
1510
+            }
1511
+            else
1512
+            {
1513
+                $out.= '<option value="-1"'.(($showempty==2 || $multiple) ? '' : ' selected').' disabled>';
1514
+                $out.= ($socid != -1) ? ($langs->trans($socid?"NoContactDefinedForThirdParty":"NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
1515
+                $out.= '</option>';
1516
+            }
1517
+
1518
+            $parameters = array(
1519
+                'socid'=>$socid,
1520
+                'htmlname'=>$htmlname,
1521
+                'resql'=>$resql,
1522
+                'out'=>&$out,
1523
+                'showfunction'=>$showfunction,
1524
+                'showsoc'=>$showsoc,
1525
+            );
1526
+
1527
+            $reshook = $hookmanager->executeHooks( 'afterSelectContactOptions', $parameters, $this, $action );    // Note that $action and $object may have been modified by some hooks
1528
+
1529
+            if ($htmlname != 'none' || $options_only)
1530
+            {
1531
+                $out.= '</select>';
1532
+            }
1533
+
1534
+            $this->num = $num;
1535
+            return $out;
1536
+        }
1537
+        else
1538
+        {
1539
+            dol_print_error($this->db);
1540
+            return -1;
1541
+        }
1542
+    }
1543
+
1544
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1545
+    /**
1546
+     *	Return select list of users
1547
+     *
1548
+     *  @param	string	$selected       Id user preselected
1549
+     *  @param  string	$htmlname       Field name in form
1550
+     *  @param  int		$show_empty     0=liste sans valeur nulle, 1=ajoute valeur inconnue
1551
+     *  @param  array	$exclude        Array list of users id to exclude
1552
+     * 	@param	int		$disabled		If select list must be disabled
1553
+     *  @param  array	$include        Array list of users id to include
1554
+     * 	@param	int		$enableonly		Array list of users id to be enabled. All other must be disabled
1555
+     *  @param	string	$force_entity	'0' or Ids of environment to force
1556
+     * 	@return	void
1557
+     *  @deprecated		Use select_dolusers instead
1558
+     *  @see select_dolusers()
1559
+     */
1560
+    function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude=null,$disabled=0,$include='',$enableonly='',$force_entity='0')
1561
+    {
1562
+        // phpcs:enable
1563
+        print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity);
1564
+    }
1565
+
1566
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1567
+    /**
1568
+     *	Return select list of users
1569
+     *
1570
+     *  @param	string	$selected       User id or user object of user preselected. If 0 or < -2, we use id of current user. If -1, keep unselected (if empty is allowed)
1571
+     *  @param  string	$htmlname       Field name in form
1572
+     *  @param  int		$show_empty     0=list with no empty value, 1=add also an empty value into list
1573
+     *  @param  array	$exclude        Array list of users id to exclude
1574
+     * 	@param	int		$disabled		If select list must be disabled
1575
+     *  @param  array|string	$include        Array list of users id to include or 'hierarchy' to have only supervised users or 'hierarchyme' to have supervised + me
1576
+     * 	@param	array	$enableonly		Array list of users id to be enabled. If defined, it means that others will be disabled
1577
+     *  @param	string	$force_entity	'0' or Ids of environment to force
1578
+     *  @param	int		$maxlength		Maximum length of string into list (0=no limit)
1579
+     *  @param	int		$showstatus		0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
1580
+     *  @param	string	$morefilter		Add more filters into sql request (Example: 'employee = 1')
1581
+     *  @param	integer	$show_every		0=default list, 1=add also a value "Everybody" at beginning of list
1582
+     *  @param	string	$enableonlytext	If option $enableonlytext is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty.
1583
+     *  @param	string	$morecss		More css
1584
+     *  @param  int     $noactive       Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
1585
+     *  @param  int		$outputmode     0=HTML select string, 1=Array
1586
+     *  @param  bool	$multiple       add [] in the name of element and add 'multiple' attribut
1587
+     * 	@return	string					HTML select string
1588
+     *  @see select_dolgroups
1589
+     */
1590
+    function select_dolusers($selected='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $show_every=0, $enableonlytext='', $morecss='', $noactive=0, $outputmode=0, $multiple=false)
1591
+    {
1592
+        // phpcs:enable
1593
+        global $conf,$user,$langs;
1594
+
1595
+        // If no preselected user defined, we take current user
1596
+        if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;
1597
+
1598
+        if ($selected === '') $selected = array();
1599
+        else if (!is_array($selected)) $selected = array($selected);
1600
+
1601
+        $excludeUsers=null;
1602
+        $includeUsers=null;
1603
+
1604
+        // Permettre l'exclusion d'utilisateurs
1605
+        if (is_array($exclude))	$excludeUsers = implode(",",$exclude);
1606
+        // Permettre l'inclusion d'utilisateurs
1607
+        if (is_array($include))	$includeUsers = implode(",",$include);
1608
+        else if ($include == 'hierarchy')
1609
+        {
1610
+            // Build list includeUsers to have only hierarchy
1611
+            $includeUsers = implode(",",$user->getAllChildIds(0));
1612
+        }
1613
+        else if ($include == 'hierarchyme')
1614
+        {
1615
+            // Build list includeUsers to have only hierarchy and current user
1616
+            $includeUsers = implode(",",$user->getAllChildIds(1));
1617
+        }
1618
+
1619
+        $out='';
1620
+        $outarray = array();
1621
+
1622
+        // Forge request to select users
1623
+        $sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity";
1624
+        if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
1625
+        {
1626
+            $sql.= ", e.label";
1627
+        }
1628
+        $sql.= " FROM ".MAIN_DB_PREFIX ."user as u";
1629
+        if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
1630
+        {
1631
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity";
1632
+            if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")";
1633
+            else $sql.= " WHERE u.entity IS NOT NULL";
1634
+        }
1635
+        else
1636
+        {
1637
+            if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1638
+            {
1639
+                $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
1640
+                $sql.= " ON ug.fk_user = u.rowid";
1641
+                $sql.= " WHERE ug.entity = ".$conf->entity;
1642
+            }
1643
+            else
1644
+            {
1645
+                $sql.= " WHERE u.entity IN (0,".$conf->entity.")";
1646
+            }
1647
+        }
1648
+        if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id;
1649
+        if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")";
1650
+        if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")";
1651
+        if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0";
1652
+        if (! empty($morefilter)) $sql.=" ".$morefilter;
1653
+
1654
+        if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))	// MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
1655
+        {
1656
+            $sql.= " ORDER BY u.firstname ASC";
1657
+        }
1658
+        else
1659
+        {
1660
+            $sql.= " ORDER BY u.lastname ASC";
1661
+        }
1662
+
1663
+        dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
1664
+        $resql=$this->db->query($sql);
1665
+        if ($resql)
1666
+        {
1667
+            $num = $this->db->num_rows($resql);
1668
+            $i = 0;
1669
+            if ($num)
1670
+            {
1671
+                    // Enhance with select2
1672
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1673
+                $out .= ajax_combobox($htmlname);
1674
+
1675
+                // do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
1676
+                $out.= '<select class="flat'.($morecss?' minwidth100 '.$morecss:' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
1677
+                if ($show_empty && !$multiple) $out.= '<option value="-1"'.((empty($selected) || in_array(-1,$selected))?' selected':'').'>&nbsp;</option>'."\n";
1678
+                if ($show_every) $out.= '<option value="-2"'.((in_array(-2,$selected))?' selected':'').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
1679
+
1680
+                $userstatic=new User($this->db);
1681
+
1682
+                while ($i < $num)
1683
+                {
1684
+                    $obj = $this->db->fetch_object($resql);
1685
+
1686
+                    $userstatic->id=$obj->rowid;
1687
+                    $userstatic->lastname=$obj->lastname;
1688
+                    $userstatic->firstname=$obj->firstname;
1689
+
1690
+                    $disableline='';
1691
+                    if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1');
1692
+
1693
+                    if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && in_array($obj->rowid,$selected) ))
1694
+                    {
1695
+                        $out.= '<option value="'.$obj->rowid.'"';
1696
+                        if ($disableline) $out.= ' disabled';
1697
+                        $out.= ' selected>';
1698
+                    }
1699
+                    else
1700
+                    {
1701
+                        $out.= '<option value="'.$obj->rowid.'"';
1702
+                        if ($disableline) $out.= ' disabled';
1703
+                        $out.= '>';
1704
+                    }
1705
+
1706
+                    // $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
1707
+                    $fullNameMode = 0;
1708
+                    if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))
1709
+                    {
1710
+                        $fullNameMode = 1; //Firstname+lastname
1711
+                    }
1712
+                    $out.= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
1713
+
1714
+                    // Complete name with more info
1715
+                    $moreinfo=0;
1716
+                    if (! empty($conf->global->MAIN_SHOW_LOGIN))
1717
+                    {
1718
+                        $out.= ($moreinfo?' - ':' (').$obj->login;
1719
+                        $moreinfo++;
1720
+                    }
1721
+                    if ($showstatus >= 0)
1722
+                    {
1723
+                        if ($obj->statut == 1 && $showstatus == 1)
1724
+                        {
1725
+                            $out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
1726
+                            $moreinfo++;
1727
+                        }
1728
+                        if ($obj->statut == 0)
1729
+                        {
1730
+                            $out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
1731
+                            $moreinfo++;
1732
+                        }
1733
+                    }
1734
+                    if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity)
1735
+                    {
1736
+                        if (! $obj->entity)
1737
+                        {
1738
+                            $out.=($moreinfo?' - ':' (').$langs->trans("AllEntities");
1739
+                            $moreinfo++;
1740
+                        }
1741
+                        else
1742
+                        {
1743
+                            $out.=($moreinfo?' - ':' (').($obj->label?$obj->label:$langs->trans("EntityNameNotDefined"));
1744
+                            $moreinfo++;
1745
+                            }
1746
+                    }
1747
+                    $out.=($moreinfo?')':'');
1748
+                    if ($disableline && $disableline != '1')
1749
+                    {
1750
+                        $out.=' - '.$disableline;	// This is text from $enableonlytext parameter
1751
+                    }
1752
+                    $out.= '</option>';
1753
+                    $outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
1754
+
1755
+                    $i++;
1756
+                }
1757
+            }
1758
+            else
1759
+            {
1760
+                $out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
1761
+                $out.= '<option value="">'.$langs->trans("None").'</option>';
1762
+            }
1763
+            $out.= '</select>';
1764
+        }
1765
+        else
1766
+        {
1767
+            dol_print_error($this->db);
1768
+        }
1769
+
1770
+        if ($outputmode) return $outarray;
1771
+        return $out;
1772
+    }
1773 1773
 
1774 1774
 
1775 1775
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1776
-	/**
1777
-	 *	Return select list of users. Selected users are stored into session.
1778
-	 *  List of users are provided into $_SESSION['assignedtouser'].
1779
-	 *
1780
-	 *  @param  string	$action         Value for $action
1781
-	 *  @param  string	$htmlname       Field name in form
1782
-	 *  @param  int		$show_empty     0=list without the empty value, 1=add empty value
1783
-	 *  @param  array	$exclude        Array list of users id to exclude
1784
-	 * 	@param	int		$disabled		If select list must be disabled
1785
-	 *  @param  array	$include        Array list of users id to include or 'hierarchy' to have only supervised users
1786
-	 * 	@param	array	$enableonly		Array list of users id to be enabled. All other must be disabled
1787
-	 *  @param	int		$force_entity	'0' or Ids of environment to force
1788
-	 *  @param	int		$maxlength		Maximum length of string into list (0=no limit)
1789
-	 *  @param	int		$showstatus		0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
1790
-	 *  @param	string	$morefilter		Add more filters into sql request
1791
-	 *  @param	int		$showproperties		Show properties of each attendees
1792
-	 *  @param	array	$listofuserid		Array with properties of each user
1793
-	 *  @param	array	$listofcontactid	Array with properties of each contact
1794
-	 *  @param	array	$listofotherid		Array with properties of each other contact
1795
-	 * 	@return	string					HTML select string
1796
-	 *  @see select_dolgroups
1797
-	 */
1798
-	function select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $showproperties=0, $listofuserid=array(), $listofcontactid=array(), $listofotherid=array())
1799
-	{
1776
+    /**
1777
+     *	Return select list of users. Selected users are stored into session.
1778
+     *  List of users are provided into $_SESSION['assignedtouser'].
1779
+     *
1780
+     *  @param  string	$action         Value for $action
1781
+     *  @param  string	$htmlname       Field name in form
1782
+     *  @param  int		$show_empty     0=list without the empty value, 1=add empty value
1783
+     *  @param  array	$exclude        Array list of users id to exclude
1784
+     * 	@param	int		$disabled		If select list must be disabled
1785
+     *  @param  array	$include        Array list of users id to include or 'hierarchy' to have only supervised users
1786
+     * 	@param	array	$enableonly		Array list of users id to be enabled. All other must be disabled
1787
+     *  @param	int		$force_entity	'0' or Ids of environment to force
1788
+     *  @param	int		$maxlength		Maximum length of string into list (0=no limit)
1789
+     *  @param	int		$showstatus		0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status
1790
+     *  @param	string	$morefilter		Add more filters into sql request
1791
+     *  @param	int		$showproperties		Show properties of each attendees
1792
+     *  @param	array	$listofuserid		Array with properties of each user
1793
+     *  @param	array	$listofcontactid	Array with properties of each contact
1794
+     *  @param	array	$listofotherid		Array with properties of each other contact
1795
+     * 	@return	string					HTML select string
1796
+     *  @see select_dolgroups
1797
+     */
1798
+    function select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $showproperties=0, $listofuserid=array(), $listofcontactid=array(), $listofotherid=array())
1799
+    {
1800 1800
         // phpcs:enable
1801
-		global $conf, $user, $langs;
1802
-
1803
-		$userstatic=new User($this->db);
1804
-		$out='';
1805
-
1806
-		// Method with no ajax
1807
-		//$out.='<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
1808
-		if ($action == 'view')
1809
-		{
1810
-			$out.='';
1811
-		}
1812
-		else
1813
-		{
1814
-			$out.='<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
1815
-			$out.='<script type="text/javascript" language="javascript">jQuery(document).ready(function () {    jQuery(".removedassigned").click(function() {        jQuery(".removedassignedhidden").val(jQuery(this).val());    });})</script>';
1816
-			$out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
1817
-			$out.=' <input type="submit" class="button valignmiddle" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
1818
-			$out.='<br>';
1819
-		}
1820
-		$assignedtouser=array();
1821
-		if (!empty($_SESSION['assignedtouser']))
1822
-		{
1823
-			$assignedtouser=json_decode($_SESSION['assignedtouser'], true);
1824
-		}
1825
-		$nbassignetouser=count($assignedtouser);
1826
-
1827
-		if ($nbassignetouser && $action != 'view') $out.='<br>';
1828
-		if ($nbassignetouser) $out.='<ul class="attendees">';
1829
-		$i=0; $ownerid=0;
1830
-		foreach($assignedtouser as $key => $value)
1831
-		{
1832
-			if ($value['id'] == $ownerid) continue;
1833
-
1834
-			$out.='<li>';
1835
-			$userstatic->fetch($value['id']);
1836
-			$out.= $userstatic->getNomUrl(-1);
1837
-			if ($i == 0) { $ownerid = $value['id']; $out.=' ('.$langs->trans("Owner").')'; }
1838
-			if ($nbassignetouser > 1 && $action != 'view')
1839
-			{
1840
-				$out.=' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
1841
-			}
1842
-			// Show my availability
1843
-			if ($showproperties)
1844
-			{
1845
-				if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid)))
1846
-				{
1847
-					$out.='<div class="myavailability inline-block">';
1848
-					$out.='&nbsp;-&nbsp;<span class="opacitymedium">'.$langs->trans("Availability").':</span>  <input id="transparency" class="marginleftonly marginrightonly" '.($action == 'view'?'disabled':'').' type="checkbox" name="transparency"'.($listofuserid[$ownerid]['transparency']?' checked':'').'>'.$langs->trans("Busy");
1849
-					$out.='</div>';
1850
-				}
1851
-			}
1852
-			//$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
1853
-			//$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
1854
-
1855
-			$out.='</li>';
1856
-			$i++;
1857
-		}
1858
-		if ($nbassignetouser) $out.='</ul>';
1859
-
1860
-		//$out.='</form>';
1861
-		return $out;
1862
-	}
1801
+        global $conf, $user, $langs;
1802
+
1803
+        $userstatic=new User($this->db);
1804
+        $out='';
1805
+
1806
+        // Method with no ajax
1807
+        //$out.='<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
1808
+        if ($action == 'view')
1809
+        {
1810
+            $out.='';
1811
+        }
1812
+        else
1813
+        {
1814
+            $out.='<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
1815
+            $out.='<script type="text/javascript" language="javascript">jQuery(document).ready(function () {    jQuery(".removedassigned").click(function() {        jQuery(".removedassignedhidden").val(jQuery(this).val());    });})</script>';
1816
+            $out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
1817
+            $out.=' <input type="submit" class="button valignmiddle" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
1818
+            $out.='<br>';
1819
+        }
1820
+        $assignedtouser=array();
1821
+        if (!empty($_SESSION['assignedtouser']))
1822
+        {
1823
+            $assignedtouser=json_decode($_SESSION['assignedtouser'], true);
1824
+        }
1825
+        $nbassignetouser=count($assignedtouser);
1826
+
1827
+        if ($nbassignetouser && $action != 'view') $out.='<br>';
1828
+        if ($nbassignetouser) $out.='<ul class="attendees">';
1829
+        $i=0; $ownerid=0;
1830
+        foreach($assignedtouser as $key => $value)
1831
+        {
1832
+            if ($value['id'] == $ownerid) continue;
1833
+
1834
+            $out.='<li>';
1835
+            $userstatic->fetch($value['id']);
1836
+            $out.= $userstatic->getNomUrl(-1);
1837
+            if ($i == 0) { $ownerid = $value['id']; $out.=' ('.$langs->trans("Owner").')'; }
1838
+            if ($nbassignetouser > 1 && $action != 'view')
1839
+            {
1840
+                $out.=' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
1841
+            }
1842
+            // Show my availability
1843
+            if ($showproperties)
1844
+            {
1845
+                if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid)))
1846
+                {
1847
+                    $out.='<div class="myavailability inline-block">';
1848
+                    $out.='&nbsp;-&nbsp;<span class="opacitymedium">'.$langs->trans("Availability").':</span>  <input id="transparency" class="marginleftonly marginrightonly" '.($action == 'view'?'disabled':'').' type="checkbox" name="transparency"'.($listofuserid[$ownerid]['transparency']?' checked':'').'>'.$langs->trans("Busy");
1849
+                    $out.='</div>';
1850
+                }
1851
+            }
1852
+            //$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
1853
+            //$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
1854
+
1855
+            $out.='</li>';
1856
+            $i++;
1857
+        }
1858
+        if ($nbassignetouser) $out.='</ul>';
1859
+
1860
+        //$out.='</form>';
1861
+        return $out;
1862
+    }
1863 1863
 
1864 1864
 
1865 1865
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1866
-	/**
1867
-	 *  Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
1868
-	 *
1869
-	 *  @param		int			$selected				Preselected products
1870
-	 *  @param		string		$htmlname				Name of HTML select field (must be unique in page)
1871
-	 *  @param		int			$filtertype				Filter on product type (''=nofilter, 0=product, 1=service)
1872
-	 *  @param		int			$limit					Limit on number of returned lines
1873
-	 *  @param		int			$price_level			Level of price to show
1874
-	 *  @param		int			$status					Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
1875
-	 *  @param		int			$finished				2=all, 1=finished, 0=raw material
1876
-	 *  @param		string		$selected_input_value	Value of preselected input text (for use with ajax)
1877
-	 *  @param		int			$hidelabel				Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
1878
-	 *  @param		array		$ajaxoptions			Options for ajax_autocompleter
1879
-	 *  @param      int			$socid					Thirdparty Id (to get also price dedicated to this customer)
1880
-	 *  @param		string		$showempty				'' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
1881
-	 * 	@param		int			$forcecombo				Force to use combo box
1882
-	 *  @param      string      $morecss                Add more css on select
1883
-	 *  @param      int         $hidepriceinlabel       1=Hide prices in label
1884
-	 *  @param      string      $warehouseStatus        warehouse status filter, following comma separated filter options can be used
1885
-	 *										            'warehouseopen' = select products from open warehouses,
1886
-	 *										            'warehouseclosed' = select products from closed warehouses,
1887
-	 *										            'warehouseinternal' = select products from warehouses for internal correct/transfer only
1888
-	 *  @param 		array 		$selected_combinations 	Selected combinations. Format: array([attrid] => attrval, [...])
1889
-	 *  @return		void
1890
-	 */
1891
-	function select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $warehouseStatus='', $selected_combinations = array())
1892
-	{
1866
+    /**
1867
+     *  Return list of products for customer in Ajax if Ajax activated or go to select_produits_list
1868
+     *
1869
+     *  @param		int			$selected				Preselected products
1870
+     *  @param		string		$htmlname				Name of HTML select field (must be unique in page)
1871
+     *  @param		int			$filtertype				Filter on product type (''=nofilter, 0=product, 1=service)
1872
+     *  @param		int			$limit					Limit on number of returned lines
1873
+     *  @param		int			$price_level			Level of price to show
1874
+     *  @param		int			$status					Sell status -1=Return all products, 0=Products not on sell, 1=Products on sell
1875
+     *  @param		int			$finished				2=all, 1=finished, 0=raw material
1876
+     *  @param		string		$selected_input_value	Value of preselected input text (for use with ajax)
1877
+     *  @param		int			$hidelabel				Hide label (0=no, 1=yes, 2=show search icon (before) and placeholder, 3 search icon after)
1878
+     *  @param		array		$ajaxoptions			Options for ajax_autocompleter
1879
+     *  @param      int			$socid					Thirdparty Id (to get also price dedicated to this customer)
1880
+     *  @param		string		$showempty				'' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
1881
+     * 	@param		int			$forcecombo				Force to use combo box
1882
+     *  @param      string      $morecss                Add more css on select
1883
+     *  @param      int         $hidepriceinlabel       1=Hide prices in label
1884
+     *  @param      string      $warehouseStatus        warehouse status filter, following comma separated filter options can be used
1885
+     *										            'warehouseopen' = select products from open warehouses,
1886
+     *										            'warehouseclosed' = select products from closed warehouses,
1887
+     *										            'warehouseinternal' = select products from warehouses for internal correct/transfer only
1888
+     *  @param 		array 		$selected_combinations 	Selected combinations. Format: array([attrid] => attrval, [...])
1889
+     *  @return		void
1890
+     */
1891
+    function select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $warehouseStatus='', $selected_combinations = array())
1892
+    {
1893 1893
         // phpcs:enable
1894
-		global $langs,$conf;
1895
-
1896
-		$price_level = (! empty($price_level) ? $price_level : 0);
1897
-
1898
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
1899
-		{
1900
-			$placeholder='';
1901
-
1902
-			if ($selected && empty($selected_input_value))
1903
-			{
1904
-				require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1905
-				$producttmpselect = new Product($this->db);
1906
-				$producttmpselect->fetch($selected);
1907
-				$selected_input_value=$producttmpselect->ref;
1908
-				unset($producttmpselect);
1909
-			}
1910
-			// mode=1 means customers products
1911
-			$urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
1912
-			//Price by customer
1913
-			if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
1914
-				$urloption.='&socid='.$socid;
1915
-			}
1916
-			print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1917
-
1918
-			if (!empty($conf->variants->enabled)) {
1919
-				?>
1894
+        global $langs,$conf;
1895
+
1896
+        $price_level = (! empty($price_level) ? $price_level : 0);
1897
+
1898
+        if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
1899
+        {
1900
+            $placeholder='';
1901
+
1902
+            if ($selected && empty($selected_input_value))
1903
+            {
1904
+                require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1905
+                $producttmpselect = new Product($this->db);
1906
+                $producttmpselect->fetch($selected);
1907
+                $selected_input_value=$producttmpselect->ref;
1908
+                unset($producttmpselect);
1909
+            }
1910
+            // mode=1 means customers products
1911
+            $urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
1912
+            //Price by customer
1913
+            if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
1914
+                $urloption.='&socid='.$socid;
1915
+            }
1916
+            print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1917
+
1918
+            if (!empty($conf->variants->enabled)) {
1919
+                ?>
1920 1920
 				<script>
1921 1921
 
1922 1922
 					selected = <?php echo json_encode($selected_combinations) ?>;
@@ -1987,3871 +1987,3871 @@  discard block
 block discarded – undo
1987 1987
 					});
1988 1988
 				</script>
1989 1989
                 <?php
1990
-			}
1991
-			if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
1992
-			else if ($hidelabel > 1) {
1993
-				$placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
1994
-				if ($hidelabel == 2) {
1995
-					print img_picto($langs->trans("Search"), 'search');
1996
-				}
1997
-			}
1998
-			print '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
1999
-			if ($hidelabel == 3) {
2000
-				print img_picto($langs->trans("Search"), 'search');
2001
-			}
2002
-		}
2003
-		else
2004
-		{
2005
-			print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus);
2006
-		}
2007
-	}
2008
-
2009
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2010
-	/**
2011
-	 *	Return list of products for a customer
2012
-	 *
2013
-	 *	@param      int		$selected           Preselected product
2014
-	 *	@param      string	$htmlname           Name of select html
2015
-	 *  @param		string	$filtertype         Filter on product type (''=nofilter, 0=product, 1=service)
2016
-	 *	@param      int		$limit              Limit on number of returned lines
2017
-	 *	@param      int		$price_level        Level of price to show
2018
-	 * 	@param      string	$filterkey          Filter on product
2019
-	 *	@param		int		$status             -1=Return all products, 0=Products not on sell, 1=Products on sell
2020
-	 *  @param      int		$finished           Filter on finished field: 2=No filter
2021
-	 *  @param      int		$outputmode         0=HTML select string, 1=Array
2022
-	 *  @param      int		$socid     		    Thirdparty Id (to get also price dedicated to this customer)
2023
-	 *  @param		string	$showempty		    '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
2024
-	 * 	@param		int		$forcecombo		    Force to use combo box
2025
-	 *  @param      string  $morecss            Add more css on select
2026
-	 *  @param      int     $hidepriceinlabel   1=Hide prices in label
2027
-	 *  @param      string  $warehouseStatus    warehouse status filter, following comma separated filter options can be used
2028
-	 *										    'warehouseopen' = select products from open warehouses,
2029
-	 *										    'warehouseclosed' = select products from closed warehouses,
2030
-	 *										    'warehouseinternal' = select products from warehouses for internal correct/transfer only
2031
-	 *  @return     array    				    Array of keys for json
2032
-	 */
2033
-	function select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0,$showempty='1',$forcecombo=0,$morecss='',$hidepriceinlabel=0, $warehouseStatus='')
2034
-	{
2035
-        // phpcs:enable
2036
-		global $langs,$conf,$user,$db;
2037
-
2038
-		$out='';
2039
-		$outarray=array();
2040
-
2041
-		$warehouseStatusArray = array();
2042
-		if (! empty($warehouseStatus))
2043
-		{
2044
-			require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
2045
-			if (preg_match('/warehouseclosed/', $warehouseStatus))
2046
-			{
2047
-				$warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
2048
-			}
2049
-			if (preg_match('/warehouseopen/', $warehouseStatus))
2050
-			{
2051
-				$warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
2052
-			}
2053
-			if (preg_match('/warehouseinternal/', $warehouseStatus))
2054
-			{
2055
-				$warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
2056
-			}
2057
-		}
2058
-
2059
-		$selectFields = " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression";
2060
-		(count($warehouseStatusArray)) ? $selectFieldsGrouped = ", sum(ps.reel) as stock" : $selectFieldsGrouped = ", p.stock";
2061
-
2062
-		$sql = "SELECT ";
2063
-		$sql.= $selectFields . $selectFieldsGrouped;
2064
-
2065
-		if (! empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
2066
-		{
2067
-			//Product category
2068
-			$sql.= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie
2069
-						FROM ".MAIN_DB_PREFIX."categorie_product
2070
-						WHERE ".MAIN_DB_PREFIX."categorie_product.fk_product=p.rowid
2071
-						LIMIT 1
2072
-				) AS categorie_product_id ";
2073
-		}
2074
-
2075
-		//Price by customer
2076
-		if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid))
2077
-		{
2078
-			$sql.=', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
2079
-			$sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
2080
-			$selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx";
2081
-		}
2082
-
2083
-		// Multilang : we add translation
2084
-		if (! empty($conf->global->MAIN_MULTILANGS))
2085
-		{
2086
-			$sql.= ", pl.label as label_translated";
2087
-			$selectFields.= ", label_translated";
2088
-		}
2089
-		// Price by quantity
2090
-		if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
2091
-		{
2092
-			$sql.= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
2093
-			if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
2094
-			$sql.= " ORDER BY date_price";
2095
-			$sql.= " DESC LIMIT 1) as price_rowid";
2096
-			$sql.= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";	// price_by_qty is 1 if some prices by qty exists in subtable
2097
-			if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
2098
-			$sql.= " ORDER BY date_price";
2099
-			$sql.= " DESC LIMIT 1) as price_by_qty";
2100
-			$selectFields.= ", price_rowid, price_by_qty";
2101
-		}
2102
-		$sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2103
-		if (count($warehouseStatusArray))
2104
-		{
2105
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
2106
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid";
2107
-		}
2108
-
2109
-		// include search in supplier ref
2110
-		if(!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF))
2111
-		{
2112
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2113
-		}
2114
-
2115
-		//Price by customer
2116
-		if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
2117
-			$sql.=" LEFT JOIN  ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
2118
-		}
2119
-		// Multilang : we add translation
2120
-		if (! empty($conf->global->MAIN_MULTILANGS))
2121
-		{
2122
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'";
2123
-		}
2124
-
2125
-		if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
2126
-			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
2127
-		}
2128
-
2129
-		$sql.= ' WHERE p.entity IN ('.getEntity('product').')';
2130
-		if (count($warehouseStatusArray))
2131
-		{
2132
-			$sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',',$warehouseStatusArray)).'))';
2133
-		}
2134
-
2135
-		if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
2136
-			$sql .= " AND pac.rowid IS NULL";
2137
-		}
2138
-
2139
-		if ($finished == 0)
2140
-		{
2141
-			$sql.= " AND p.finished = ".$finished;
2142
-		}
2143
-		elseif ($finished == 1)
2144
-		{
2145
-			$sql.= " AND p.finished = ".$finished;
2146
-			if ($status >= 0)  $sql.= " AND p.tosell = ".$status;
2147
-		}
2148
-		elseif ($status >= 0)
2149
-		{
2150
-			$sql.= " AND p.tosell = ".$status;
2151
-		}
2152
-		if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype;
2153
-		// Add criteria on ref/label
2154
-		if ($filterkey != '')
2155
-		{
2156
-			$sql.=' AND (';
2157
-			$prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2158
-			// For natural search
2159
-			$scrit = explode(' ', $filterkey);
2160
-			$i=0;
2161
-			if (count($scrit) > 1) $sql.="(";
2162
-			foreach ($scrit as $crit)
2163
-			{
2164
-				if ($i > 0) $sql.=" AND ";
2165
-				$sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'";
2166
-				if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
2167
-				if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION))
2168
-				{
2169
-					$sql.=" OR p.description LIKE '".$db->escape($prefix.$crit)."%'";
2170
-					if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.description LIKE '".$db->escape($prefix.$crit)."%'";
2171
-				}
2172
-				if (! empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql.=" OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'";
2173
-				$sql.=")";
2174
-				$i++;
2175
-			}
2176
-			if (count($scrit) > 1) $sql.=")";
2177
-		  	if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
2178
-			$sql.=')';
2179
-		}
2180
-		if (count($warehouseStatusArray))
2181
-		{
2182
-			$sql.= ' GROUP BY'.$selectFields;
2183
-		}
2184
-
2185
-		//Sort by category
2186
-		if(! empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
2187
-		{
2188
-			$sql .= " ORDER BY categorie_product_id ";
2189
-			//ASC OR DESC order
2190
-			($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .="ASC" : $sql .="DESC";
2191
-		}
2192
-		else
2193
-		{
2194
-			$sql.= $db->order("p.ref");
2195
-		}
2196
-
2197
-		$sql.= $db->plimit($limit, 0);
2198
-
2199
-		// Build output string
2200
-		dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG);
2201
-		$result=$this->db->query($sql);
2202
-		if ($result)
2203
-		{
2204
-			require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2205
-			require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2206
-			$num = $this->db->num_rows($result);
2207
-
2208
-			$events=null;
2209
-
2210
-			if (! $forcecombo)
2211
-			{
2212
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2213
-				$out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
2214
-			}
2215
-
2216
-			$out.='<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
2217
-
2218
-			$textifempty='';
2219
-			// Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
2220
-			//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
2221
-			if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2222
-			{
2223
-				if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
2224
-				else $textifempty.=$langs->trans("All");
2225
-			}
2226
-			if ($showempty) $out.='<option value="0" selected>'.$textifempty.'</option>';
2227
-
2228
-			$i = 0;
2229
-			while ($num && $i < $num)
2230
-			{
2231
-				$opt = '';
2232
-				$optJson = array();
2233
-				$objp = $this->db->fetch_object($result);
2234
-
2235
-				if ((!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1)
2236
-				{ // Price by quantity will return many prices for the same product
2237
-					$sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
2238
-					$sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
2239
-					$sql.= " WHERE fk_product_price=".$objp->price_rowid;
2240
-					$sql.= " ORDER BY quantity ASC";
2241
-
2242
-					dol_syslog(get_class($this)."::select_produits_list search price by qty", LOG_DEBUG);
2243
-					$result2 = $this->db->query($sql);
2244
-					if ($result2)
2245
-					{
2246
-						$nb_prices = $this->db->num_rows($result2);
2247
-						$j = 0;
2248
-						while ($nb_prices && $j < $nb_prices) {
2249
-							$objp2 = $this->db->fetch_object($result2);
2250
-
2251
-							$objp->price_by_qty_rowid = $objp2->rowid;
2252
-							$objp->price_by_qty_price_base_type = $objp2->price_base_type;
2253
-							$objp->price_by_qty_quantity = $objp2->quantity;
2254
-							$objp->price_by_qty_unitprice = $objp2->unitprice;
2255
-							$objp->price_by_qty_remise_percent = $objp2->remise_percent;
2256
-							// For backward compatibility
2257
-							$objp->quantity = $objp2->quantity;
2258
-							$objp->price = $objp2->price;
2259
-							$objp->unitprice = $objp2->unitprice;
2260
-							$objp->remise_percent = $objp2->remise_percent;
2261
-							$objp->remise = $objp2->remise;
2262
-
2263
-							$this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel);
2264
-
2265
-							$j++;
2266
-
2267
-							// Add new entry
2268
-							// "key" value of json key array is used by jQuery automatically as selected value
2269
-							// "label" value of json key array is used by jQuery automatically as text for combo box
2270
-							$out.=$opt;
2271
-							array_push($outarray, $optJson);
2272
-						}
2273
-					}
2274
-				}
2275
-				else
2276
-				{
2277
-					if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
2278
-						$price_product = new Product($this->db);
2279
-						$price_product->fetch($objp->rowid, '', '', 1);
2280
-						$priceparser = new PriceParser($this->db);
2281
-						$price_result = $priceparser->parseProduct($price_product);
2282
-						if ($price_result >= 0) {
2283
-							$objp->price = $price_result;
2284
-							$objp->unitprice = $price_result;
2285
-							//Calculate the VAT
2286
-							$objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
2287
-							$objp->price_ttc = price2num($objp->price_ttc,'MU');
2288
-						}
2289
-					}
2290
-					$this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel);
2291
-					// Add new entry
2292
-					// "key" value of json key array is used by jQuery automatically as selected value
2293
-					// "label" value of json key array is used by jQuery automatically as text for combo box
2294
-					$out.=$opt;
2295
-					array_push($outarray, $optJson);
2296
-				}
2297
-
2298
-				$i++;
2299
-			}
2300
-
2301
-			$out.='</select>';
2302
-
2303
-			$this->db->free($result);
2304
-
2305
-			if (empty($outputmode)) return $out;
2306
-			return $outarray;
2307
-		}
2308
-		else
2309
-		{
2310
-			dol_print_error($db);
2311
-		}
2312
-	}
2313
-
2314
-	/**
2315
-	 * constructProductListOption
2316
-	 *
2317
-	 * @param 	resultset	$objp			    Resultset of fetch
2318
-	 * @param 	string		$opt			    Option (var used for returned value in string option format)
2319
-	 * @param 	string		$optJson		    Option (var used for returned value in json format)
2320
-	 * @param 	int			$price_level	    Price level
2321
-	 * @param 	string		$selected		    Preselected value
2322
-	 * @param   int         $hidepriceinlabel   Hide price in label
2323
-	 * @return	void
2324
-	 */
2325
-	private function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0)
2326
-	{
2327
-		global $langs,$conf,$user,$db;
2328
-
2329
-		$outkey='';
2330
-		$outval='';
2331
-		$outref='';
2332
-		$outlabel='';
2333
-		$outdesc='';
2334
-		$outbarcode='';
2335
-		$outtype='';
2336
-		$outprice_ht='';
2337
-		$outprice_ttc='';
2338
-		$outpricebasetype='';
2339
-		$outtva_tx='';
2340
-		$outqty=1;
2341
-		$outdiscount=0;
2342
-
2343
-		$maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO);
2344
-
2345
-		$label=$objp->label;
2346
-		if (! empty($objp->label_translated)) $label=$objp->label_translated;
2347
-		if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
2348
-
2349
-		$outkey=$objp->rowid;
2350
-		$outref=$objp->ref;
2351
-		$outlabel=$objp->label;
2352
-		$outdesc=$objp->description;
2353
-		$outbarcode=$objp->barcode;
2354
-
2355
-		$outtype=$objp->fk_product_type;
2356
-		$outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
2357
-		$outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
2358
-
2359
-		$opt = '<option value="'.$objp->rowid.'"';
2360
-		$opt.= ($objp->rowid == $selected)?' selected':'';
2361
-		if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)
2362
-		{
2363
-			$opt.= ' pbq="'.$objp->price_by_qty_rowid.'" data-pbq="'.$objp->price_by_qty_rowid.'" data-pbqqty="'.$objp->price_by_qty_quantity.'" data-pbqpercent="'.$objp->price_by_qty_remise_percent.'"';
2364
-		}
2365
-		if (! empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))
2366
-		{
2367
-			if ($objp->stock > 0) $opt.= ' class="product_line_stock_ok"';
2368
-			else if ($objp->stock <= 0) $opt.= ' class="product_line_stock_too_low"';
2369
-		}
2370
-		$opt.= '>';
2371
-		$opt.= $objp->ref;
2372
-		if ($outbarcode) $opt.=' ('.$outbarcode.')';
2373
-		$opt.=' - '.dol_trunc($label,$maxlengtharticle);
2374
-
2375
-		$objRef = $objp->ref;
2376
-		if (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2377
-		$outval.=$objRef;
2378
-		if ($outbarcode) $outval.=' ('.$outbarcode.')';
2379
-		$outval.=' - '.dol_trunc($label,$maxlengtharticle);
2380
-
2381
-		$found=0;
2382
-
2383
-		// Multiprice
2384
-		// If we need a particular price level (from 1 to 6)
2385
-		if (empty($hidepriceinlabel) && $price_level >= 1 && (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
2386
-		{
2387
-			$sql = "SELECT price, price_ttc, price_base_type, tva_tx";
2388
-			$sql.= " FROM ".MAIN_DB_PREFIX."product_price";
2389
-			$sql.= " WHERE fk_product='".$objp->rowid."'";
2390
-			$sql.= " AND entity IN (".getEntity('productprice').")";
2391
-			$sql.= " AND price_level=".$price_level;
2392
-			$sql.= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
2393
-			$sql.= " LIMIT 1";
2394
-
2395
-			dol_syslog(get_class($this).'::constructProductListOption search price for level '.$price_level.'', LOG_DEBUG);
2396
-			$result2 = $this->db->query($sql);
2397
-			if ($result2)
2398
-			{
2399
-				$objp2 = $this->db->fetch_object($result2);
2400
-				if ($objp2)
2401
-				{
2402
-					$found=1;
2403
-					if ($objp2->price_base_type == 'HT')
2404
-					{
2405
-						$opt.= ' - '.price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2406
-						$outval.= ' - '.price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2407
-					}
2408
-					else
2409
-					{
2410
-						$opt.= ' - '.price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2411
-						$outval.= ' - '.price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2412
-					}
2413
-					$outprice_ht=price($objp2->price);
2414
-					$outprice_ttc=price($objp2->price_ttc);
2415
-					$outpricebasetype=$objp2->price_base_type;
2416
-					$outtva_tx=$objp2->tva_tx;
2417
-				}
2418
-			}
2419
-			else
2420
-			{
2421
-				dol_print_error($this->db);
2422
-			}
2423
-		}
2424
-
2425
-		// Price by quantity
2426
-		if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
2427
-		{
2428
-			$found = 1;
2429
-			$outqty=$objp->quantity;
2430
-			$outdiscount=$objp->remise_percent;
2431
-			if ($objp->quantity == 1)
2432
-			{
2433
-				$opt.= ' - '.price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/";
2434
-				$outval.= ' - '.price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/";
2435
-				$opt.= $langs->trans("Unit");	// Do not use strtolower because it breaks utf8 encoding
2436
-				$outval.=$langs->transnoentities("Unit");
2437
-			}
2438
-			else
2439
-			{
2440
-				$opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2441
-				$outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2442
-				$opt.= $langs->trans("Units");	// Do not use strtolower because it breaks utf8 encoding
2443
-				$outval.=$langs->transnoentities("Units");
2444
-			}
2445
-
2446
-			$outprice_ht=price($objp->unitprice);
2447
-			$outprice_ttc=price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
2448
-			$outpricebasetype=$objp->price_base_type;
2449
-			$outtva_tx=$objp->tva_tx;
2450
-		}
2451
-		if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)
2452
-		{
2453
-			$opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2454
-			$outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2455
-		}
2456
-		if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)
2457
-		{
2458
-			$opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
2459
-			$outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
2460
-		}
2461
-
2462
-		// Price by customer
2463
-		if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))
2464
-		{
2465
-			if (!empty($objp->idprodcustprice))
2466
-			{
2467
-				$found = 1;
2468
-
2469
-				if ($objp->custprice_base_type == 'HT')
2470
-				{
2471
-					$opt.= ' - '.price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2472
-					$outval.= ' - '.price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2473
-				}
2474
-				else
2475
-				{
2476
-					$opt.= ' - '.price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2477
-					$outval.= ' - '.price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2478
-				}
2479
-
2480
-				$outprice_ht=price($objp->custprice);
2481
-				$outprice_ttc=price($objp->custprice_ttc);
2482
-				$outpricebasetype=$objp->custprice_base_type;
2483
-				$outtva_tx=$objp->custtva_tx;
2484
-			}
2485
-		}
2486
-
2487
-		// If level no defined or multiprice not found, we used the default price
2488
-		if (empty($hidepriceinlabel) && ! $found)
2489
-		{
2490
-			if ($objp->price_base_type == 'HT')
2491
-			{
2492
-				$opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2493
-				$outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2494
-			}
2495
-			else
2496
-			{
2497
-				$opt.= ' - '.price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2498
-				$outval.= ' - '.price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2499
-			}
2500
-			$outprice_ht=price($objp->price);
2501
-			$outprice_ttc=price($objp->price_ttc);
2502
-			$outpricebasetype=$objp->price_base_type;
2503
-			$outtva_tx=$objp->tva_tx;
2504
-		}
2505
-
2506
-		if (! empty($conf->stock->enabled) && isset($objp->stock) && $objp->fk_product_type == 0)
2507
-		{
2508
-			$opt.= ' - '.$langs->trans("Stock").':'.$objp->stock;
2509
-
2510
-			if ($objp->stock > 0) {
2511
-				$outval.= ' - <span class="product_line_stock_ok">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2512
-			}elseif ($objp->stock <= 0) {
2513
-				$outval.= ' - <span class="product_line_stock_too_low">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2514
-			}
2515
-		}
2516
-
2517
-		if ($outdurationvalue && $outdurationunit)
2518
-		{
2519
-			$da=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("Day"),"w"=>$langs->trans("Week"),"m"=>$langs->trans("Month"),"y"=>$langs->trans("Year"));
2520
-			if (isset($da[$outdurationunit]))
2521
-			{
2522
-				$key = $da[$outdurationunit].($outdurationvalue > 1?'s':'');
2523
-				$opt.= ' - '.$outdurationvalue.' '.$langs->trans($key);
2524
-				$outval.=' - '.$outdurationvalue.' '.$langs->transnoentities($key);
2525
-			}
2526
-		}
2527
-
2528
-		$opt.= "</option>\n";
2529
-		$optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>$outprice_ht, 'price_ttc'=>$outprice_ttc, 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit);
2530
-	}
1990
+            }
1991
+            if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
1992
+            else if ($hidelabel > 1) {
1993
+                $placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
1994
+                if ($hidelabel == 2) {
1995
+                    print img_picto($langs->trans("Search"), 'search');
1996
+                }
1997
+            }
1998
+            print '<input type="text" class="minwidth100" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->PRODUCT_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
1999
+            if ($hidelabel == 3) {
2000
+                print img_picto($langs->trans("Search"), 'search');
2001
+            }
2002
+        }
2003
+        else
2004
+        {
2005
+            print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus);
2006
+        }
2007
+    }
2531 2008
 
2532 2009
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2533
-	/**
2534
-	 *	Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
2535
-	 *
2536
-	 *	@param	int		$socid			Id third party
2537
-	 *	@param  string	$selected       Preselected product
2538
-	 *	@param  string	$htmlname       Name of HTML Select
2539
-	 *  @param	string	$filtertype     Filter on product type (''=nofilter, 0=product, 1=service)
2540
-	 *	@param  string	$filtre			For a SQL filter
2541
-	 *	@param	array	$ajaxoptions	Options for ajax_autocompleter
2542
-	 *  @param	int		$hidelabel		Hide label (0=no, 1=yes)
2543
-	 *  @param  int     $alsoproductwithnosupplierprice    1=Add also product without supplier prices
2544
-	 *	@return	void
2545
-	 */
2546
-	function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0)
2547
-	{
2010
+    /**
2011
+     *	Return list of products for a customer
2012
+     *
2013
+     *	@param      int		$selected           Preselected product
2014
+     *	@param      string	$htmlname           Name of select html
2015
+     *  @param		string	$filtertype         Filter on product type (''=nofilter, 0=product, 1=service)
2016
+     *	@param      int		$limit              Limit on number of returned lines
2017
+     *	@param      int		$price_level        Level of price to show
2018
+     * 	@param      string	$filterkey          Filter on product
2019
+     *	@param		int		$status             -1=Return all products, 0=Products not on sell, 1=Products on sell
2020
+     *  @param      int		$finished           Filter on finished field: 2=No filter
2021
+     *  @param      int		$outputmode         0=HTML select string, 1=Array
2022
+     *  @param      int		$socid     		    Thirdparty Id (to get also price dedicated to this customer)
2023
+     *  @param		string	$showempty		    '' to not show empty line. Translation key to show an empty line. '1' show empty line with no text.
2024
+     * 	@param		int		$forcecombo		    Force to use combo box
2025
+     *  @param      string  $morecss            Add more css on select
2026
+     *  @param      int     $hidepriceinlabel   1=Hide prices in label
2027
+     *  @param      string  $warehouseStatus    warehouse status filter, following comma separated filter options can be used
2028
+     *										    'warehouseopen' = select products from open warehouses,
2029
+     *										    'warehouseclosed' = select products from closed warehouses,
2030
+     *										    'warehouseinternal' = select products from warehouses for internal correct/transfer only
2031
+     *  @return     array    				    Array of keys for json
2032
+     */
2033
+    function select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0,$showempty='1',$forcecombo=0,$morecss='',$hidepriceinlabel=0, $warehouseStatus='')
2034
+    {
2548 2035
         // phpcs:enable
2549
-		global $langs,$conf;
2550
-		global $price_level, $status, $finished;
2551
-
2552
-		$selected_input_value='';
2553
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2554
-		{
2555
-			if ($selected > 0)
2556
-			{
2557
-				require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2558
-				$producttmpselect = new Product($this->db);
2559
-				$producttmpselect->fetch($selected);
2560
-				$selected_input_value=$producttmpselect->ref;
2561
-				unset($producttmpselect);
2562
-			}
2563
-
2564
-			// mode=2 means suppliers products
2565
-			$urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
2566
-			print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
2567
-			print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
2568
-		}
2569
-		else
2570
-		{
2571
-			print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice);
2572
-		}
2573
-	}
2036
+        global $langs,$conf,$user,$db;
2574 2037
 
2575
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2576
-	/**
2577
-	 *	Return list of suppliers products
2578
-	 *
2579
-	 *	@param	int		$socid   		Id societe fournisseur (0 pour aucun filtre)
2580
-	 *	@param  int		$selected       Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
2581
-	 *	@param  string	$htmlname       Nom de la zone select
2582
-	 *  @param	string	$filtertype     Filter on product type (''=nofilter, 0=product, 1=service)
2583
-	 *	@param  string	$filtre         Pour filtre sql
2584
-	 *	@param  string	$filterkey      Filtre des produits
2585
-	 *  @param  int		$statut         -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request)
2586
-	 *  @param  int		$outputmode     0=HTML select string, 1=Array
2587
-	 *  @param  int     $limit          Limit of line number
2588
-	 *  @param  int     $alsoproductwithnosupplierprice    1=Add also product without supplier prices
2589
-	 *  @return array           		Array of keys for json
2590
-	 */
2591
-	function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0)
2592
-	{
2593
-        // phpcs:enable
2594
-		global $langs,$conf,$db;
2595
-
2596
-		$out='';
2597
-		$outarray=array();
2598
-
2599
-		$langs->load('stocks');
2600
-
2601
-		$sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,";
2602
-		$sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
2603
-		$sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
2604
-		$sql.= " pfp.supplier_reputation";
2605
-		$sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2606
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2607
-		if ($socid) $sql.= " AND pfp.fk_soc = ".$socid;
2608
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2609
-		$sql.= " WHERE p.entity IN (".getEntity('product').")";
2610
-		$sql.= " AND p.tobuy = 1";
2611
-		if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype);
2612
-		if (! empty($filtre)) $sql.=" ".$filtre;
2613
-		// Add criteria on ref/label
2614
-		if ($filterkey != '')
2615
-		{
2616
-			$sql.=' AND (';
2617
-			$prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2618
-			// For natural search
2619
-			$scrit = explode(' ', $filterkey);
2620
-			$i=0;
2621
-			if (count($scrit) > 1) $sql.="(";
2622
-			foreach ($scrit as $crit)
2623
-			{
2624
-				if ($i > 0) $sql.=" AND ";
2625
-				$sql.="(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')";
2626
-				$i++;
2627
-			}
2628
-			if (count($scrit) > 1) $sql.=")";
2629
-			if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
2630
-			$sql.=')';
2631
-		}
2632
-		$sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
2633
-		$sql.= $db->plimit($limit, 0);
2634
-
2635
-		// Build output string
2636
-
2637
-		dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
2638
-		$result=$this->db->query($sql);
2639
-		if ($result)
2640
-		{
2641
-			require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2642
-
2643
-			$num = $this->db->num_rows($result);
2644
-
2645
-			//$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">';	// remove select to have id same with combo and ajax
2646
-			$out.='<select class="flat maxwidthonsmartphone" id="'.$htmlname.'" name="'.$htmlname.'">';
2647
-			if (! $selected) $out.='<option value="0" selected>&nbsp;</option>';
2648
-			else $out.='<option value="0">&nbsp;</option>';
2649
-
2650
-			$i = 0;
2651
-			while ($i < $num)
2652
-			{
2653
-				$objp = $this->db->fetch_object($result);
2654
-
2655
-				$outkey=$objp->idprodfournprice;                                                    // id in table of price
2656
-				if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid;   // id of product
2657
-
2658
-				$outref=$objp->ref;
2659
-				$outval='';
2660
-				$outqty=1;
2661
-				$outdiscount=0;
2662
-				$outtype=$objp->fk_product_type;
2663
-				$outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
2664
-				$outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
2665
-
2666
-				$opt = '<option value="'.$outkey.'"';
2667
-				if ($selected && $selected == $objp->idprodfournprice) $opt.= ' selected';
2668
-				if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt.=' disabled';
2669
-				if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0)
2670
-				{
2671
-					$opt.= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqpercent="'.$objp->remise_percent.'"';
2672
-				}
2673
-				$opt.= '>';
2674
-
2675
-				$objRef = $objp->ref;
2676
-				if ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2677
-				$objRefFourn = $objp->ref_fourn;
2678
-				if ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);
2679
-				$label = $objp->label;
2680
-				if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
2681
-
2682
-				$opt.=$objp->ref;
2683
-				if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2684
-					$opt.=' ('.$objp->ref_fourn.')';
2685
-				$opt.=' - ';
2686
-				$outval.=$objRef;
2687
-				if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2688
-					$outval.=' ('.$objRefFourn.')';
2689
-				$outval.=' - ';
2690
-				$opt.=dol_trunc($label, 72).' - ';
2691
-				$outval.=dol_trunc($label, 72).' - ';
2692
-
2693
-				if (! empty($objp->idprodfournprice))
2694
-				{
2695
-					$outqty=$objp->quantity;
2696
-					$outdiscount=$objp->remise_percent;
2697
-					if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
2698
-						$prod_supplier = new ProductFournisseur($this->db);
2699
-						$prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
2700
-						$prod_supplier->id = $objp->fk_product;
2701
-						$prod_supplier->fourn_qty = $objp->quantity;
2702
-						$prod_supplier->fourn_tva_tx = $objp->tva_tx;
2703
-						$prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
2704
-						$priceparser = new PriceParser($this->db);
2705
-						$price_result = $priceparser->parseProductSupplier($prod_supplier);
2706
-						if ($price_result >= 0) {
2707
-							$objp->fprice = $price_result;
2708
-							if ($objp->quantity >= 1)
2709
-							{
2710
-								$objp->unitprice = $objp->fprice / $objp->quantity;
2711
-							}
2712
-						}
2713
-					}
2714
-					if ($objp->quantity == 1)
2715
-					{
2716
-						$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
2717
-						$outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/";
2718
-						$opt.= $langs->trans("Unit");	// Do not use strtolower because it breaks utf8 encoding
2719
-						$outval.=$langs->transnoentities("Unit");
2720
-					}
2721
-					else
2722
-					{
2723
-						$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2724
-						$outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2725
-						$opt.= ' '.$langs->trans("Units");	// Do not use strtolower because it breaks utf8 encoding
2726
-						$outval.= ' '.$langs->transnoentities("Units");
2727
-					}
2038
+        $out='';
2039
+        $outarray=array();
2728 2040
 
2729
-					if ($objp->quantity >= 1)
2730
-					{
2731
-						$opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2732
-						$outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2733
-					}
2734
-					if ($objp->remise_percent >= 1)
2735
-					{
2736
-						$opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
2737
-						$outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
2738
-					}
2739
-					if ($objp->duration)
2740
-					{
2741
-						$opt .= " - ".$objp->duration;
2742
-						$outval.=" - ".$objp->duration;
2743
-					}
2744
-					if (! $socid)
2745
-					{
2746
-						$opt .= " - ".dol_trunc($objp->name,8);
2747
-						$outval.=" - ".dol_trunc($objp->name,8);
2748
-					}
2749
-					if ($objp->supplier_reputation)
2750
-					{
2751
-						//TODO dictionary
2752
-						$reputations=array(''=>$langs->trans('Standard'),'FAVORITE'=>$langs->trans('Favorite'),'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
2041
+        $warehouseStatusArray = array();
2042
+        if (! empty($warehouseStatus))
2043
+        {
2044
+            require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
2045
+            if (preg_match('/warehouseclosed/', $warehouseStatus))
2046
+            {
2047
+                $warehouseStatusArray[] = Entrepot::STATUS_CLOSED;
2048
+            }
2049
+            if (preg_match('/warehouseopen/', $warehouseStatus))
2050
+            {
2051
+                $warehouseStatusArray[] = Entrepot::STATUS_OPEN_ALL;
2052
+            }
2053
+            if (preg_match('/warehouseinternal/', $warehouseStatus))
2054
+            {
2055
+                $warehouseStatusArray[] = Entrepot::STATUS_OPEN_INTERNAL;
2056
+            }
2057
+        }
2753 2058
 
2754
-						$opt .= " - ".$reputations[$objp->supplier_reputation];
2755
-						$outval.=" - ".$reputations[$objp->supplier_reputation];
2756
-					}
2757
-				}
2758
-				else
2759
-				{
2760
-					if (empty($alsoproductwithnosupplierprice))     // No supplier price defined for couple product/supplier
2761
-					{
2762
-						$opt.= $langs->trans("NoPriceDefinedForThisSupplier");
2763
-						$outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
2764
-					}
2765
-					else                                            // No supplier price defined for product, even on other suppliers
2766
-					{
2767
-						$opt.= $langs->trans("NoPriceDefinedForThisSupplier");
2768
-						$outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
2769
-					}
2770
-				}
2771
-				$opt .= "</option>\n";
2772
-
2773
-
2774
-				// Add new entry
2775
-				// "key" value of json key array is used by jQuery automatically as selected value
2776
-				// "label" value of json key array is used by jQuery automatically as text for combo box
2777
-				$out.=$opt;
2778
-				array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false)));
2779
-				// Exemple of var_dump $outarray
2780
-				// array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
2781
-				//           ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
2782
-				//      	 ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
2783
-				//}
2784
-				//var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
2785
-				//$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
2786
-				//var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
2787
-
2788
-				$i++;
2789
-			}
2790
-			$out.='</select>';
2791
-
2792
-			$this->db->free($result);
2793
-
2794
-			include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2795
-			$out.=ajax_combobox($htmlname);
2796
-
2797
-			if (empty($outputmode)) return $out;
2798
-			return $outarray;
2799
-		}
2800
-		else
2801
-		{
2802
-			dol_print_error($this->db);
2803
-		}
2804
-	}
2059
+        $selectFields = " p.rowid, p.label, p.ref, p.description, p.barcode, p.fk_product_type, p.price, p.price_ttc, p.price_base_type, p.tva_tx, p.duration, p.fk_price_expression";
2060
+        (count($warehouseStatusArray)) ? $selectFieldsGrouped = ", sum(ps.reel) as stock" : $selectFieldsGrouped = ", p.stock";
2805 2061
 
2806
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2807
-	/**
2808
-	 *	Return list of suppliers prices for a product
2809
-	 *
2810
-	 *  @param	    int		$productid       	Id of product
2811
-	 *  @param      string	$htmlname        	Name of HTML field
2812
-	 *  @param      int		$selected_supplier  Pre-selected supplier if more than 1 result
2813
-	 *  @return	    void
2814
-	 */
2815
-	function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='')
2816
-	{
2817
-        // phpcs:enable
2818
-		global $langs,$conf;
2819
-
2820
-		$langs->load('stocks');
2821
-
2822
-		$sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,";
2823
-		$sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,";
2824
-		$sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
2825
-		$sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2826
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2827
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2828
-		$sql.= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
2829
-		$sql.= " AND p.tobuy = 1";
2830
-		$sql.= " AND s.fournisseur = 1";
2831
-		$sql.= " AND p.rowid = ".$productid;
2832
-		$sql.= " ORDER BY s.nom, pfp.ref_fourn DESC";
2833
-
2834
-		dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
2835
-		$result=$this->db->query($sql);
2836
-
2837
-		if ($result)
2838
-		{
2839
-			$num = $this->db->num_rows($result);
2840
-
2841
-			$form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
2842
-
2843
-			if (! $num)
2844
-			{
2845
-				$form.= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
2846
-			}
2847
-			else
2848
-			{
2849
-				require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2850
-				$form.= '<option value="0">&nbsp;</option>';
2851
-
2852
-				$i = 0;
2853
-				while ($i < $num)
2854
-				{
2855
-					$objp = $this->db->fetch_object($result);
2856
-
2857
-					$opt = '<option value="'.$objp->idprodfournprice.'"';
2858
-					//if there is only one supplier, preselect it
2859
-					if($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
2860
-						$opt .= ' selected';
2861
-					}
2862
-					$opt.= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
2863
-
2864
-					if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
2865
-						$prod_supplier = new ProductFournisseur($this->db);
2866
-						$prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
2867
-						$prod_supplier->id = $productid;
2868
-						$prod_supplier->fourn_qty = $objp->quantity;
2869
-						$prod_supplier->fourn_tva_tx = $objp->tva_tx;
2870
-						$prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
2871
-						$priceparser = new PriceParser($this->db);
2872
-						$price_result = $priceparser->parseProductSupplier($prod_supplier);
2873
-						if ($price_result >= 0) {
2874
-							$objp->fprice = $price_result;
2875
-							if ($objp->quantity >= 1)
2876
-							{
2877
-								$objp->unitprice = $objp->fprice / $objp->quantity;
2878
-							}
2879
-						}
2880
-					}
2881
-					if ($objp->quantity == 1)
2882
-					{
2883
-						$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
2884
-					}
2062
+        $sql = "SELECT ";
2063
+        $sql.= $selectFields . $selectFieldsGrouped;
2885 2064
 
2886
-					$opt.= $objp->quantity.' ';
2065
+        if (! empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
2066
+        {
2067
+            //Product category
2068
+            $sql.= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie
2069
+						FROM ".MAIN_DB_PREFIX."categorie_product
2070
+						WHERE ".MAIN_DB_PREFIX."categorie_product.fk_product=p.rowid
2071
+						LIMIT 1
2072
+				) AS categorie_product_id ";
2073
+        }
2887 2074
 
2888
-					if ($objp->quantity == 1)
2889
-					{
2890
-						$opt.= $langs->trans("Unit");
2891
-					}
2892
-					else
2893
-					{
2894
-						$opt.= $langs->trans("Units");
2895
-					}
2896
-					if ($objp->quantity > 1)
2897
-					{
2898
-						$opt.=" - ";
2899
-						$opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit");
2900
-					}
2901
-					if ($objp->duration) $opt .= " - ".$objp->duration;
2902
-					$opt .= "</option>\n";
2903
-
2904
-					$form.= $opt;
2905
-					$i++;
2906
-				}
2907
-			}
2908
-
2909
-			$form.= '</select>';
2910
-			$this->db->free($result);
2911
-			return $form;
2912
-		}
2913
-		else
2914
-		{
2915
-			dol_print_error($this->db);
2916
-		}
2917
-	}
2075
+        //Price by customer
2076
+        if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid))
2077
+        {
2078
+            $sql.=', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
2079
+            $sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
2080
+            $selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx";
2081
+        }
2918 2082
 
2919
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2920
-	/**
2921
-	 *    Return list of delivery address
2922
-	 *
2923
-	 *    @param    string	$selected          	Id contact pre-selectionn
2924
-	 *    @param    int		$socid				Id of company
2925
-	 *    @param    string	$htmlname          	Name of HTML field
2926
-	 *    @param    int		$showempty         	Add an empty field
2927
-	 *    @return	integer|null
2928
-	 */
2929
-	function select_address($selected, $socid, $htmlname='address_id',$showempty=0)
2930
-	{
2931
-        // phpcs:enable
2932
-		// looking for users
2933
-		$sql = "SELECT a.rowid, a.label";
2934
-		$sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a";
2935
-		$sql .= " WHERE a.fk_soc = ".$socid;
2936
-		$sql .= " ORDER BY a.label ASC";
2937
-
2938
-		dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
2939
-		$resql=$this->db->query($sql);
2940
-		if ($resql)
2941
-		{
2942
-			print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
2943
-			if ($showempty) print '<option value="0">&nbsp;</option>';
2944
-			$num = $this->db->num_rows($resql);
2945
-			$i = 0;
2946
-			if ($num)
2947
-			{
2948
-				while ($i < $num)
2949
-				{
2950
-					$obj = $this->db->fetch_object($resql);
2951
-
2952
-					if ($selected && $selected == $obj->rowid)
2953
-					{
2954
-						print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
2955
-					}
2956
-					else
2957
-					{
2958
-						print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
2959
-					}
2960
-					$i++;
2961
-				}
2962
-			}
2963
-			print '</select>';
2964
-			return $num;
2965
-		}
2966
-		else
2967
-		{
2968
-			dol_print_error($this->db);
2969
-		}
2970
-	}
2083
+        // Multilang : we add translation
2084
+        if (! empty($conf->global->MAIN_MULTILANGS))
2085
+        {
2086
+            $sql.= ", pl.label as label_translated";
2087
+            $selectFields.= ", label_translated";
2088
+        }
2089
+        // Price by quantity
2090
+        if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
2091
+        {
2092
+            $sql.= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
2093
+            if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
2094
+            $sql.= " ORDER BY date_price";
2095
+            $sql.= " DESC LIMIT 1) as price_rowid";
2096
+            $sql.= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";	// price_by_qty is 1 if some prices by qty exists in subtable
2097
+            if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
2098
+            $sql.= " ORDER BY date_price";
2099
+            $sql.= " DESC LIMIT 1) as price_by_qty";
2100
+            $selectFields.= ", price_rowid, price_by_qty";
2101
+        }
2102
+        $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2103
+        if (count($warehouseStatusArray))
2104
+        {
2105
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
2106
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid";
2107
+        }
2971 2108
 
2109
+        // include search in supplier ref
2110
+        if(!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF))
2111
+        {
2112
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2113
+        }
2972 2114
 
2973
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2974
-	/**
2975
-	 *      Load into cache list of payment terms
2976
-	 *
2977
-	 *      @return     int             Nb of lines loaded, <0 if KO
2978
-	 */
2979
-	function load_cache_conditions_paiements()
2980
-	{
2981
-        // phpcs:enable
2982
-		global $langs;
2983
-
2984
-		$num = count($this->cache_conditions_paiements);
2985
-		if ($num > 0) return 0;    // Cache already loaded
2986
-
2987
-		dol_syslog(__METHOD__, LOG_DEBUG);
2988
-
2989
-		$sql = "SELECT rowid, code, libelle as label";
2990
-		$sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
2991
-		$sql.= " WHERE entity IN (".getEntity('c_payment_term').")";
2992
-		$sql.= " AND active > 0";
2993
-		$sql.= " ORDER BY sortorder";
2994
-
2995
-		$resql = $this->db->query($sql);
2996
-		if ($resql)
2997
-		{
2998
-			$num = $this->db->num_rows($resql);
2999
-			$i = 0;
3000
-			while ($i < $num)
3001
-			{
3002
-				$obj = $this->db->fetch_object($resql);
3003
-
3004
-				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3005
-				$label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:''));
3006
-				$this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code;
3007
-				$this->cache_conditions_paiements[$obj->rowid]['label']=$label;
3008
-				$i++;
3009
-			}
3010
-
3011
-			//$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1);		// We use the field sortorder of table
3012
-
3013
-			return $num;
3014
-		}
3015
-		else
3016
-		{
3017
-			dol_print_error($this->db);
3018
-			return -1;
3019
-		}
3020
-	}
2115
+        //Price by customer
2116
+        if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
2117
+            $sql.=" LEFT JOIN  ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
2118
+        }
2119
+        // Multilang : we add translation
2120
+        if (! empty($conf->global->MAIN_MULTILANGS))
2121
+        {
2122
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'";
2123
+        }
3021 2124
 
3022
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3023
-	/**
3024
-	 *      Charge dans cache la liste des délais de livraison possibles
3025
-	 *
3026
-	 *      @return     int             Nb of lines loaded, <0 if KO
3027
-	 */
3028
-	function load_cache_availability()
3029
-	{
3030
-        // phpcs:enable
3031
-		global $langs;
3032
-
3033
-		$num = count($this->cache_availability);
3034
-		if ($num > 0) return 0;    // Cache already loaded
3035
-
3036
-		dol_syslog(__METHOD__, LOG_DEBUG);
3037
-
3038
-		$langs->load('propal');
3039
-
3040
-		$sql = "SELECT rowid, code, label";
3041
-		$sql.= " FROM ".MAIN_DB_PREFIX.'c_availability';
3042
-		$sql.= " WHERE active > 0";
3043
-
3044
-		$resql = $this->db->query($sql);
3045
-		if ($resql)
3046
-		{
3047
-			$num = $this->db->num_rows($resql);
3048
-			$i = 0;
3049
-			while ($i < $num)
3050
-			{
3051
-				$obj = $this->db->fetch_object($resql);
3052
-
3053
-				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3054
-				$label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:''));
3055
-				$this->cache_availability[$obj->rowid]['code'] =$obj->code;
3056
-				$this->cache_availability[$obj->rowid]['label']=$label;
3057
-				$i++;
3058
-			}
3059
-
3060
-			$this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);
3061
-
3062
-			return $num;
3063
-		}
3064
-		else
3065
-		{
3066
-			dol_print_error($this->db);
3067
-			return -1;
3068
-		}
3069
-	}
3070
-
3071
-	/**
3072
-	 *      Retourne la liste des types de delais de livraison possibles
3073
-	 *
3074
-	 *      @param	int		$selected        Id du type de delais pre-selectionne
3075
-	 *      @param  string	$htmlname        Nom de la zone select
3076
-	 *      @param  string	$filtertype      To add a filter
3077
-	 *		@param	int		$addempty		Add empty entry
3078
-	 *		@return	void
3079
-	 */
3080
-	function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0)
3081
-	{
3082
-		global $langs,$user;
3083
-
3084
-		$this->load_cache_availability();
3085
-
3086
-		dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
3087
-
3088
-		print '<select id="'.$htmlname.'" class="flat" name="'.$htmlname.'">';
3089
-		if ($addempty) print '<option value="0">&nbsp;</option>';
3090
-		foreach($this->cache_availability as $id => $arrayavailability)
3091
-		{
3092
-			if ($selected == $id)
3093
-			{
3094
-				print '<option value="'.$id.'" selected>';
3095
-			}
3096
-			else
3097
-			{
3098
-				print '<option value="'.$id.'">';
3099
-			}
3100
-			print $arrayavailability['label'];
3101
-			print '</option>';
3102
-		}
3103
-		print '</select>';
3104
-		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3105
-	}
3106
-
3107
-	/**
3108
-	 *      Load into cache cache_demand_reason, array of input reasons
3109
-	 *
3110
-	 *      @return     int             Nb of lines loaded, <0 if KO
3111
-	 */
3112
-	function loadCacheInputReason()
3113
-	{
3114
-		global $langs;
3115
-
3116
-		$num = count($this->cache_demand_reason);
3117
-		if ($num > 0) return 0;    // Cache already loaded
3118
-
3119
-		$sql = "SELECT rowid, code, label";
3120
-		$sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
3121
-		$sql.= " WHERE active > 0";
3122
-
3123
-		$resql = $this->db->query($sql);
3124
-		if ($resql)
3125
-		{
3126
-			$num = $this->db->num_rows($resql);
3127
-			$i = 0;
3128
-			$tmparray=array();
3129
-			while ($i < $num)
3130
-			{
3131
-				$obj = $this->db->fetch_object($resql);
3132
-
3133
-				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3134
-				$label=($obj->label!='-'?$obj->label:'');
3135
-				if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
3136
-				if ($langs->trans($obj->code) != $obj->code) $label=$langs->trans($obj->code);																// So translation key SRC_XXX will work
3137
-
3138
-				$tmparray[$obj->rowid]['id']   =$obj->rowid;
3139
-				$tmparray[$obj->rowid]['code'] =$obj->code;
3140
-				$tmparray[$obj->rowid]['label']=$label;
3141
-				$i++;
3142
-			}
3143
-
3144
-			$this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
3145
-
3146
-			unset($tmparray);
3147
-			return $num;
3148
-		}
3149
-		else
3150
-		{
3151
-			dol_print_error($this->db);
3152
-			return -1;
3153
-		}
3154
-	}
3155
-
3156
-	/**
3157
-	 *	Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
3158
-	 *  List found into table c_input_reason loaded by loadCacheInputReason
3159
-	 *
3160
-	 *  @param	int		$selected        Id or code of type origin to select by default
3161
-	 *  @param  string	$htmlname        Nom de la zone select
3162
-	 *  @param  string	$exclude         To exclude a code value (Example: SRC_PROP)
3163
-	 *	@param	int		$addempty		 Add an empty entry
3164
-	 *	@return	void
3165
-	 */
3166
-	function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0)
3167
-	{
3168
-		global $langs,$user;
3169
-
3170
-		$this->loadCacheInputReason();
3171
-
3172
-		print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3173
-		if ($addempty) print '<option value="0"'.(empty($selected)?' selected':'').'>&nbsp;</option>';
3174
-		foreach($this->cache_demand_reason as $id => $arraydemandreason)
3175
-		{
3176
-			if ($arraydemandreason['code']==$exclude) continue;
3177
-
3178
-			if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
3179
-			{
3180
-				print '<option value="'.$arraydemandreason['id'].'" selected>';
3181
-			}
3182
-			else
3183
-			{
3184
-				print '<option value="'.$arraydemandreason['id'].'">';
3185
-			}
3186
-			$label=$arraydemandreason['label'];	// Translation of label was already done into the ->loadCacheInputReason
3187
-			print $langs->trans($label);
3188
-			print '</option>';
3189
-		}
3190
-		print '</select>';
3191
-		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3192
-	}
2125
+        if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
2126
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
2127
+        }
3193 2128
 
3194
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3195
-	/**
3196
-	 *      Charge dans cache la liste des types de paiements possibles
3197
-	 *
3198
-	 *      @return     int                 Nb of lines loaded, <0 if KO
3199
-	 */
3200
-	function load_cache_types_paiements()
3201
-	{
3202
-        // phpcs:enable
3203
-		global $langs;
3204
-
3205
-		$num=count($this->cache_types_paiements);
3206
-		if ($num > 0) return $num;    // Cache already loaded
3207
-
3208
-		dol_syslog(__METHOD__, LOG_DEBUG);
3209
-
3210
-		$this->cache_types_paiements = array();
3211
-
3212
-		$sql = "SELECT id, code, libelle as label, type, active";
3213
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_paiement";
3214
-		$sql.= " WHERE entity IN (".getEntity('c_paiement').")";
3215
-		//if ($active >= 0) $sql.= " AND active = ".$active;
3216
-
3217
-		$resql = $this->db->query($sql);
3218
-		if ($resql)
3219
-		{
3220
-			$num = $this->db->num_rows($resql);
3221
-			$i = 0;
3222
-			while ($i < $num)
3223
-			{
3224
-				$obj = $this->db->fetch_object($resql);
3225
-
3226
-				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3227
-				$label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:''));
3228
-				$this->cache_types_paiements[$obj->id]['id'] =$obj->id;
3229
-				$this->cache_types_paiements[$obj->id]['code'] =$obj->code;
3230
-				$this->cache_types_paiements[$obj->id]['label']=$label;
3231
-				$this->cache_types_paiements[$obj->id]['type'] =$obj->type;
3232
-				$this->cache_types_paiements[$obj->id]['active'] =$obj->active;
3233
-				$i++;
3234
-			}
3235
-
3236
-			$this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
3237
-
3238
-			return $num;
3239
-		}
3240
-		else
3241
-		{
3242
-			dol_print_error($this->db);
3243
-			return -1;
3244
-		}
3245
-	}
2129
+        $sql.= ' WHERE p.entity IN ('.getEntity('product').')';
2130
+        if (count($warehouseStatusArray))
2131
+        {
2132
+            $sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',',$warehouseStatusArray)).'))';
2133
+        }
3246 2134
 
2135
+        if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
2136
+            $sql .= " AND pac.rowid IS NULL";
2137
+        }
3247 2138
 
3248
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3249
-	/**
3250
-	 *      Return list of payment modes.
3251
-	 *      Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
3252
-	 *      See instead to force the default value by the caller.
3253
-	 *
3254
-	 *      @param	int		$selected		Id of payment term to preselect by default
3255
-	 *      @param	string	$htmlname		Nom de la zone select
3256
-	 *      @param	int		$filtertype		Not used
3257
-	 *		@param	int		$addempty		Add an empty entry
3258
-	 * 		@param	int		$noinfoadmin		0=Add admin info, 1=Disable admin info
3259
-	 * 		@param	string	$morecss			Add more CSS on select tag
3260
-	 *		@return	void
3261
-	 */
3262
-	function select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='')
3263
-	{
3264
-        // phpcs:enable
3265
-		global $langs, $user, $conf;
3266
-
3267
-		dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
3268
-
3269
-		$this->load_cache_conditions_paiements();
3270
-
3271
-		// Set default value if not already set by caller
3272
-		if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
3273
-
3274
-		print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
3275
-		if ($addempty) print '<option value="0">&nbsp;</option>';
3276
-		foreach($this->cache_conditions_paiements as $id => $arrayconditions)
3277
-		{
3278
-			if ($selected == $id)
3279
-			{
3280
-				print '<option value="'.$id.'" selected>';
3281
-			}
3282
-			else
3283
-			{
3284
-				print '<option value="'.$id.'">';
3285
-			}
3286
-			print $arrayconditions['label'];
3287
-			print '</option>';
3288
-		}
3289
-		print '</select>';
3290
-		if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3291
-	}
2139
+        if ($finished == 0)
2140
+        {
2141
+            $sql.= " AND p.finished = ".$finished;
2142
+        }
2143
+        elseif ($finished == 1)
2144
+        {
2145
+            $sql.= " AND p.finished = ".$finished;
2146
+            if ($status >= 0)  $sql.= " AND p.tosell = ".$status;
2147
+        }
2148
+        elseif ($status >= 0)
2149
+        {
2150
+            $sql.= " AND p.tosell = ".$status;
2151
+        }
2152
+        if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype;
2153
+        // Add criteria on ref/label
2154
+        if ($filterkey != '')
2155
+        {
2156
+            $sql.=' AND (';
2157
+            $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2158
+            // For natural search
2159
+            $scrit = explode(' ', $filterkey);
2160
+            $i=0;
2161
+            if (count($scrit) > 1) $sql.="(";
2162
+            foreach ($scrit as $crit)
2163
+            {
2164
+                if ($i > 0) $sql.=" AND ";
2165
+                $sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'";
2166
+                if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
2167
+                if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION))
2168
+                {
2169
+                    $sql.=" OR p.description LIKE '".$db->escape($prefix.$crit)."%'";
2170
+                    if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.description LIKE '".$db->escape($prefix.$crit)."%'";
2171
+                }
2172
+                if (! empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql.=" OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'";
2173
+                $sql.=")";
2174
+                $i++;
2175
+            }
2176
+            if (count($scrit) > 1) $sql.=")";
2177
+                if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
2178
+            $sql.=')';
2179
+        }
2180
+        if (count($warehouseStatusArray))
2181
+        {
2182
+            $sql.= ' GROUP BY'.$selectFields;
2183
+        }
3292 2184
 
2185
+        //Sort by category
2186
+        if(! empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
2187
+        {
2188
+            $sql .= " ORDER BY categorie_product_id ";
2189
+            //ASC OR DESC order
2190
+            ($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .="ASC" : $sql .="DESC";
2191
+        }
2192
+        else
2193
+        {
2194
+            $sql.= $db->order("p.ref");
2195
+        }
3293 2196
 
3294
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3295
-	/**
3296
-	 *      Return list of payment methods
3297
-	 *
3298
-	 *      @param	string	$selected       Id du mode de paiement pre-selectionne
3299
-	 *      @param  string	$htmlname       Nom de la zone select
3300
-	 *      @param  string	$filtertype     To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
3301
-	 *      @param  int		$format         0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code
3302
-	 *      @param  int		$empty			1=peut etre vide, 0 sinon
3303
-	 * 		@param	int		$noadmininfo	0=Add admin info, 1=Disable admin info
3304
-	 *      @param  int		$maxlength      Max length of label
3305
-	 *      @param  int     $active         Active or not, -1 = all
3306
-	 *      @param  string  $morecss        Add more CSS on select tag
3307
-	 * 		@return	void
3308
-	 */
3309
-	function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=1, $noadmininfo=0, $maxlength=0, $active=1, $morecss='')
3310
-	{
3311
-        // phpcs:enable
3312
-		global $langs,$user;
3313
-
3314
-		dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
3315
-
3316
-		$filterarray=array();
3317
-		if ($filtertype == 'CRDT')  	$filterarray=array(0,2,3);
3318
-		elseif ($filtertype == 'DBIT') 	$filterarray=array(1,2,3);
3319
-		elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);
3320
-
3321
-		$this->load_cache_types_paiements();
3322
-
3323
-		print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
3324
-		if ($empty) print '<option value="">&nbsp;</option>';
3325
-		foreach($this->cache_types_paiements as $id => $arraytypes)
3326
-		{
3327
-			// If not good status
3328
-			if ($active >= 0 && $arraytypes['active'] != $active) continue;
3329
-
3330
-			// On passe si on a demande de filtrer sur des modes de paiments particuliers
3331
-			if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;
3332
-
3333
-			// We discard empty line if showempty is on because an empty line has already been output.
3334
-			if ($empty && empty($arraytypes['code'])) continue;
3335
-
3336
-			if ($format == 0) print '<option value="'.$id.'"';
3337
-			elseif ($format == 1) print '<option value="'.$arraytypes['code'].'"';
3338
-			elseif ($format == 2) print '<option value="'.$arraytypes['code'].'"';
3339
-			elseif ($format == 3) print '<option value="'.$id.'"';
3340
-			// Si selected est text, on compare avec code, sinon avec id
3341
-			if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';
3342
-			elseif ($selected == $id) print ' selected';
3343
-			print '>';
3344
-			if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3345
-			elseif ($format == 1) $value=$arraytypes['code'];
3346
-			elseif ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3347
-			elseif ($format == 3) $value=$arraytypes['code'];
3348
-			print $value?$value:'&nbsp;';
3349
-			print '</option>';
3350
-		}
3351
-		print '</select>';
3352
-		if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3353
-	}
3354
-
3355
-
3356
-	/**
3357
-	 *  Selection HT or TTC
3358
-	 *
3359
-	 *  @param	string	$selected       Id pre-selectionne
3360
-	 *  @param  string	$htmlname       Nom de la zone select
3361
-	 * 	@return	string					Code of HTML select to chose tax or not
3362
-	 */
3363
-	function selectPriceBaseType($selected='',$htmlname='price_base_type')
3364
-	{
3365
-		global $langs;
3366
-
3367
-		$return='';
3368
-
3369
-		$return.= '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3370
-		$options = array(
3371
-			'HT'=>$langs->trans("HT"),
3372
-			'TTC'=>$langs->trans("TTC")
3373
-		);
3374
-		foreach($options as $id => $value)
3375
-		{
3376
-			if ($selected == $id)
3377
-			{
3378
-				$return.= '<option value="'.$id.'" selected>'.$value;
3379
-			}
3380
-			else
3381
-			{
3382
-				$return.= '<option value="'.$id.'">'.$value;
3383
-			}
3384
-			$return.= '</option>';
3385
-		}
3386
-		$return.= '</select>';
3387
-
3388
-		return $return;
3389
-	}
3390
-
3391
-	/**
3392
-	 *  Return a HTML select list of shipping mode
3393
-	 *
3394
-	 *  @param	string	$selected          Id shipping mode pre-selected
3395
-	 *  @param  string	$htmlname          Name of select zone
3396
-	 *  @param  string	$filtre            To filter list
3397
-	 *  @param  int		$useempty          1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3398
-	 *  @param  string	$moreattrib        To add more attribute on select
3399
-	 * 	@return	void
3400
-	 */
3401
-	function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='')
3402
-	{
3403
-		global $langs, $conf, $user;
3404
-
3405
-		$langs->load("admin");
3406
-		$langs->load("deliveries");
3407
-
3408
-		$sql = "SELECT rowid, code, libelle as label";
3409
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
3410
-		$sql.= " WHERE active > 0";
3411
-		if ($filtre) $sql.=" AND ".$filtre;
3412
-		$sql.= " ORDER BY libelle ASC";
3413
-
3414
-		dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
3415
-		$result = $this->db->query($sql);
3416
-		if ($result) {
3417
-			$num = $this->db->num_rows($result);
3418
-			$i = 0;
3419
-			if ($num) {
3420
-				print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
3421
-				if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
3422
-					print '<option value="-1">&nbsp;</option>';
3423
-				}
3424
-				while ($i < $num) {
3425
-					$obj = $this->db->fetch_object($result);
3426
-					if ($selected == $obj->rowid) {
3427
-						print '<option value="'.$obj->rowid.'" selected>';
3428
-					} else {
3429
-						print '<option value="'.$obj->rowid.'">';
3430
-					}
3431
-					print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
3432
-					print '</option>';
3433
-					$i++;
3434
-				}
3435
-				print "</select>";
3436
-				if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3437
-			} else {
3438
-				print $langs->trans("NoShippingMethodDefined");
3439
-			}
3440
-		} else {
3441
-			dol_print_error($this->db);
3442
-		}
3443
-	}
3444
-
3445
-	/**
3446
-	 *    Display form to select shipping mode
3447
-	 *
3448
-	 *    @param	string	$page        Page
3449
-	 *    @param    int		$selected    Id of shipping mode
3450
-	 *    @param    string	$htmlname    Name of select html field
3451
-	 *    @param    int		$addempty    1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3452
-	 *    @return	void
3453
-	 */
3454
-	function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0)
3455
-	{
3456
-		global $langs, $db;
3457
-
3458
-		$langs->load("deliveries");
3459
-
3460
-		if ($htmlname != "none") {
3461
-			print '<form method="POST" action="'.$page.'">';
3462
-			print '<input type="hidden" name="action" value="setshippingmethod">';
3463
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
3464
-			$this->selectShippingMethod($selected, $htmlname, '', $addempty);
3465
-			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
3466
-			print '</form>';
3467
-		} else {
3468
-			if ($selected) {
3469
-				$code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
3470
-				print $langs->trans("SendingMethod".strtoupper($code));
3471
-			} else {
3472
-				print "&nbsp;";
3473
-			}
3474
-		}
3475
-	}
3476
-
3477
-	/**
3478
-	 * Creates HTML last in cycle situation invoices selector
3479
-	 *
3480
-	 * @param     string  $selected   		Preselected ID
3481
-	 * @param     int     $socid      		Company ID
3482
-	 *
3483
-	 * @return    string                     HTML select
3484
-	 */
3485
-	function selectSituationInvoices($selected = '', $socid = 0)
3486
-	{
3487
-		global $langs;
3488
-
3489
-		$langs->load('bills');
3490
-
3491
-		$opt = '<option value ="" selected></option>';
3492
-		$sql = 'SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_counter>=1';
3493
-		$sql.= ' ORDER by situation_cycle_ref, situation_counter desc';
3494
-		$resql = $this->db->query($sql);
3495
-		if ($resql && $this->db->num_rows($resql) > 0) {
3496
-			// Last seen cycle
3497
-			$ref = 0;
3498
-			while ($obj = $this->db->fetch_object($resql)){
3499
-				//Same company ?
3500
-			    if ($socid == $obj->fk_soc) {
3501
-					//Same cycle ?
3502
-			        if ($obj->situation_cycle_ref != $ref) {
3503
-						// Just seen this cycle
3504
-			            $ref = $obj->situation_cycle_ref;
3505
-						//not final ?
3506
-			            if ($obj->situation_final != 1) {
3507
-							//Not prov?
3508
-			                if (substr($obj->ref, 1, 4) != 'PROV') {
3509
-			                    if ($selected == $obj->rowid) {
3510
-			                        $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
3511
-								} else {
3512
-								    $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
3513
-								}
3514
-							}
3515
-						}
3516
-					}
3517
-				}
3518
-			}
3519
-		}
3520
-		else
3521
-		{
3522
-				dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
3523
-		}
3524
-		if ($opt == '<option value ="" selected></option>')
3525
-		{
3526
-			$opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
3527
-		}
3528
-		return $opt;
3529
-	}
3530
-
3531
-	/**
3532
-	 *      Creates HTML units selector (code => label)
3533
-	 *
3534
-	 *      @param	string	$selected       Preselected Unit ID
3535
-	 *      @param  string	$htmlname       Select name
3536
-	 *      @param	int		$showempty		Add a nempty line
3537
-	 * 		@return	string                  HTML select
3538
-	 */
3539
-	function selectUnits($selected = '', $htmlname = 'units', $showempty=0)
3540
-	{
3541
-		global $langs;
3542
-
3543
-		$langs->load('products');
3544
-
3545
-		$return= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
3546
-
3547
-		$sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';
3548
-		$sql.= ' WHERE active > 0';
3549
-
3550
-		$resql = $this->db->query($sql);
3551
-		if($resql && $this->db->num_rows($resql) > 0)
3552
-		{
3553
-			if ($showempty) $return .= '<option value="none"></option>';
3554
-
3555
-			while($res = $this->db->fetch_object($resql))
3556
-			{
3557
-			    $unitLabel = $res->label;
3558
-			    if (! empty($langs->tab_translate['unit'.$res->code]))	// check if Translation is available before
3559
-			    {
3560
-			        $unitLabel = $langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label;
3561
-			    }
3562
-
3563
-				if ($selected == $res->rowid)
3564
-				{
3565
-				    $return.='<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
3566
-				}
3567
-				else
3568
-				{
3569
-				    $return.='<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
3570
-				}
3571
-			}
3572
-			$return.='</select>';
3573
-		}
3574
-		return $return;
3575
-	}
2197
+        $sql.= $db->plimit($limit, 0);
3576 2198
 
3577
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3578
-	/**
3579
-	 *  Return a HTML select list of bank accounts
3580
-	 *
3581
-	 *  @param	string	$selected           Id account pre-selected
3582
-	 *  @param  string	$htmlname           Name of select zone
3583
-	 *  @param  int		$statut             Status of searched accounts (0=open, 1=closed, 2=both)
3584
-	 *  @param  string	$filtre             To filter list
3585
-	 *  @param  int		$useempty           1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3586
-	 *  @param  string	$moreattrib         To add more attribute on select
3587
-	 *  @param	int		$showcurrency		Show currency in label
3588
-	 * 	@return	int							<0 if error, Num of bank account found if OK (0, 1, 2, ...)
3589
-	 */
3590
-	function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='',$showcurrency=0)
3591
-	{
3592
-        // phpcs:enable
3593
-		global $langs, $conf;
3594
-
3595
-		$langs->load("admin");
3596
-		$num = 0;
3597
-
3598
-		$sql = "SELECT rowid, label, bank, clos as status, currency_code";
3599
-		$sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
3600
-		$sql.= " WHERE entity IN (".getEntity('bank_account').")";
3601
-		if ($statut != 2) $sql.= " AND clos = '".$statut."'";
3602
-		if ($filtre) $sql.=" AND ".$filtre;
3603
-		$sql.= " ORDER BY label";
3604
-
3605
-		dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
3606
-		$result = $this->db->query($sql);
3607
-		if ($result)
3608
-		{
3609
-			$num = $this->db->num_rows($result);
3610
-			$i = 0;
3611
-			if ($num)
3612
-			{
3613
-				print '<select id="select'.$htmlname.'" class="flat selectbankaccount" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
3614
-				if ($useempty == 1 || ($useempty == 2 && $num > 1))
3615
-				{
3616
-					print '<option value="-1">&nbsp;</option>';
3617
-				}
3618
-
3619
-				while ($i < $num)
3620
-				{
3621
-					$obj = $this->db->fetch_object($result);
3622
-					if ($selected == $obj->rowid)
3623
-					{
3624
-						print '<option value="'.$obj->rowid.'" selected>';
3625
-					}
3626
-					else
3627
-					{
3628
-						print '<option value="'.$obj->rowid.'">';
3629
-					}
3630
-					print trim($obj->label);
3631
-					if ($showcurrency) print ' ('.$obj->currency_code.')';
3632
-					if ($statut == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
3633
-					print '</option>';
3634
-					$i++;
3635
-				}
3636
-				print "</select>";
3637
-			}
3638
-			else
3639
-			{
3640
-				if ($statut == 0) print '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
3641
-				else print '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
3642
-			}
3643
-		}
3644
-		else {
3645
-			dol_print_error($this->db);
3646
-		}
3647
-
3648
-		return $num;
3649
-	}
3650
-
3651
-	/**
3652
-	 *    Display form to select bank account
3653
-	 *
3654
-	 *    @param	string	$page        Page
3655
-	 *    @param    int		$selected    Id of bank account
3656
-	 *    @param    string	$htmlname    Name of select html field
3657
-	 *    @param    int		$addempty    1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3658
-	 *    @return	void
3659
-	 */
3660
-	function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0)
3661
-	{
3662
-		global $langs;
3663
-		if ($htmlname != "none") {
3664
-			print '<form method="POST" action="'.$page.'">';
3665
-			print '<input type="hidden" name="action" value="setbankaccount">';
3666
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
3667
-			$nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
3668
-			if ($nbaccountfound > 0) print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
3669
-			print '</form>';
3670
-		} else {
3671
-
3672
-			$langs->load('banks');
3673
-
3674
-			if ($selected) {
3675
-				require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php';
3676
-				$bankstatic=new Account($this->db);
3677
-				$result = $bankstatic->fetch($selected);
3678
-				if ($result) print $bankstatic->getNomUrl(1);
3679
-			} else {
3680
-				print "&nbsp;";
3681
-			}
3682
-		}
3683
-	}
2199
+        // Build output string
2200
+        dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG);
2201
+        $result=$this->db->query($sql);
2202
+        if ($result)
2203
+        {
2204
+            require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2205
+            require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2206
+            $num = $this->db->num_rows($result);
3684 2207
 
3685
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3686
-	/**
3687
-	 *    Return list of categories having choosed type
3688
-	 *
3689
-	 *    @param	string|int	$type				Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
3690
-	 *    @param    string		$selected    		Id of category preselected or 'auto' (autoselect category if there is only one element)
3691
-	 *    @param    string		$htmlname			HTML field name
3692
-	 *    @param    int			$maxlength      	Maximum length for labels
3693
-	 *    @param    int			$excludeafterid 	Exclude all categories after this leaf in category tree.
3694
-	 *    @param	int			$outputmode			0=HTML select string, 1=Array
3695
-	 *    @return	string
3696
-	 *    @see select_categories
3697
-	 */
3698
-	function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0)
3699
-	{
3700
-        // phpcs:enable
3701
-		global $conf, $langs;
3702
-		$langs->load("categories");
3703
-
3704
-		include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
3705
-
3706
-		// For backward compatibility
3707
-		if (is_numeric($type))
3708
-		{
3709
-			dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
3710
-		}
3711
-
3712
-		if ($type === Categorie::TYPE_BANK_LINE)
3713
-		{
3714
-			// TODO Move this into common category feature
3715
-			$categids=array();
3716
-			$sql = "SELECT c.label, c.rowid";
3717
-			$sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
3718
-			$sql.= " WHERE entity = ".$conf->entity;
3719
-			$sql.= " ORDER BY c.label";
3720
-			$result = $this->db->query($sql);
3721
-			if ($result)
3722
-			{
3723
-				$num = $this->db->num_rows($result);
3724
-				$i = 0;
3725
-				while ($i < $num)
3726
-				{
3727
-					$objp = $this->db->fetch_object($result);
3728
-					if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
3729
-					$i++;
3730
-				}
3731
-				$this->db->free($result);
3732
-			}
3733
-			else dol_print_error($this->db);
3734
-		}
3735
-		else
3736
-		{
3737
-			$cat = new Categorie($this->db);
3738
-			$cate_arbo = $cat->get_full_arbo($type, $excludeafterid);
3739
-		}
3740
-
3741
-		$output = '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
3742
-		$outarray=array();
3743
-		if (is_array($cate_arbo))
3744
-		{
3745
-			if (! count($cate_arbo)) $output.= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
3746
-			else
3747
-			{
3748
-				$output.= '<option value="-1">&nbsp;</option>';
3749
-				foreach($cate_arbo as $key => $value)
3750
-				{
3751
-					if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
3752
-					{
3753
-						$add = 'selected ';
3754
-					}
3755
-					else
3756
-					{
3757
-						$add = '';
3758
-					}
3759
-					$output.= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'],$maxlength,'middle').'</option>';
2208
+            $events=null;
3760 2209
 
3761
-					$outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
3762
-				}
3763
-			}
3764
-		}
3765
-		$output.= '</select>';
3766
-		$output.= "\n";
2210
+            if (! $forcecombo)
2211
+            {
2212
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2213
+                $out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
2214
+            }
3767 2215
 
3768
-		if ($outputmode) return $outarray;
3769
-		return $output;
3770
-	}
2216
+            $out.='<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
3771 2217
 
3772
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3773
-	/**
3774
-	 *     Show a confirmation HTML form or AJAX popup
3775
-	 *
3776
-	 *     @param	string		$page        	   	Url of page to call if confirmation is OK
3777
-	 *     @param	string		$title       	   	Title
3778
-	 *     @param	string		$question    	   	Question
3779
-	 *     @param 	string		$action      	   	Action
3780
-	 *	   @param	array		$formquestion	   	An array with forms complementary inputs
3781
-	 * 	   @param	string		$selectedchoice		"" or "no" or "yes"
3782
-	 * 	   @param	int			$useajax		   	0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx
3783
-	 *     @param	int			$height          	Force height of box
3784
-	 *     @param	int			$width				Force width of box
3785
-	 *     @return 	void
3786
-	 *     @deprecated
3787
-	 *     @see formconfirm()
3788
-	 */
3789
-	function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500)
3790
-	{
3791
-        // phpcs:enable
3792
-        dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
3793
-		print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
3794
-	}
3795
-
3796
-	/**
3797
-	 *     Show a confirmation HTML form or AJAX popup.
3798
-	 *     Easiest way to use this is with useajax=1.
3799
-	 *     If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
3800
-	 *     just after calling this method. For example:
3801
-	 *       print '<script type="text/javascript">'."\n";
3802
-	 *       print 'jQuery(document).ready(function() {'."\n";
3803
-	 *       print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
3804
-	 *       print '});'."\n";
3805
-	 *       print '</script>'."\n";
3806
-	 *
3807
-	 *     @param  	string		$page        	   	Url of page to call if confirmation is OK. Can contains paramaters (param 'action' and 'confirm' will be reformated)
3808
-	 *     @param	string		$title       	   	Title
3809
-	 *     @param	string		$question    	   	Question
3810
-	 *     @param 	string		$action      	   	Action
3811
-	 *	   @param  	array		$formquestion	   	An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))
3812
-	 *												type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', ...
3813
-	 * 	   @param  	string		$selectedchoice  	'' or 'no', or 'yes' or '1' or '0'
3814
-	 * 	   @param  	int			$useajax		   	0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
3815
-	 *     @param  	int			$height          	Force height of box
3816
-	 *     @param	int			$width				Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
3817
-	 *     @param	int			$disableformtag		1=Disable form tag. Can be used if we are already inside a <form> section.
3818
-	 *     @return 	string      	    			HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
3819
-	 */
3820
-	function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice='', $useajax=0, $height=210, $width=500, $disableformtag=0)
3821
-	{
3822
-		global $langs,$conf;
3823
-		global $useglobalvars;
3824
-
3825
-		$more='';
3826
-		$formconfirm='';
3827
-		$inputok=array();
3828
-		$inputko=array();
3829
-
3830
-		// Clean parameters
3831
-		$newselectedchoice=empty($selectedchoice)?"no":$selectedchoice;
3832
-		if ($conf->browser->layout == 'phone') $width='95%';
3833
-
3834
-		if (is_array($formquestion) && ! empty($formquestion))
3835
-		{
3836
-			// First add hidden fields and value
3837
-			foreach ($formquestion as $key => $input)
3838
-			{
3839
-				if (is_array($input) && ! empty($input))
3840
-				{
3841
-					if ($input['type'] == 'hidden')
3842
-					{
3843
-						$more.='<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
3844
-					}
3845
-				}
3846
-			}
3847
-
3848
-			// Now add questions
3849
-			$more.='<table class="paddingtopbottomonly" width="100%">'."\n";
3850
-			if (! empty($formquestion['text'])) $more.='<tr><td colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
3851
-			foreach ($formquestion as $key => $input)
3852
-			{
3853
-				if (is_array($input) && ! empty($input))
3854
-				{
3855
-					$size=(! empty($input['size'])?' size="'.$input['size'].'"':'');
3856
-					$moreattr=(! empty($input['moreattr'])?' '.$input['moreattr']:'');
3857
-					$morecss=(! empty($input['morecss'])?' '.$input['morecss']:'');
3858
-
3859
-					if ($input['type'] == 'text')
3860
-					{
3861
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="text" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3862
-					}
3863
-					elseif ($input['type'] == 'password')
3864
-					{
3865
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="password" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3866
-					}
3867
-					elseif ($input['type'] == 'select')
3868
-					{
3869
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
3870
-						if (! empty($input['label'])) $more.=$input['label'].'</td><td class="tdtop" align="left">';
3871
-						$more.=$this->selectarray($input['name'],$input['values'],$input['default'],1,0,0,$moreattr,0,0,0,'',$morecss);
3872
-						$more.='</td></tr>'."\n";
3873
-					}
3874
-					elseif ($input['type'] == 'checkbox')
3875
-					{
3876
-						$more.='<tr>';
3877
-						$more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].' </td><td align="left">';
3878
-						$more.='<input type="checkbox" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$moreattr;
3879
-						if (! is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') $more.=' checked';
3880
-						if (is_bool($input['value']) && $input['value']) $more.=' checked';
3881
-						if (isset($input['disabled'])) $more.=' disabled';
3882
-						$more.=' /></td>';
3883
-						$more.='</tr>'."\n";
3884
-					}
3885
-					elseif ($input['type'] == 'radio')
3886
-					{
3887
-						$i=0;
3888
-						foreach($input['values'] as $selkey => $selval)
3889
-						{
3890
-							$more.='<tr>';
3891
-							if ($i==0) $more.='<td'.(empty($input['tdclass'])?' class="tdtop"':(' class="tdtop '.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3892
-							else $more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>&nbsp;</td>';
3893
-							$more.='<td><input type="radio" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"'.$moreattr;
3894
-							if ($input['disabled']) $more.=' disabled';
3895
-							$more.=' /> ';
3896
-							$more.=$selval;
3897
-							$more.='</td></tr>'."\n";
3898
-							$i++;
3899
-						}
3900
-					}
3901
-					elseif ($input['type'] == 'date')
3902
-					{
3903
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3904
-						$more.='<td align="left">';
3905
-						$more.=$this->selectDate($input['value'],$input['name'],0,0,0,'',1,0);
3906
-						$more.='</td></tr>'."\n";
3907
-						$formquestion[] = array('name'=>$input['name'].'day');
3908
-						$formquestion[] = array('name'=>$input['name'].'month');
3909
-						$formquestion[] = array('name'=>$input['name'].'year');
3910
-						$formquestion[] = array('name'=>$input['name'].'hour');
3911
-						$formquestion[] = array('name'=>$input['name'].'min');
3912
-					}
3913
-					elseif ($input['type'] == 'other')
3914
-					{
3915
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
3916
-						if (! empty($input['label'])) $more.=$input['label'].'</td><td align="left">';
3917
-						$more.=$input['value'];
3918
-						$more.='</td></tr>'."\n";
3919
-					}
2218
+            $textifempty='';
2219
+            // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
2220
+            //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
2221
+            if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2222
+            {
2223
+                if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
2224
+                else $textifempty.=$langs->trans("All");
2225
+            }
2226
+            if ($showempty) $out.='<option value="0" selected>'.$textifempty.'</option>';
3920 2227
 
3921
-					elseif ($input['type'] == 'onecolumn')
3922
-					{
3923
-						$more.='<tr><td colspan="2" align="left">';
3924
-						$more.=$input['value'];
3925
-						$more.='</td></tr>'."\n";
3926
-					}
3927
-				}
3928
-			}
3929
-			$more.='</table>'."\n";
3930
-		}
3931
-
3932
-		// JQUI method dialog is broken with jmobile, we use standard HTML.
3933
-		// Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx
3934
-		// See page product/card.php for example
3935
-		if (! empty($conf->dol_use_jmobile)) $useajax=0;
3936
-		if (empty($conf->use_javascript_ajax)) $useajax=0;
3937
-
3938
-		if ($useajax)
3939
-		{
3940
-			$autoOpen=true;
3941
-			$dialogconfirm='dialog-confirm';
3942
-			$button='';
3943
-			if (! is_numeric($useajax))
3944
-			{
3945
-				$button=$useajax;
3946
-				$useajax=1;
3947
-				$autoOpen=false;
3948
-				$dialogconfirm.='-'.$button;
3949
-			}
3950
-			$pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes';
3951
-			$pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':'');
3952
-			// Add input fields into list of fields to read during submit (inputok and inputko)
3953
-			if (is_array($formquestion))
3954
-			{
3955
-				foreach ($formquestion as $key => $input)
3956
-				{
3957
-					//print "xx ".$key." rr ".is_array($input)."<br>\n";
3958
-					if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']);
3959
-					if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']);
3960
-				}
3961
-			}
3962
-			// Show JQuery confirm box. Note that global var $useglobalvars is used inside this template
3963
-			$formconfirm.= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
3964
-			if (! empty($more)) {
3965
-				$formconfirm.= '<div class="confirmquestions">'.$more.'</div>';
3966
-			}
3967
-			$formconfirm.= ($question ? '<div class="confirmmessage">'.img_help('','').' '.$question . '</div>': '');
3968
-			$formconfirm.= '</div>'."\n";
3969
-
3970
-			$formconfirm.= "\n<!-- begin ajax formconfirm page=".$page." -->\n";
3971
-			$formconfirm.= '<script type="text/javascript">'."\n";
3972
-			$formconfirm.= 'jQuery(document).ready(function() {
3973
-            $(function() {
3974
-            	$( "#'.$dialogconfirm.'" ).dialog(
3975
-            	{
3976
-                    autoOpen: '.($autoOpen ? "true" : "false").',';
3977
-			if ($newselectedchoice == 'no')
3978
-			{
3979
-				$formconfirm.='
3980
-						open: function() {
3981
-            				$(this).parent().find("button.ui-button:eq(2)").focus();
3982
-						},';
3983
-			}
3984
-			$formconfirm.='
3985
-                    resizable: false,
3986
-                    height: "'.$height.'",
3987
-                    width: "'.$width.'",
3988
-                    modal: true,
3989
-                    closeOnEscape: false,
3990
-                    buttons: {
3991
-                        "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
3992
-                        	var options="";
3993
-                        	var inputok = '.json_encode($inputok).';
3994
-                         	var pageyes = "'.dol_escape_js(! empty($pageyes)?$pageyes:'').'";
3995
-                         	if (inputok.length>0) {
3996
-                         		$.each(inputok, function(i, inputname) {
3997
-                         			var more = "";
3998
-                         			if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
3999
-                         		    if ($("#" + inputname).attr("type") == "radio") { more = ":checked"; }
4000
-                         			var inputvalue = $("#" + inputname + more).val();
4001
-                         			if (typeof inputvalue == "undefined") { inputvalue=""; }
4002
-                         			options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
4003
-                         		});
4004
-                         	}
4005
-                         	var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
4006
-                         	//alert(urljump);
4007
-            				if (pageyes.length > 0) { location.href = urljump; }
4008
-                            $(this).dialog("close");
4009
-                        },
4010
-                        "'.dol_escape_js($langs->transnoentities("No")).'": function() {
4011
-                        	var options = "";
4012
-                         	var inputko = '.json_encode($inputko).';
4013
-                         	var pageno="'.dol_escape_js(! empty($pageno)?$pageno:'').'";
4014
-                         	if (inputko.length>0) {
4015
-                         		$.each(inputko, function(i, inputname) {
4016
-                         			var more = "";
4017
-                         			if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
4018
-                         			var inputvalue = $("#" + inputname + more).val();
4019
-                         			if (typeof inputvalue == "undefined") { inputvalue=""; }
4020
-                         			options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
4021
-                         		});
4022
-                         	}
4023
-                         	var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
4024
-                         	//alert(urljump);
4025
-            				if (pageno.length > 0) { location.href = urljump; }
4026
-                            $(this).dialog("close");
2228
+            $i = 0;
2229
+            while ($num && $i < $num)
2230
+            {
2231
+                $opt = '';
2232
+                $optJson = array();
2233
+                $objp = $this->db->fetch_object($result);
2234
+
2235
+                if ((!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1)
2236
+                { // Price by quantity will return many prices for the same product
2237
+                    $sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
2238
+                    $sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
2239
+                    $sql.= " WHERE fk_product_price=".$objp->price_rowid;
2240
+                    $sql.= " ORDER BY quantity ASC";
2241
+
2242
+                    dol_syslog(get_class($this)."::select_produits_list search price by qty", LOG_DEBUG);
2243
+                    $result2 = $this->db->query($sql);
2244
+                    if ($result2)
2245
+                    {
2246
+                        $nb_prices = $this->db->num_rows($result2);
2247
+                        $j = 0;
2248
+                        while ($nb_prices && $j < $nb_prices) {
2249
+                            $objp2 = $this->db->fetch_object($result2);
2250
+
2251
+                            $objp->price_by_qty_rowid = $objp2->rowid;
2252
+                            $objp->price_by_qty_price_base_type = $objp2->price_base_type;
2253
+                            $objp->price_by_qty_quantity = $objp2->quantity;
2254
+                            $objp->price_by_qty_unitprice = $objp2->unitprice;
2255
+                            $objp->price_by_qty_remise_percent = $objp2->remise_percent;
2256
+                            // For backward compatibility
2257
+                            $objp->quantity = $objp2->quantity;
2258
+                            $objp->price = $objp2->price;
2259
+                            $objp->unitprice = $objp2->unitprice;
2260
+                            $objp->remise_percent = $objp2->remise_percent;
2261
+                            $objp->remise = $objp2->remise;
2262
+
2263
+                            $this->constructProductListOption($objp, $opt, $optJson, 0, $selected, $hidepriceinlabel);
2264
+
2265
+                            $j++;
2266
+
2267
+                            // Add new entry
2268
+                            // "key" value of json key array is used by jQuery automatically as selected value
2269
+                            // "label" value of json key array is used by jQuery automatically as text for combo box
2270
+                            $out.=$opt;
2271
+                            array_push($outarray, $optJson);
4027 2272
                         }
4028 2273
                     }
4029 2274
                 }
4030
-                );
4031
-
4032
-            	var button = "'.$button.'";
4033
-            	if (button.length > 0) {
4034
-                	$( "#" + button ).click(function() {
4035
-                		$("#'.$dialogconfirm.'").dialog("open");
4036
-        			});
2275
+                else
2276
+                {
2277
+                    if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
2278
+                        $price_product = new Product($this->db);
2279
+                        $price_product->fetch($objp->rowid, '', '', 1);
2280
+                        $priceparser = new PriceParser($this->db);
2281
+                        $price_result = $priceparser->parseProduct($price_product);
2282
+                        if ($price_result >= 0) {
2283
+                            $objp->price = $price_result;
2284
+                            $objp->unitprice = $price_result;
2285
+                            //Calculate the VAT
2286
+                            $objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
2287
+                            $objp->price_ttc = price2num($objp->price_ttc,'MU');
2288
+                        }
2289
+                    }
2290
+                    $this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel);
2291
+                    // Add new entry
2292
+                    // "key" value of json key array is used by jQuery automatically as selected value
2293
+                    // "label" value of json key array is used by jQuery automatically as text for combo box
2294
+                    $out.=$opt;
2295
+                    array_push($outarray, $optJson);
4037 2296
                 }
4038
-            });
4039
-            });
4040
-            </script>';
4041
-			$formconfirm.= "<!-- end ajax formconfirm -->\n";
4042
-		}
4043
-		else
4044
-		{
4045
-			$formconfirm.= "\n<!-- begin formconfirm page=".$page." -->\n";
4046
-
4047
-			if (empty($disableformtag)) $formconfirm.= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
4048 2297
 
4049
-			$formconfirm.= '<input type="hidden" name="action" value="'.$action.'">'."\n";
4050
-			if (empty($disableformtag)) $formconfirm.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
2298
+                $i++;
2299
+            }
4051 2300
 
4052
-			$formconfirm.= '<table width="100%" class="valid">'."\n";
2301
+            $out.='</select>';
4053 2302
 
4054
-			// Line title
4055
-			$formconfirm.= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('','recent').' '.$title.'</td></tr>'."\n";
2303
+            $this->db->free($result);
4056 2304
 
4057
-			// Line form fields
4058
-			if ($more)
4059
-			{
4060
-				$formconfirm.='<tr class="valid"><td class="valid" colspan="3">'."\n";
4061
-				$formconfirm.=$more;
4062
-				$formconfirm.='</td></tr>'."\n";
4063
-			}
2305
+            if (empty($outputmode)) return $out;
2306
+            return $outarray;
2307
+        }
2308
+        else
2309
+        {
2310
+            dol_print_error($db);
2311
+        }
2312
+    }
4064 2313
 
4065
-			// Line with question
4066
-			$formconfirm.= '<tr class="valid">';
4067
-			$formconfirm.= '<td class="valid">'.$question.'</td>';
4068
-			$formconfirm.= '<td class="valid">';
4069
-			$formconfirm.= $this->selectyesno("confirm",$newselectedchoice);
4070
-			$formconfirm.= '</td>';
4071
-			$formconfirm.= '<td class="valid" align="center"><input class="button valignmiddle" type="submit" value="'.$langs->trans("Validate").'"></td>';
4072
-			$formconfirm.= '</tr>'."\n";
2314
+    /**
2315
+     * constructProductListOption
2316
+     *
2317
+     * @param 	resultset	$objp			    Resultset of fetch
2318
+     * @param 	string		$opt			    Option (var used for returned value in string option format)
2319
+     * @param 	string		$optJson		    Option (var used for returned value in json format)
2320
+     * @param 	int			$price_level	    Price level
2321
+     * @param 	string		$selected		    Preselected value
2322
+     * @param   int         $hidepriceinlabel   Hide price in label
2323
+     * @return	void
2324
+     */
2325
+    private function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0)
2326
+    {
2327
+        global $langs,$conf,$user,$db;
2328
+
2329
+        $outkey='';
2330
+        $outval='';
2331
+        $outref='';
2332
+        $outlabel='';
2333
+        $outdesc='';
2334
+        $outbarcode='';
2335
+        $outtype='';
2336
+        $outprice_ht='';
2337
+        $outprice_ttc='';
2338
+        $outpricebasetype='';
2339
+        $outtva_tx='';
2340
+        $outqty=1;
2341
+        $outdiscount=0;
2342
+
2343
+        $maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO);
2344
+
2345
+        $label=$objp->label;
2346
+        if (! empty($objp->label_translated)) $label=$objp->label_translated;
2347
+        if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
2348
+
2349
+        $outkey=$objp->rowid;
2350
+        $outref=$objp->ref;
2351
+        $outlabel=$objp->label;
2352
+        $outdesc=$objp->description;
2353
+        $outbarcode=$objp->barcode;
2354
+
2355
+        $outtype=$objp->fk_product_type;
2356
+        $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
2357
+        $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
2358
+
2359
+        $opt = '<option value="'.$objp->rowid.'"';
2360
+        $opt.= ($objp->rowid == $selected)?' selected':'';
2361
+        if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)
2362
+        {
2363
+            $opt.= ' pbq="'.$objp->price_by_qty_rowid.'" data-pbq="'.$objp->price_by_qty_rowid.'" data-pbqqty="'.$objp->price_by_qty_quantity.'" data-pbqpercent="'.$objp->price_by_qty_remise_percent.'"';
2364
+        }
2365
+        if (! empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))
2366
+        {
2367
+            if ($objp->stock > 0) $opt.= ' class="product_line_stock_ok"';
2368
+            else if ($objp->stock <= 0) $opt.= ' class="product_line_stock_too_low"';
2369
+        }
2370
+        $opt.= '>';
2371
+        $opt.= $objp->ref;
2372
+        if ($outbarcode) $opt.=' ('.$outbarcode.')';
2373
+        $opt.=' - '.dol_trunc($label,$maxlengtharticle);
2374
+
2375
+        $objRef = $objp->ref;
2376
+        if (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2377
+        $outval.=$objRef;
2378
+        if ($outbarcode) $outval.=' ('.$outbarcode.')';
2379
+        $outval.=' - '.dol_trunc($label,$maxlengtharticle);
2380
+
2381
+        $found=0;
2382
+
2383
+        // Multiprice
2384
+        // If we need a particular price level (from 1 to 6)
2385
+        if (empty($hidepriceinlabel) && $price_level >= 1 && (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
2386
+        {
2387
+            $sql = "SELECT price, price_ttc, price_base_type, tva_tx";
2388
+            $sql.= " FROM ".MAIN_DB_PREFIX."product_price";
2389
+            $sql.= " WHERE fk_product='".$objp->rowid."'";
2390
+            $sql.= " AND entity IN (".getEntity('productprice').")";
2391
+            $sql.= " AND price_level=".$price_level;
2392
+            $sql.= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
2393
+            $sql.= " LIMIT 1";
2394
+
2395
+            dol_syslog(get_class($this).'::constructProductListOption search price for level '.$price_level.'', LOG_DEBUG);
2396
+            $result2 = $this->db->query($sql);
2397
+            if ($result2)
2398
+            {
2399
+                $objp2 = $this->db->fetch_object($result2);
2400
+                if ($objp2)
2401
+                {
2402
+                    $found=1;
2403
+                    if ($objp2->price_base_type == 'HT')
2404
+                    {
2405
+                        $opt.= ' - '.price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2406
+                        $outval.= ' - '.price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2407
+                    }
2408
+                    else
2409
+                    {
2410
+                        $opt.= ' - '.price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2411
+                        $outval.= ' - '.price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2412
+                    }
2413
+                    $outprice_ht=price($objp2->price);
2414
+                    $outprice_ttc=price($objp2->price_ttc);
2415
+                    $outpricebasetype=$objp2->price_base_type;
2416
+                    $outtva_tx=$objp2->tva_tx;
2417
+                }
2418
+            }
2419
+            else
2420
+            {
2421
+                dol_print_error($this->db);
2422
+            }
2423
+        }
4073 2424
 
4074
-			$formconfirm.= '</table>'."\n";
2425
+        // Price by quantity
2426
+        if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
2427
+        {
2428
+            $found = 1;
2429
+            $outqty=$objp->quantity;
2430
+            $outdiscount=$objp->remise_percent;
2431
+            if ($objp->quantity == 1)
2432
+            {
2433
+                $opt.= ' - '.price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/";
2434
+                $outval.= ' - '.price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/";
2435
+                $opt.= $langs->trans("Unit");	// Do not use strtolower because it breaks utf8 encoding
2436
+                $outval.=$langs->transnoentities("Unit");
2437
+            }
2438
+            else
2439
+            {
2440
+                $opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2441
+                $outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2442
+                $opt.= $langs->trans("Units");	// Do not use strtolower because it breaks utf8 encoding
2443
+                $outval.=$langs->transnoentities("Units");
2444
+            }
4075 2445
 
4076
-			if (empty($disableformtag)) $formconfirm.= "</form>\n";
4077
-			$formconfirm.= '<br>';
2446
+            $outprice_ht=price($objp->unitprice);
2447
+            $outprice_ttc=price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
2448
+            $outpricebasetype=$objp->price_base_type;
2449
+            $outtva_tx=$objp->tva_tx;
2450
+        }
2451
+        if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)
2452
+        {
2453
+            $opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2454
+            $outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2455
+        }
2456
+        if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)
2457
+        {
2458
+            $opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
2459
+            $outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
2460
+        }
4078 2461
 
4079
-			$formconfirm.= "<!-- end formconfirm -->\n";
4080
-		}
2462
+        // Price by customer
2463
+        if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))
2464
+        {
2465
+            if (!empty($objp->idprodcustprice))
2466
+            {
2467
+                $found = 1;
4081 2468
 
4082
-		return $formconfirm;
4083
-	}
2469
+                if ($objp->custprice_base_type == 'HT')
2470
+                {
2471
+                    $opt.= ' - '.price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2472
+                    $outval.= ' - '.price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2473
+                }
2474
+                else
2475
+                {
2476
+                    $opt.= ' - '.price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2477
+                    $outval.= ' - '.price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2478
+                }
4084 2479
 
2480
+                $outprice_ht=price($objp->custprice);
2481
+                $outprice_ttc=price($objp->custprice_ttc);
2482
+                $outpricebasetype=$objp->custprice_base_type;
2483
+                $outtva_tx=$objp->custtva_tx;
2484
+            }
2485
+        }
4085 2486
 
4086
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4087
-	/**
4088
-	 *    Show a form to select a project
4089
-	 *
4090
-	 *    @param	int		$page        		Page
4091
-	 *    @param	int		$socid       		Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
4092
-	 *    @param    int		$selected    		Id pre-selected project
4093
-	 *    @param    string	$htmlname    		Name of select field
4094
-	 *    @param	int		$discard_closed		Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
4095
-	 *    @param	int		$maxlength			Max length
4096
-	 *    @param	int		$forcefocus			Force focus on field (works with javascript only)
4097
-	 *    @param    int     $nooutput           No print is done. String is returned.
4098
-	 *    @return	string                      Return html content
4099
-	 */
4100
-	function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0)
4101
-	{
4102
-        // phpcs:enable
4103
-		global $langs;
4104
-
4105
-		require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
4106
-		require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
4107
-
4108
-		$out='';
4109
-
4110
-		$formproject=new FormProjets($this->db);
4111
-
4112
-		$langs->load("project");
4113
-		if ($htmlname != "none")
4114
-		{
4115
-			$out.="\n";
4116
-			$out.='<form method="post" action="'.$page.'">';
4117
-			$out.='<input type="hidden" name="action" value="classin">';
4118
-			$out.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4119
-			$out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
4120
-			$out.='<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4121
-			$out.='</form>';
4122
-		}
4123
-		else
4124
-		{
4125
-			if ($selected)
4126
-			{
4127
-				$projet = new Project($this->db);
4128
-				$projet->fetch($selected);
4129
-				//print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
4130
-				$out.=$projet->getNomUrl(0,'',1);
4131
-			}
4132
-			else
4133
-			{
4134
-				$out.="&nbsp;";
4135
-			}
4136
-		}
4137
-
4138
-		if (empty($nooutput))
4139
-		{
4140
-			print $out;
4141
-			return '';
4142
-		}
4143
-		return $out;
4144
-	}
2487
+        // If level no defined or multiprice not found, we used the default price
2488
+        if (empty($hidepriceinlabel) && ! $found)
2489
+        {
2490
+            if ($objp->price_base_type == 'HT')
2491
+            {
2492
+                $opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2493
+                $outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2494
+            }
2495
+            else
2496
+            {
2497
+                $opt.= ' - '.price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2498
+                $outval.= ' - '.price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2499
+            }
2500
+            $outprice_ht=price($objp->price);
2501
+            $outprice_ttc=price($objp->price_ttc);
2502
+            $outpricebasetype=$objp->price_base_type;
2503
+            $outtva_tx=$objp->tva_tx;
2504
+        }
4145 2505
 
4146
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4147
-	/**
4148
-	 *	Show a form to select payment conditions
4149
-	 *
4150
-	 *  @param	int		$page        	Page
4151
-	 *  @param  string	$selected    	Id condition pre-selectionne
4152
-	 *  @param  string	$htmlname    	Name of select html field
4153
-	 *	@param	int		$addempty		Add empty entry
4154
-	 *  @return	void
4155
-	 */
4156
-	function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0)
4157
-	{
4158
-        // phpcs:enable
4159
-		global $langs;
4160
-		if ($htmlname != "none")
4161
-		{
4162
-			print '<form method="post" action="'.$page.'">';
4163
-			print '<input type="hidden" name="action" value="setconditions">';
4164
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4165
-			$this->select_conditions_paiements($selected,$htmlname,-1,$addempty);
4166
-			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4167
-			print '</form>';
4168
-		}
4169
-		else
4170
-		{
4171
-			if ($selected)
4172
-			{
4173
-				$this->load_cache_conditions_paiements();
4174
-				print $this->cache_conditions_paiements[$selected]['label'];
4175
-			} else {
4176
-				print "&nbsp;";
4177
-			}
4178
-		}
4179
-	}
2506
+        if (! empty($conf->stock->enabled) && isset($objp->stock) && $objp->fk_product_type == 0)
2507
+        {
2508
+            $opt.= ' - '.$langs->trans("Stock").':'.$objp->stock;
4180 2509
 
4181
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4182
-	/**
4183
-	 *  Show a form to select a delivery delay
4184
-	 *
4185
-	 *  @param  int		$page        	Page
4186
-	 *  @param  string	$selected    	Id condition pre-selectionne
4187
-	 *  @param  string	$htmlname    	Name of select html field
4188
-	 *	@param	int		$addempty		Ajoute entree vide
4189
-	 *  @return	void
4190
-	 */
4191
-	function form_availability($page, $selected='', $htmlname='availability', $addempty=0)
4192
-	{
4193
-        // phpcs:enable
4194
-		global $langs;
4195
-		if ($htmlname != "none")
4196
-		{
4197
-			print '<form method="post" action="'.$page.'">';
4198
-			print '<input type="hidden" name="action" value="setavailability">';
4199
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4200
-			$this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty);
4201
-			print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4202
-			print '</form>';
4203
-		}
4204
-		else
4205
-		{
4206
-			if ($selected)
4207
-			{
4208
-				$this->load_cache_availability();
4209
-				print $this->cache_availability[$selected]['label'];
4210
-			} else {
4211
-				print "&nbsp;";
4212
-			}
4213
-		}
4214
-	}
4215
-
4216
-	/**
4217
-	 *	Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
4218
-	 *  List found into table c_input_reason loaded by loadCacheInputReason
4219
-	 *
4220
-	 *  @param  string	$page        	Page
4221
-	 *  @param  string	$selected    	Id condition pre-selectionne
4222
-	 *  @param  string	$htmlname    	Name of select html field
4223
-	 *	@param	int		$addempty		Add empty entry
4224
-	 *  @return	void
4225
-	 */
4226
-	function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0)
4227
-	{
4228
-		global $langs;
4229
-		if ($htmlname != "none")
4230
-		{
4231
-			print '<form method="post" action="'.$page.'">';
4232
-			print '<input type="hidden" name="action" value="setdemandreason">';
4233
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4234
-			$this->selectInputReason($selected,$htmlname,-1,$addempty);
4235
-			print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4236
-			print '</form>';
4237
-		}
4238
-		else
4239
-		{
4240
-			if ($selected)
4241
-			{
4242
-				$this->loadCacheInputReason();
4243
-				foreach ($this->cache_demand_reason as $key => $val)
4244
-				{
4245
-					if ($val['id'] == $selected)
4246
-					{
4247
-						print $val['label'];
4248
-						break;
4249
-					}
4250
-				}
4251
-			} else {
4252
-				print "&nbsp;";
4253
-			}
4254
-		}
4255
-	}
2510
+            if ($objp->stock > 0) {
2511
+                $outval.= ' - <span class="product_line_stock_ok">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2512
+            }elseif ($objp->stock <= 0) {
2513
+                $outval.= ' - <span class="product_line_stock_too_low">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2514
+            }
2515
+        }
4256 2516
 
4257
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4258
-	/**
4259
-	 *    Show a form + html select a date
4260
-	 *
4261
-	 *    @param	string		$page        	Page
4262
-	 *    @param	string		$selected    	Date preselected
4263
-	 *    @param    string		$htmlname    	Html name of date input fields or 'none'
4264
-	 *    @param    int			$displayhour 	Display hour selector
4265
-	 *    @param    int			$displaymin		Display minutes selector
4266
-	 *    @param	int			$nooutput		1=No print output, return string
4267
-	 *    @return	string
4268
-	 *    @see		selectDate
4269
-	 */
4270
-	function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0)
4271
-	{
4272
-        // phpcs:enable
4273
-		global $langs;
4274
-
4275
-		$ret='';
4276
-
4277
-		if ($htmlname != "none")
4278
-		{
4279
-			$ret.='<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
4280
-			$ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
4281
-			$ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4282
-			$ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
4283
-			$ret.='<tr><td>';
4284
-			$ret.=$this->selectDate($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0);
4285
-			$ret.='</td>';
4286
-			$ret.='<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
4287
-			$ret.='</tr></table></form>';
4288
-		}
4289
-		else
4290
-		{
4291
-			if ($displayhour) $ret.=dol_print_date($selected,'dayhour');
4292
-			else $ret.=dol_print_date($selected,'day');
4293
-		}
4294
-
4295
-		if (empty($nooutput)) print $ret;
4296
-		return $ret;
4297
-	}
2517
+        if ($outdurationvalue && $outdurationunit)
2518
+        {
2519
+            $da=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("Day"),"w"=>$langs->trans("Week"),"m"=>$langs->trans("Month"),"y"=>$langs->trans("Year"));
2520
+            if (isset($da[$outdurationunit]))
2521
+            {
2522
+                $key = $da[$outdurationunit].($outdurationvalue > 1?'s':'');
2523
+                $opt.= ' - '.$outdurationvalue.' '.$langs->trans($key);
2524
+                $outval.=' - '.$outdurationvalue.' '.$langs->transnoentities($key);
2525
+            }
2526
+        }
4298 2527
 
2528
+        $opt.= "</option>\n";
2529
+        $optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>$outprice_ht, 'price_ttc'=>$outprice_ttc, 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit);
2530
+    }
4299 2531
 
4300 2532
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4301
-	/**
4302
-	 *  Show a select form to choose a user
4303
-	 *
4304
-	 *  @param	string	$page        	Page
4305
-	 *  @param  string	$selected    	Id of user preselected
4306
-	 *  @param  string	$htmlname    	Name of input html field. If 'none', we just output the user link.
4307
-	 *  @param  array	$exclude		List of users id to exclude
4308
-	 *  @param  array	$include        List of users id to include
4309
-	 *  @return	void
4310
-	 */
4311
-	function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='')
4312
-	{
2533
+    /**
2534
+     *	Return list of products for customer (in Ajax if Ajax activated or go to select_produits_fournisseurs_list)
2535
+     *
2536
+     *	@param	int		$socid			Id third party
2537
+     *	@param  string	$selected       Preselected product
2538
+     *	@param  string	$htmlname       Name of HTML Select
2539
+     *  @param	string	$filtertype     Filter on product type (''=nofilter, 0=product, 1=service)
2540
+     *	@param  string	$filtre			For a SQL filter
2541
+     *	@param	array	$ajaxoptions	Options for ajax_autocompleter
2542
+     *  @param	int		$hidelabel		Hide label (0=no, 1=yes)
2543
+     *  @param  int     $alsoproductwithnosupplierprice    1=Add also product without supplier prices
2544
+     *	@return	void
2545
+     */
2546
+    function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0)
2547
+    {
4313 2548
         // phpcs:enable
4314
-		global $langs;
4315
-
4316
-		if ($htmlname != "none")
4317
-		{
4318
-			print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
4319
-			print '<input type="hidden" name="action" value="set'.$htmlname.'">';
4320
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4321
-			print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include);
4322
-			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4323
-			print '</form>';
4324
-		}
4325
-		else
4326
-		{
4327
-			if ($selected)
4328
-			{
4329
-				require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';
4330
-				$theuser=new User($this->db);
4331
-				$theuser->fetch($selected);
4332
-				print $theuser->getNomUrl(1);
4333
-			} else {
4334
-				print "&nbsp;";
4335
-			}
4336
-		}
4337
-	}
2549
+        global $langs,$conf;
2550
+        global $price_level, $status, $finished;
4338 2551
 
2552
+        $selected_input_value='';
2553
+        if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2554
+        {
2555
+            if ($selected > 0)
2556
+            {
2557
+                require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2558
+                $producttmpselect = new Product($this->db);
2559
+                $producttmpselect->fetch($selected);
2560
+                $selected_input_value=$producttmpselect->ref;
2561
+                unset($producttmpselect);
2562
+            }
4339 2563
 
4340
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4341
-	/**
4342
-	 *    Show form with payment mode
4343
-	 *
4344
-	 *    @param	string	$page        	Page
4345
-	 *    @param    int		$selected    	Id mode pre-selectionne
4346
-	 *    @param    string	$htmlname    	Name of select html field
4347
-	 *    @param  	string	$filtertype		To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
4348
-	 *    @param    int     $active         Active or not, -1 = all
4349
-	 *    @return	void
4350
-	 */
4351
-	function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1)
4352
-	{
4353
-        // phpcs:enable
4354
-		global $langs;
4355
-		if ($htmlname != "none")
4356
-		{
4357
-			print '<form method="POST" action="'.$page.'">';
4358
-			print '<input type="hidden" name="action" value="setmode">';
4359
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4360
-			$this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active);
4361
-			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4362
-			print '</form>';
4363
-		}
4364
-		else
4365
-		{
4366
-			if ($selected)
4367
-			{
4368
-				$this->load_cache_types_paiements();
4369
-				print $this->cache_types_paiements[$selected]['label'];
4370
-			} else {
4371
-				print "&nbsp;";
4372
-			}
4373
-		}
4374
-	}
2564
+            // mode=2 means suppliers products
2565
+            $urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
2566
+            print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
2567
+            print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
2568
+        }
2569
+        else
2570
+        {
2571
+            print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice);
2572
+        }
2573
+    }
4375 2574
 
4376 2575
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4377
-	/**
4378
-	 *    Show form with multicurrency code
4379
-	 *
4380
-	 *    @param	string	$page        	Page
4381
-	 *    @param    string	$selected    	code pre-selectionne
4382
-	 *    @param    string	$htmlname    	Name of select html field
4383
-	 *    @return	void
4384
-	 */
4385
-	function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code')
4386
-	{
2576
+    /**
2577
+     *	Return list of suppliers products
2578
+     *
2579
+     *	@param	int		$socid   		Id societe fournisseur (0 pour aucun filtre)
2580
+     *	@param  int		$selected       Product price pre-selected (must be 'id' in product_fournisseur_price or 'idprod_IDPROD')
2581
+     *	@param  string	$htmlname       Nom de la zone select
2582
+     *  @param	string	$filtertype     Filter on product type (''=nofilter, 0=product, 1=service)
2583
+     *	@param  string	$filtre         Pour filtre sql
2584
+     *	@param  string	$filterkey      Filtre des produits
2585
+     *  @param  int		$statut         -1=Return all products, 0=Products not on sell, 1=Products on sell (not used here, a filter on tobuy is already hard coded in request)
2586
+     *  @param  int		$outputmode     0=HTML select string, 1=Array
2587
+     *  @param  int     $limit          Limit of line number
2588
+     *  @param  int     $alsoproductwithnosupplierprice    1=Add also product without supplier prices
2589
+     *  @return array           		Array of keys for json
2590
+     */
2591
+    function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0)
2592
+    {
4387 2593
         // phpcs:enable
4388
-		global $langs;
4389
-		if ($htmlname != "none")
4390
-		{
4391
-			print '<form method="POST" action="'.$page.'">';
4392
-			print '<input type="hidden" name="action" value="setmulticurrencycode">';
4393
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4394
-			print $this->selectMultiCurrency($selected, $htmlname, 0);
4395
-			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4396
-			print '</form>';
4397
-		}
4398
-		else
4399
-		{
4400
-			dol_include_once('/core/lib/company.lib.php');
4401
-			print !empty($selected) ? currency_name($selected,1) : '&nbsp;';
4402
-		}
4403
-	}
2594
+        global $langs,$conf,$db;
2595
+
2596
+        $out='';
2597
+        $outarray=array();
2598
+
2599
+        $langs->load('stocks');
2600
+
2601
+        $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,";
2602
+        $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
2603
+        $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
2604
+        $sql.= " pfp.supplier_reputation";
2605
+        $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2606
+        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2607
+        if ($socid) $sql.= " AND pfp.fk_soc = ".$socid;
2608
+        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2609
+        $sql.= " WHERE p.entity IN (".getEntity('product').")";
2610
+        $sql.= " AND p.tobuy = 1";
2611
+        if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype);
2612
+        if (! empty($filtre)) $sql.=" ".$filtre;
2613
+        // Add criteria on ref/label
2614
+        if ($filterkey != '')
2615
+        {
2616
+            $sql.=' AND (';
2617
+            $prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2618
+            // For natural search
2619
+            $scrit = explode(' ', $filterkey);
2620
+            $i=0;
2621
+            if (count($scrit) > 1) $sql.="(";
2622
+            foreach ($scrit as $crit)
2623
+            {
2624
+                if ($i > 0) $sql.=" AND ";
2625
+                $sql.="(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')";
2626
+                $i++;
2627
+            }
2628
+            if (count($scrit) > 1) $sql.=")";
2629
+            if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
2630
+            $sql.=')';
2631
+        }
2632
+        $sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
2633
+        $sql.= $db->plimit($limit, 0);
2634
+
2635
+        // Build output string
2636
+
2637
+        dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
2638
+        $result=$this->db->query($sql);
2639
+        if ($result)
2640
+        {
2641
+            require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2642
+
2643
+            $num = $this->db->num_rows($result);
2644
+
2645
+            //$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">';	// remove select to have id same with combo and ajax
2646
+            $out.='<select class="flat maxwidthonsmartphone" id="'.$htmlname.'" name="'.$htmlname.'">';
2647
+            if (! $selected) $out.='<option value="0" selected>&nbsp;</option>';
2648
+            else $out.='<option value="0">&nbsp;</option>';
2649
+
2650
+            $i = 0;
2651
+            while ($i < $num)
2652
+            {
2653
+                $objp = $this->db->fetch_object($result);
2654
+
2655
+                $outkey=$objp->idprodfournprice;                                                    // id in table of price
2656
+                if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid;   // id of product
2657
+
2658
+                $outref=$objp->ref;
2659
+                $outval='';
2660
+                $outqty=1;
2661
+                $outdiscount=0;
2662
+                $outtype=$objp->fk_product_type;
2663
+                $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
2664
+                $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
2665
+
2666
+                $opt = '<option value="'.$outkey.'"';
2667
+                if ($selected && $selected == $objp->idprodfournprice) $opt.= ' selected';
2668
+                if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt.=' disabled';
2669
+                if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0)
2670
+                {
2671
+                    $opt.= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqpercent="'.$objp->remise_percent.'"';
2672
+                }
2673
+                $opt.= '>';
2674
+
2675
+                $objRef = $objp->ref;
2676
+                if ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2677
+                $objRefFourn = $objp->ref_fourn;
2678
+                if ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);
2679
+                $label = $objp->label;
2680
+                if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
2681
+
2682
+                $opt.=$objp->ref;
2683
+                if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2684
+                    $opt.=' ('.$objp->ref_fourn.')';
2685
+                $opt.=' - ';
2686
+                $outval.=$objRef;
2687
+                if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2688
+                    $outval.=' ('.$objRefFourn.')';
2689
+                $outval.=' - ';
2690
+                $opt.=dol_trunc($label, 72).' - ';
2691
+                $outval.=dol_trunc($label, 72).' - ';
2692
+
2693
+                if (! empty($objp->idprodfournprice))
2694
+                {
2695
+                    $outqty=$objp->quantity;
2696
+                    $outdiscount=$objp->remise_percent;
2697
+                    if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
2698
+                        $prod_supplier = new ProductFournisseur($this->db);
2699
+                        $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
2700
+                        $prod_supplier->id = $objp->fk_product;
2701
+                        $prod_supplier->fourn_qty = $objp->quantity;
2702
+                        $prod_supplier->fourn_tva_tx = $objp->tva_tx;
2703
+                        $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
2704
+                        $priceparser = new PriceParser($this->db);
2705
+                        $price_result = $priceparser->parseProductSupplier($prod_supplier);
2706
+                        if ($price_result >= 0) {
2707
+                            $objp->fprice = $price_result;
2708
+                            if ($objp->quantity >= 1)
2709
+                            {
2710
+                                $objp->unitprice = $objp->fprice / $objp->quantity;
2711
+                            }
2712
+                        }
2713
+                    }
2714
+                    if ($objp->quantity == 1)
2715
+                    {
2716
+                        $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
2717
+                        $outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/";
2718
+                        $opt.= $langs->trans("Unit");	// Do not use strtolower because it breaks utf8 encoding
2719
+                        $outval.=$langs->transnoentities("Unit");
2720
+                    }
2721
+                    else
2722
+                    {
2723
+                        $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2724
+                        $outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2725
+                        $opt.= ' '.$langs->trans("Units");	// Do not use strtolower because it breaks utf8 encoding
2726
+                        $outval.= ' '.$langs->transnoentities("Units");
2727
+                    }
2728
+
2729
+                    if ($objp->quantity >= 1)
2730
+                    {
2731
+                        $opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2732
+                        $outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2733
+                    }
2734
+                    if ($objp->remise_percent >= 1)
2735
+                    {
2736
+                        $opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
2737
+                        $outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
2738
+                    }
2739
+                    if ($objp->duration)
2740
+                    {
2741
+                        $opt .= " - ".$objp->duration;
2742
+                        $outval.=" - ".$objp->duration;
2743
+                    }
2744
+                    if (! $socid)
2745
+                    {
2746
+                        $opt .= " - ".dol_trunc($objp->name,8);
2747
+                        $outval.=" - ".dol_trunc($objp->name,8);
2748
+                    }
2749
+                    if ($objp->supplier_reputation)
2750
+                    {
2751
+                        //TODO dictionary
2752
+                        $reputations=array(''=>$langs->trans('Standard'),'FAVORITE'=>$langs->trans('Favorite'),'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
2753
+
2754
+                        $opt .= " - ".$reputations[$objp->supplier_reputation];
2755
+                        $outval.=" - ".$reputations[$objp->supplier_reputation];
2756
+                    }
2757
+                }
2758
+                else
2759
+                {
2760
+                    if (empty($alsoproductwithnosupplierprice))     // No supplier price defined for couple product/supplier
2761
+                    {
2762
+                        $opt.= $langs->trans("NoPriceDefinedForThisSupplier");
2763
+                        $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
2764
+                    }
2765
+                    else                                            // No supplier price defined for product, even on other suppliers
2766
+                    {
2767
+                        $opt.= $langs->trans("NoPriceDefinedForThisSupplier");
2768
+                        $outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
2769
+                    }
2770
+                }
2771
+                $opt .= "</option>\n";
2772
+
2773
+
2774
+                // Add new entry
2775
+                // "key" value of json key array is used by jQuery automatically as selected value
2776
+                // "label" value of json key array is used by jQuery automatically as text for combo box
2777
+                $out.=$opt;
2778
+                array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false)));
2779
+                // Exemple of var_dump $outarray
2780
+                // array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
2781
+                //           ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
2782
+                //      	 ["qty"]=>string(1) "1" ["discount"]=>string(1) "0" ["disabled"]=>bool(false)
2783
+                //}
2784
+                //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
2785
+                //$outval=array('label'=>'ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/ Unité (20,00 Euros/unité)');
2786
+                //var_dump($outval); var_dump(utf8_check($outval)); var_dump(json_encode($outval));
2787
+
2788
+                $i++;
2789
+            }
2790
+            $out.='</select>';
2791
+
2792
+            $this->db->free($result);
2793
+
2794
+            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2795
+            $out.=ajax_combobox($htmlname);
2796
+
2797
+            if (empty($outputmode)) return $out;
2798
+            return $outarray;
2799
+        }
2800
+        else
2801
+        {
2802
+            dol_print_error($this->db);
2803
+        }
2804
+    }
4404 2805
 
4405 2806
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4406
-	/**
4407
-	 *    Show form with multicurrency rate
4408
-	 *
4409
-	 *    @param	string	$page        	Page
4410
-	 *    @param    double	$rate	    	Current rate
4411
-	 *    @param    string	$htmlname    	Name of select html field
4412
-	 *    @param    string  $currency       Currency code to explain the rate
4413
-	 *    @return	void
4414
-	 */
4415
-	function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='')
4416
-	{
2807
+    /**
2808
+     *	Return list of suppliers prices for a product
2809
+     *
2810
+     *  @param	    int		$productid       	Id of product
2811
+     *  @param      string	$htmlname        	Name of HTML field
2812
+     *  @param      int		$selected_supplier  Pre-selected supplier if more than 1 result
2813
+     *  @return	    void
2814
+     */
2815
+    function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='')
2816
+    {
4417 2817
         // phpcs:enable
4418
-		global $langs, $mysoc, $conf;
4419
-
4420
-		if ($htmlname != "none")
4421
-		{
4422
-			print '<form method="POST" action="'.$page.'">';
4423
-			print '<input type="hidden" name="action" value="setmulticurrencyrate">';
4424
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4425
-			print '<input type="text" name="'.$htmlname.'" value="'.(!empty($rate) ? price($rate) : 1).'" size="10" /> ';
4426
-			print '<select name="calculation_mode">';
4427
-			print '<option value="1">'.$currency.' > '.$conf->currency.'</option>';
4428
-			print '<option value="2">'.$conf->currency.' > '.$currency.'</option>';
4429
-			print '</select> ';
4430
-			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4431
-			print '</form>';
4432
-		}
4433
-		else
4434
-		{
4435
-			if (! empty($rate))
4436
-			{
4437
-				print price($rate, 1, $langs, 1, 0);
4438
-				if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
4439
-			}
4440
-			else
4441
-			{
4442
-				print 1;
4443
-			}
4444
-		}
4445
-	}
2818
+        global $langs,$conf;
2819
+
2820
+        $langs->load('stocks');
2821
+
2822
+        $sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,";
2823
+        $sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,";
2824
+        $sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
2825
+        $sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2826
+        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2827
+        $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2828
+        $sql.= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
2829
+        $sql.= " AND p.tobuy = 1";
2830
+        $sql.= " AND s.fournisseur = 1";
2831
+        $sql.= " AND p.rowid = ".$productid;
2832
+        $sql.= " ORDER BY s.nom, pfp.ref_fourn DESC";
2833
+
2834
+        dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
2835
+        $result=$this->db->query($sql);
2836
+
2837
+        if ($result)
2838
+        {
2839
+            $num = $this->db->num_rows($result);
2840
+
2841
+            $form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
2842
+
2843
+            if (! $num)
2844
+            {
2845
+                $form.= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
2846
+            }
2847
+            else
2848
+            {
2849
+                require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2850
+                $form.= '<option value="0">&nbsp;</option>';
2851
+
2852
+                $i = 0;
2853
+                while ($i < $num)
2854
+                {
2855
+                    $objp = $this->db->fetch_object($result);
2856
+
2857
+                    $opt = '<option value="'.$objp->idprodfournprice.'"';
2858
+                    //if there is only one supplier, preselect it
2859
+                    if($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
2860
+                        $opt .= ' selected';
2861
+                    }
2862
+                    $opt.= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
2863
+
2864
+                    if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
2865
+                        $prod_supplier = new ProductFournisseur($this->db);
2866
+                        $prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
2867
+                        $prod_supplier->id = $productid;
2868
+                        $prod_supplier->fourn_qty = $objp->quantity;
2869
+                        $prod_supplier->fourn_tva_tx = $objp->tva_tx;
2870
+                        $prod_supplier->fk_supplier_price_expression = $objp->fk_supplier_price_expression;
2871
+                        $priceparser = new PriceParser($this->db);
2872
+                        $price_result = $priceparser->parseProductSupplier($prod_supplier);
2873
+                        if ($price_result >= 0) {
2874
+                            $objp->fprice = $price_result;
2875
+                            if ($objp->quantity >= 1)
2876
+                            {
2877
+                                $objp->unitprice = $objp->fprice / $objp->quantity;
2878
+                            }
2879
+                        }
2880
+                    }
2881
+                    if ($objp->quantity == 1)
2882
+                    {
2883
+                        $opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
2884
+                    }
2885
+
2886
+                    $opt.= $objp->quantity.' ';
2887
+
2888
+                    if ($objp->quantity == 1)
2889
+                    {
2890
+                        $opt.= $langs->trans("Unit");
2891
+                    }
2892
+                    else
2893
+                    {
2894
+                        $opt.= $langs->trans("Units");
2895
+                    }
2896
+                    if ($objp->quantity > 1)
2897
+                    {
2898
+                        $opt.=" - ";
2899
+                        $opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit");
2900
+                    }
2901
+                    if ($objp->duration) $opt .= " - ".$objp->duration;
2902
+                    $opt .= "</option>\n";
2903
+
2904
+                    $form.= $opt;
2905
+                    $i++;
2906
+                }
2907
+            }
4446 2908
 
2909
+            $form.= '</select>';
2910
+            $this->db->free($result);
2911
+            return $form;
2912
+        }
2913
+        else
2914
+        {
2915
+            dol_print_error($this->db);
2916
+        }
2917
+    }
4447 2918
 
4448 2919
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4449
-	/**
4450
-	 *	Show a select box with available absolute discounts
4451
-	 *
4452
-	 *  @param  string	$page        	Page URL where form is shown
4453
-	 *  @param  int		$selected    	Value pre-selected
4454
-	 *	@param  string	$htmlname    	Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
4455
-	 *	@param	int		$socid			Third party id
4456
-	 * 	@param	float	$amount			Total amount available
4457
-	 * 	@param	string	$filter			SQL filter on discounts
4458
-	 * 	@param	int		$maxvalue		Max value for lines that can be selected
4459
-	 *  @param  string	$more           More string to add
4460
-	 *  @param  int     $hidelist       1=Hide list
4461
-	 *  @param	int		$discount_type	0 => customer discount, 1 => supplier discount
4462
-	 *  @return	void
4463
-	 */
4464
-	function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $discount_type=0)
4465
-	{
2920
+    /**
2921
+     *    Return list of delivery address
2922
+     *
2923
+     *    @param    string	$selected          	Id contact pre-selectionn
2924
+     *    @param    int		$socid				Id of company
2925
+     *    @param    string	$htmlname          	Name of HTML field
2926
+     *    @param    int		$showempty         	Add an empty field
2927
+     *    @return	integer|null
2928
+     */
2929
+    function select_address($selected, $socid, $htmlname='address_id',$showempty=0)
2930
+    {
4466 2931
         // phpcs:enable
4467
-		global $conf,$langs;
4468
-		if ($htmlname != "none")
4469
-		{
4470
-			print '<form method="post" action="'.$page.'">';
4471
-			print '<input type="hidden" name="action" value="setabsolutediscount">';
4472
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4473
-			print '<div class="inline-block">';
4474
-			if(! empty($discount_type)) {
4475
-				if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4476
-				{
4477
-					if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier';    // If we want deposit to be substracted to payments only and not to total of final invoice
4478
-					else $translationKey = 'HasCreditNoteFromSupplier';
4479
-				}
4480
-				else
4481
-				{
4482
-					if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier';
4483
-					else $translationKey = 'HasCreditNoteFromSupplier';
4484
-				}
4485
-			} else {
4486
-				if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4487
-				{
4488
-					if (! $filter || $filter=="fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount';    // If we want deposit to be substracted to payments only and not to total of final invoice
4489
-					else $translationKey = 'CompanyHasCreditNote';
4490
-				}
4491
-				else
4492
-				{
4493
-					if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount';
4494
-					else $translationKey = 'CompanyHasCreditNote';
4495
-				}
4496
-			}
4497
-			print $langs->trans($translationKey,price($amount,0,$langs,0,0,-1,$conf->currency));
4498
-			if (empty($hidelist)) print ': ';
4499
-			print '</div>';
4500
-			if (empty($hidelist))
4501
-			{
4502
-				print '<div class="inline-block" style="padding-right: 10px">';
4503
-				$newfilter = 'discount_type='.intval($discount_type);
4504
-				if(! empty($discount_type)) {
4505
-					$newfilter.= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
4506
-				} else {
4507
-					$newfilter.= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
4508
-				}
4509
-				if ($filter) $newfilter.=' AND ('.$filter.')';
4510
-				$nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);
4511
-				if ($nbqualifiedlines > 0)
4512
-				{
4513
-					print ' &nbsp; <input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
4514
-					if(! empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')")
4515
-						print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4516
-					if(empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')")
4517
-						print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4518
-
4519
-					print '>';
4520
-				}
4521
-				print '</div>';
4522
-			}
4523
-			if ($more)
4524
-			{
4525
-				print '<div class="inline-block">';
4526
-				print $more;
4527
-				print '</div>';
4528
-			}
4529
-			print '</form>';
4530
-		}
4531
-		else
4532
-		{
4533
-			if ($selected)
4534
-			{
4535
-				print $selected;
4536
-			}
4537
-			else
4538
-			{
4539
-				print "0";
4540
-			}
4541
-		}
4542
-	}
2932
+        // looking for users
2933
+        $sql = "SELECT a.rowid, a.label";
2934
+        $sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a";
2935
+        $sql .= " WHERE a.fk_soc = ".$socid;
2936
+        $sql .= " ORDER BY a.label ASC";
2937
+
2938
+        dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
2939
+        $resql=$this->db->query($sql);
2940
+        if ($resql)
2941
+        {
2942
+            print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
2943
+            if ($showempty) print '<option value="0">&nbsp;</option>';
2944
+            $num = $this->db->num_rows($resql);
2945
+            $i = 0;
2946
+            if ($num)
2947
+            {
2948
+                while ($i < $num)
2949
+                {
2950
+                    $obj = $this->db->fetch_object($resql);
2951
+
2952
+                    if ($selected && $selected == $obj->rowid)
2953
+                    {
2954
+                        print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
2955
+                    }
2956
+                    else
2957
+                    {
2958
+                        print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
2959
+                    }
2960
+                    $i++;
2961
+                }
2962
+            }
2963
+            print '</select>';
2964
+            return $num;
2965
+        }
2966
+        else
2967
+        {
2968
+            dol_print_error($this->db);
2969
+        }
2970
+    }
4543 2971
 
4544 2972
 
4545 2973
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4546
-	/**
4547
-	 *    Show forms to select a contact
4548
-	 *
4549
-	 *    @param	string		$page        	Page
4550
-	 *    @param	Societe		$societe		Filter on third party
4551
-	 *    @param    int			$selected    	Id contact pre-selectionne
4552
-	 *    @param    string		$htmlname    	Name of HTML select. If 'none', we just show contact link.
4553
-	 *    @return	void
4554
-	 */
4555
-	function form_contacts($page, $societe, $selected='', $htmlname='contactid')
4556
-	{
2974
+    /**
2975
+     *      Load into cache list of payment terms
2976
+     *
2977
+     *      @return     int             Nb of lines loaded, <0 if KO
2978
+     */
2979
+    function load_cache_conditions_paiements()
2980
+    {
4557 2981
         // phpcs:enable
4558
-		global $langs, $conf;
4559
-
4560
-		if ($htmlname != "none")
4561
-		{
4562
-			print '<form method="post" action="'.$page.'">';
4563
-			print '<input type="hidden" name="action" value="set_contact">';
4564
-			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4565
-			print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
4566
-			print '<tr><td>';
4567
-			$num=$this->select_contacts($societe->id, $selected, $htmlname);
4568
-			if ($num==0)
4569
-			{
4570
-				$addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
4571
-				print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
4572
-			}
4573
-			print '</td>';
4574
-			print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
4575
-			print '</tr></table></form>';
4576
-		}
4577
-		else
4578
-		{
4579
-			if ($selected)
4580
-			{
4581
-				require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php';
4582
-				$contact=new Contact($this->db);
4583
-				$contact->fetch($selected);
4584
-				print $contact->getFullName($langs);
4585
-			} else {
4586
-				print "&nbsp;";
4587
-			}
4588
-		}
4589
-	}
2982
+        global $langs;
2983
+
2984
+        $num = count($this->cache_conditions_paiements);
2985
+        if ($num > 0) return 0;    // Cache already loaded
2986
+
2987
+        dol_syslog(__METHOD__, LOG_DEBUG);
2988
+
2989
+        $sql = "SELECT rowid, code, libelle as label";
2990
+        $sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
2991
+        $sql.= " WHERE entity IN (".getEntity('c_payment_term').")";
2992
+        $sql.= " AND active > 0";
2993
+        $sql.= " ORDER BY sortorder";
2994
+
2995
+        $resql = $this->db->query($sql);
2996
+        if ($resql)
2997
+        {
2998
+            $num = $this->db->num_rows($resql);
2999
+            $i = 0;
3000
+            while ($i < $num)
3001
+            {
3002
+                $obj = $this->db->fetch_object($resql);
3003
+
3004
+                // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3005
+                $label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:''));
3006
+                $this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code;
3007
+                $this->cache_conditions_paiements[$obj->rowid]['label']=$label;
3008
+                $i++;
3009
+            }
3010
+
3011
+            //$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1);		// We use the field sortorder of table
3012
+
3013
+            return $num;
3014
+        }
3015
+        else
3016
+        {
3017
+            dol_print_error($this->db);
3018
+            return -1;
3019
+        }
3020
+    }
4590 3021
 
4591 3022
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4592
-	/**
4593
-	 *  Output html select to select thirdparty
4594
-	 *
4595
-	 *  @param	string	$page       	Page
4596
-	 *  @param  string	$selected   	Id preselected
4597
-	 *  @param  string	$htmlname		Name of HTML select
4598
-	 *  @param  string	$filter         optional filters criteras
4599
-	 *	@param	int		$showempty		Add an empty field
4600
-	 * 	@param	int		$showtype		Show third party type in combolist (customer, prospect or supplier)
4601
-	 * 	@param	int		$forcecombo		Force to use combo box
4602
-	 *  @param	array	$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
4603
-	 *  @param  int     $nooutput       No print output. Return it only.
4604
-	 *  @return	void
4605
-	 */
4606
-	function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array(), $nooutput=0)
4607
-	{
3023
+    /**
3024
+     *      Charge dans cache la liste des délais de livraison possibles
3025
+     *
3026
+     *      @return     int             Nb of lines loaded, <0 if KO
3027
+     */
3028
+    function load_cache_availability()
3029
+    {
4608 3030
         // phpcs:enable
4609
-		global $langs;
4610
-
4611
-		$out = '';
4612
-		if ($htmlname != "none")
4613
-		{
4614
-			$out.='<form method="post" action="'.$page.'">';
4615
-			$out.= '<input type="hidden" name="action" value="set_thirdparty">';
4616
-			$out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4617
-			$out.= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
4618
-			$out.= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4619
-			$out.= '</form>';
4620
-		}
4621
-		else
4622
-		{
4623
-			if ($selected)
4624
-			{
4625
-				require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
4626
-				$soc = new Societe($this->db);
4627
-				$soc->fetch($selected);
4628
-				$out.= $soc->getNomUrl($langs);
4629
-			}
4630
-			else
4631
-			{
4632
-				$out.= "&nbsp;";
4633
-			}
4634
-		}
4635
-
4636
-		if ($nooutput) return $out;
4637
-		else print $out;
4638
-	}
3031
+        global $langs;
3032
+
3033
+        $num = count($this->cache_availability);
3034
+        if ($num > 0) return 0;    // Cache already loaded
3035
+
3036
+        dol_syslog(__METHOD__, LOG_DEBUG);
3037
+
3038
+        $langs->load('propal');
3039
+
3040
+        $sql = "SELECT rowid, code, label";
3041
+        $sql.= " FROM ".MAIN_DB_PREFIX.'c_availability';
3042
+        $sql.= " WHERE active > 0";
3043
+
3044
+        $resql = $this->db->query($sql);
3045
+        if ($resql)
3046
+        {
3047
+            $num = $this->db->num_rows($resql);
3048
+            $i = 0;
3049
+            while ($i < $num)
3050
+            {
3051
+                $obj = $this->db->fetch_object($resql);
3052
+
3053
+                // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3054
+                $label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:''));
3055
+                $this->cache_availability[$obj->rowid]['code'] =$obj->code;
3056
+                $this->cache_availability[$obj->rowid]['label']=$label;
3057
+                $i++;
3058
+            }
3059
+
3060
+            $this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);
3061
+
3062
+            return $num;
3063
+        }
3064
+        else
3065
+        {
3066
+            dol_print_error($this->db);
3067
+            return -1;
3068
+        }
3069
+    }
3070
+
3071
+    /**
3072
+     *      Retourne la liste des types de delais de livraison possibles
3073
+     *
3074
+     *      @param	int		$selected        Id du type de delais pre-selectionne
3075
+     *      @param  string	$htmlname        Nom de la zone select
3076
+     *      @param  string	$filtertype      To add a filter
3077
+     *		@param	int		$addempty		Add empty entry
3078
+     *		@return	void
3079
+     */
3080
+    function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0)
3081
+    {
3082
+        global $langs,$user;
3083
+
3084
+        $this->load_cache_availability();
3085
+
3086
+        dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
3087
+
3088
+        print '<select id="'.$htmlname.'" class="flat" name="'.$htmlname.'">';
3089
+        if ($addempty) print '<option value="0">&nbsp;</option>';
3090
+        foreach($this->cache_availability as $id => $arrayavailability)
3091
+        {
3092
+            if ($selected == $id)
3093
+            {
3094
+                print '<option value="'.$id.'" selected>';
3095
+            }
3096
+            else
3097
+            {
3098
+                print '<option value="'.$id.'">';
3099
+            }
3100
+            print $arrayavailability['label'];
3101
+            print '</option>';
3102
+        }
3103
+        print '</select>';
3104
+        if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3105
+    }
3106
+
3107
+    /**
3108
+     *      Load into cache cache_demand_reason, array of input reasons
3109
+     *
3110
+     *      @return     int             Nb of lines loaded, <0 if KO
3111
+     */
3112
+    function loadCacheInputReason()
3113
+    {
3114
+        global $langs;
3115
+
3116
+        $num = count($this->cache_demand_reason);
3117
+        if ($num > 0) return 0;    // Cache already loaded
3118
+
3119
+        $sql = "SELECT rowid, code, label";
3120
+        $sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
3121
+        $sql.= " WHERE active > 0";
3122
+
3123
+        $resql = $this->db->query($sql);
3124
+        if ($resql)
3125
+        {
3126
+            $num = $this->db->num_rows($resql);
3127
+            $i = 0;
3128
+            $tmparray=array();
3129
+            while ($i < $num)
3130
+            {
3131
+                $obj = $this->db->fetch_object($resql);
3132
+
3133
+                // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3134
+                $label=($obj->label!='-'?$obj->label:'');
3135
+                if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
3136
+                if ($langs->trans($obj->code) != $obj->code) $label=$langs->trans($obj->code);																// So translation key SRC_XXX will work
3137
+
3138
+                $tmparray[$obj->rowid]['id']   =$obj->rowid;
3139
+                $tmparray[$obj->rowid]['code'] =$obj->code;
3140
+                $tmparray[$obj->rowid]['label']=$label;
3141
+                $i++;
3142
+            }
3143
+
3144
+            $this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
3145
+
3146
+            unset($tmparray);
3147
+            return $num;
3148
+        }
3149
+        else
3150
+        {
3151
+            dol_print_error($this->db);
3152
+            return -1;
3153
+        }
3154
+    }
3155
+
3156
+    /**
3157
+     *	Return list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
3158
+     *  List found into table c_input_reason loaded by loadCacheInputReason
3159
+     *
3160
+     *  @param	int		$selected        Id or code of type origin to select by default
3161
+     *  @param  string	$htmlname        Nom de la zone select
3162
+     *  @param  string	$exclude         To exclude a code value (Example: SRC_PROP)
3163
+     *	@param	int		$addempty		 Add an empty entry
3164
+     *	@return	void
3165
+     */
3166
+    function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0)
3167
+    {
3168
+        global $langs,$user;
3169
+
3170
+        $this->loadCacheInputReason();
3171
+
3172
+        print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3173
+        if ($addempty) print '<option value="0"'.(empty($selected)?' selected':'').'>&nbsp;</option>';
3174
+        foreach($this->cache_demand_reason as $id => $arraydemandreason)
3175
+        {
3176
+            if ($arraydemandreason['code']==$exclude) continue;
3177
+
3178
+            if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
3179
+            {
3180
+                print '<option value="'.$arraydemandreason['id'].'" selected>';
3181
+            }
3182
+            else
3183
+            {
3184
+                print '<option value="'.$arraydemandreason['id'].'">';
3185
+            }
3186
+            $label=$arraydemandreason['label'];	// Translation of label was already done into the ->loadCacheInputReason
3187
+            print $langs->trans($label);
3188
+            print '</option>';
3189
+        }
3190
+        print '</select>';
3191
+        if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3192
+    }
4639 3193
 
4640 3194
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4641
-	/**
4642
-	 *    Retourne la liste des devises, dans la langue de l'utilisateur
4643
-	 *
4644
-	 *    @param	string	$selected    preselected currency code
4645
-	 *    @param    string	$htmlname    name of HTML select list
4646
-     *    @deprecated
4647
-	 *    @return	void
4648
-	 */
4649
-	function select_currency($selected='',$htmlname='currency_id')
4650
-	{
3195
+    /**
3196
+     *      Charge dans cache la liste des types de paiements possibles
3197
+     *
3198
+     *      @return     int                 Nb of lines loaded, <0 if KO
3199
+     */
3200
+    function load_cache_types_paiements()
3201
+    {
4651 3202
         // phpcs:enable
4652
-		print $this->selectCurrency($selected,$htmlname);
4653
-	}
4654
-
4655
-	/**
4656
-	 *  Retourne la liste des devises, dans la langue de l'utilisateur
4657
-	 *
4658
-	 *  @param	string	$selected    preselected currency code
4659
-	 *  @param  string	$htmlname    name of HTML select list
4660
-	 * 	@return	string
4661
-	 */
4662
-	function selectCurrency($selected='',$htmlname='currency_id')
4663
-	{
4664
-		global $conf,$langs,$user;
4665
-
4666
-		$langs->loadCacheCurrencies('');
4667
-
4668
-		$out='';
4669
-
4670
-		if ($selected=='euro' || $selected=='euros') $selected='EUR';   // Pour compatibilite
4671
-
4672
-		$out.= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
4673
-		foreach ($langs->cache_currencies as $code_iso => $currency)
4674
-		{
4675
-			if ($selected && $selected == $code_iso)
4676
-			{
4677
-				$out.= '<option value="'.$code_iso.'" selected>';
4678
-			}
4679
-			else
4680
-			{
4681
-				$out.= '<option value="'.$code_iso.'">';
4682
-			}
4683
-			$out.= $currency['label'];
4684
-			$out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
4685
-			$out.= '</option>';
4686
-		}
4687
-		$out.= '</select>';
4688
-		if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
4689
-
4690
-		// Make select dynamic
4691
-		include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4692
-		$out .= ajax_combobox($htmlname);
4693
-
4694
-		return $out;
4695
-	}
4696
-
4697
-	/**
4698
-	 *	Return array of currencies in user language
4699
-	 *
4700
-	 *  @param	string	$selected    preselected currency code
4701
-	 *  @param  string	$htmlname    name of HTML select list
4702
-	 *  @param  integer	$useempty    1=Add empty line
4703
-	 * 	@return	string
4704
-	 */
4705
-	function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0)
4706
-	{
4707
-		global $db,$conf,$langs,$user;
4708
-
4709
-		$langs->loadCacheCurrencies('');        // Load ->cache_currencies
4710
-
4711
-		$TCurrency = array();
4712
-
4713
-		$sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
4714
-		$sql.= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
4715
-		$resql = $db->query($sql);
4716
-		if ($resql)
4717
-		{
4718
-			while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
4719
-		}
4720
-
4721
-		$out='';
4722
-		$out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
4723
-		if ($useempty) $out .= '<option value=""></option>';
4724
-		// If company current currency not in table, we add it into list. Should always be available.
4725
-		if (! in_array($conf->currency, $TCurrency))
4726
-		{
4727
-			$TCurrency[$conf->currency] = $conf->currency;
4728
-		}
4729
-		if (count($TCurrency) > 0)
4730
-		{
4731
-			foreach ($langs->cache_currencies as $code_iso => $currency)
4732
-			{
4733
-				if (isset($TCurrency[$code_iso]))
4734
-				{
4735
-					if (!empty($selected) && $selected == $code_iso) $out.= '<option value="'.$code_iso.'" selected="selected">';
4736
-					else $out.= '<option value="'.$code_iso.'">';
4737
-
4738
-					$out.= $currency['label'];
4739
-					$out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
4740
-					$out.= '</option>';
4741
-				}
4742
-			}
4743
-		}
4744
-
4745
-		$out.= '</select>';
4746
-		// Make select dynamic
4747
-		include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4748
-		$out.= ajax_combobox($htmlname);
4749
-
4750
-		return $out;
4751
-	}
3203
+        global $langs;
3204
+
3205
+        $num=count($this->cache_types_paiements);
3206
+        if ($num > 0) return $num;    // Cache already loaded
3207
+
3208
+        dol_syslog(__METHOD__, LOG_DEBUG);
3209
+
3210
+        $this->cache_types_paiements = array();
3211
+
3212
+        $sql = "SELECT id, code, libelle as label, type, active";
3213
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement";
3214
+        $sql.= " WHERE entity IN (".getEntity('c_paiement').")";
3215
+        //if ($active >= 0) $sql.= " AND active = ".$active;
3216
+
3217
+        $resql = $this->db->query($sql);
3218
+        if ($resql)
3219
+        {
3220
+            $num = $this->db->num_rows($resql);
3221
+            $i = 0;
3222
+            while ($i < $num)
3223
+            {
3224
+                $obj = $this->db->fetch_object($resql);
3225
+
3226
+                // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3227
+                $label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:''));
3228
+                $this->cache_types_paiements[$obj->id]['id'] =$obj->id;
3229
+                $this->cache_types_paiements[$obj->id]['code'] =$obj->code;
3230
+                $this->cache_types_paiements[$obj->id]['label']=$label;
3231
+                $this->cache_types_paiements[$obj->id]['type'] =$obj->type;
3232
+                $this->cache_types_paiements[$obj->id]['active'] =$obj->active;
3233
+                $i++;
3234
+            }
3235
+
3236
+            $this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
3237
+
3238
+            return $num;
3239
+        }
3240
+        else
3241
+        {
3242
+            dol_print_error($this->db);
3243
+            return -1;
3244
+        }
3245
+    }
3246
+
4752 3247
 
4753 3248
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4754
-	/**
4755
-	 *	Load into the cache vat rates of a country
4756
-	 *
4757
-	 *	@param	string	$country_code		Country code with quotes ("'CA'", or "'CA,IN,...'")
4758
-	 *	@return	int							Nb of loaded lines, 0 if already loaded, <0 if KO
4759
-	 */
4760
-	function load_cache_vatrates($country_code)
4761
-	{
3249
+    /**
3250
+     *      Return list of payment modes.
3251
+     *      Constant MAIN_DEFAULT_PAYMENT_TERM_ID can used to set default value but scope is all application, probably not what you want.
3252
+     *      See instead to force the default value by the caller.
3253
+     *
3254
+     *      @param	int		$selected		Id of payment term to preselect by default
3255
+     *      @param	string	$htmlname		Nom de la zone select
3256
+     *      @param	int		$filtertype		Not used
3257
+     *		@param	int		$addempty		Add an empty entry
3258
+     * 		@param	int		$noinfoadmin		0=Add admin info, 1=Disable admin info
3259
+     * 		@param	string	$morecss			Add more CSS on select tag
3260
+     *		@return	void
3261
+     */
3262
+    function select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='')
3263
+    {
4762 3264
         // phpcs:enable
4763
-		global $langs;
4764
-
4765
-		$num = count($this->cache_vatrates);
4766
-		if ($num > 0) return $num;    // Cache already loaded
4767
-
4768
-		dol_syslog(__METHOD__, LOG_DEBUG);
4769
-
4770
-		$sql  = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
4771
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4772
-		$sql.= " WHERE t.fk_pays = c.rowid";
4773
-		$sql.= " AND t.active > 0";
4774
-		$sql.= " AND c.code IN (".$country_code.")";
4775
-		$sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
4776
-
4777
-		$resql=$this->db->query($sql);
4778
-		if ($resql)
4779
-		{
4780
-			$num = $this->db->num_rows($resql);
4781
-			if ($num)
4782
-			{
4783
-				for ($i = 0; $i < $num; $i++)
4784
-				{
4785
-					$obj = $this->db->fetch_object($resql);
4786
-					$this->cache_vatrates[$i]['rowid']	= $obj->rowid;
4787
-					$this->cache_vatrates[$i]['code']	= $obj->code;
4788
-					$this->cache_vatrates[$i]['txtva']	= $obj->taux;
4789
-					$this->cache_vatrates[$i]['nprtva']	= $obj->recuperableonly;
4790
-					$this->cache_vatrates[$i]['localtax1']	    = $obj->localtax1;
4791
-					$this->cache_vatrates[$i]['localtax1_type']	= $obj->localtax1_type;
4792
-					$this->cache_vatrates[$i]['localtax2']	    = $obj->localtax2;
4793
-					$this->cache_vatrates[$i]['localtax2_type']	= $obj->localtax1_type;
4794
-
4795
-					$this->cache_vatrates[$i]['label']	= $obj->taux.'%'.($obj->code?' ('.$obj->code.')':'');   // Label must contains only 0-9 , . % or *
4796
-					$this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':'');	// Must never be used as key, only label
4797
-					$positiverates='';
4798
-					if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux;
4799
-					if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1;
4800
-					if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2;
4801
-					if (empty($positiverates)) $positiverates='0';
4802
-					$this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':'');	// Must never be used as key, only label
4803
-				}
4804
-
4805
-				return $num;
4806
-			}
4807
-			else
4808
-			{
4809
-				$this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).'</font>';
4810
-				return -1;
4811
-			}
4812
-		}
4813
-		else
4814
-		{
4815
-			$this->error = '<font class="error">'.$this->db->error().'</font>';
4816
-			return -2;
4817
-		}
4818
-	}
3265
+        global $langs, $user, $conf;
3266
+
3267
+        dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
3268
+
3269
+        $this->load_cache_conditions_paiements();
3270
+
3271
+        // Set default value if not already set by caller
3272
+        if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
3273
+
3274
+        print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
3275
+        if ($addempty) print '<option value="0">&nbsp;</option>';
3276
+        foreach($this->cache_conditions_paiements as $id => $arrayconditions)
3277
+        {
3278
+            if ($selected == $id)
3279
+            {
3280
+                print '<option value="'.$id.'" selected>';
3281
+            }
3282
+            else
3283
+            {
3284
+                print '<option value="'.$id.'">';
3285
+            }
3286
+            print $arrayconditions['label'];
3287
+            print '</option>';
3288
+        }
3289
+        print '</select>';
3290
+        if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3291
+    }
3292
+
4819 3293
 
4820 3294
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4821
-	/**
4822
-	 *  Output an HTML select vat rate.
4823
-	 *  The name of this function should be selectVat. We keep bad name for compatibility purpose.
4824
-	 *
4825
-	 *  @param	string	      $htmlname           Name of HTML select field
4826
-	 *  @param  float|string  $selectedrate       Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
4827
-	 *  @param  Societe	      $societe_vendeuse   Thirdparty seller
4828
-	 *  @param  Societe	      $societe_acheteuse  Thirdparty buyer
4829
-	 *  @param  int		      $idprod             Id product. O if unknown of NA.
4830
-	 *  @param  int		      $info_bits          Miscellaneous information on line (1 for NPR)
4831
-	 *  @param  int|string    $type               ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
4832
-	 *                  		                  Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
4833
-	 *                  					      Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
4834
-	 *                  					      Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
4835
-	 *                                            Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
4836
-	 *                                            Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
4837
-	 *                  					      Sinon la TVA proposee par defaut=0. Fin de regle.
4838
-	 *  @param	bool	     $options_only		  Return HTML options lines only (for ajax treatment)
4839
-	 *  @param  int          $mode                0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key
4840
-	 *  @return	string
4841
-	 */
4842
-	function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0)
4843
-	{
3295
+    /**
3296
+     *      Return list of payment methods
3297
+     *
3298
+     *      @param	string	$selected       Id du mode de paiement pre-selectionne
3299
+     *      @param  string	$htmlname       Nom de la zone select
3300
+     *      @param  string	$filtertype     To filter on field type in llx_c_paiement ('CRDT' or 'DBIT' or array('code'=>xx,'label'=>zz))
3301
+     *      @param  int		$format         0=id+libelle, 1=code+code, 2=code+libelle, 3=id+code
3302
+     *      @param  int		$empty			1=peut etre vide, 0 sinon
3303
+     * 		@param	int		$noadmininfo	0=Add admin info, 1=Disable admin info
3304
+     *      @param  int		$maxlength      Max length of label
3305
+     *      @param  int     $active         Active or not, -1 = all
3306
+     *      @param  string  $morecss        Add more CSS on select tag
3307
+     * 		@return	void
3308
+     */
3309
+    function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=1, $noadmininfo=0, $maxlength=0, $active=1, $morecss='')
3310
+    {
4844 3311
         // phpcs:enable
4845
-		global $langs,$conf,$mysoc;
4846
-
4847
-		$langs->load('errors');
4848
-
4849
-		$return='';
4850
-
4851
-		// Define defaultnpr, defaultttx and defaultcode
4852
-		$defaultnpr=($info_bits & 0x01);
4853
-		$defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr);
4854
-		$defaulttx=str_replace('*','',$selectedrate);
4855
-		$defaultcode='';
4856
-		if (preg_match('/\((.*)\)/', $defaulttx, $reg))
4857
-		{
4858
-			$defaultcode=$reg[1];
4859
-			$defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
4860
-		}
4861
-		//var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
4862
-
4863
-		// Check parameters
4864
-		if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)
4865
-		{
4866
-			if ($societe_vendeuse->id == $mysoc->id)
4867
-			{
4868
-				$return.= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</div>';
4869
-			}
4870
-			else
4871
-			{
4872
-				$return.= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</div>';
4873
-			}
4874
-			return $return;
4875
-		}
4876
-
4877
-		//var_dump($societe_acheteuse);
4878
-		//print "name=$name, selectedrate=$selectedrate, seller=".$societe_vendeuse->country_code." buyer=".$societe_acheteuse->country_code." buyer is company=".$societe_acheteuse->isACompany()." idprod=$idprod, info_bits=$info_bits type=$type";
4879
-		//exit;
4880
-
4881
-		// Define list of countries to use to search VAT rates to show
4882
-		// First we defined code_country to use to find list
4883
-		if (is_object($societe_vendeuse))
4884
-		{
4885
-			$code_country="'".$societe_vendeuse->country_code."'";
4886
-		}
4887
-		else
4888
-		{
4889
-			$code_country="'".$mysoc->country_code."'";   // Pour compatibilite ascendente
4890
-		}
4891
-		if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))    // If option to have vat for end customer for services is on
4892
-		{
4893
-			require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4894
-			if (! isInEEC($societe_vendeuse) && (! is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && ! $societe_acheteuse->isACompany())))
4895
-			{
4896
-				// We also add the buyer
4897
-				if (is_numeric($type))
4898
-				{
4899
-					if ($type == 1) // We know product is a service
4900
-					{
4901
-						$code_country.=",'".$societe_acheteuse->country_code."'";
4902
-					}
4903
-				}
4904
-				else if (! $idprod)  // We don't know type of product
4905
-				{
4906
-					$code_country.=",'".$societe_acheteuse->country_code."'";
4907
-				}
4908
-				else
4909
-				{
4910
-					$prodstatic=new Product($this->db);
4911
-					$prodstatic->fetch($idprod);
4912
-					if ($prodstatic->type == Product::TYPE_SERVICE)   // We know product is a service
4913
-					{
4914
-						$code_country.=",'".$societe_acheteuse->country_code."'";
4915
-					}
4916
-				}
4917
-			}
4918
-		}
4919
-
4920
-		// Now we get list
4921
-		$num = $this->load_cache_vatrates($code_country);   // If no vat defined, return -1 with message into this->error
4922
-
4923
-		if ($num > 0)
4924
-		{
4925
-			// Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
4926
-			if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
4927
-			{
4928
-				$tmpthirdparty=new Societe($this->db);
4929
-				$defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
4930
-				$defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
4931
-		        if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
4932
-			        $defaultcode=$reg[1];
4933
-			        $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
4934
-		        }
4935
-				if (empty($defaulttx)) $defaultnpr=0;
4936
-			}
4937
-
4938
-			// Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
4939
-			// Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
4940
-			if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
4941
-			{
4942
-				if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva'];
4943
-				else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
4944
-			}
4945
-
4946
-			// Disabled if seller is not subject to VAT
4947
-			$disabled=false; $title='';
4948
-			if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0")
4949
-			{
4950
-				// Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses
4951
-				if (empty($conf->global->OVERRIDE_VAT_FOR_EXPENSE_REPORT))
4952
-				{
4953
-					$title=' title="'.$langs->trans('VATIsNotUsed').'"';
4954
-					$disabled=true;
4955
-				}
4956
-			}
4957
-
4958
-			if (! $options_only) $return.= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$title.'>';
4959
-
4960
-			$selectedfound=false;
4961
-			foreach ($this->cache_vatrates as $rate)
4962
-			{
4963
-				// Keep only 0 if seller is not subject to VAT
4964
-				if ($disabled && $rate['txtva'] != 0) continue;
4965
-
4966
-				// Define key to use into select list
4967
-				$key = $rate['txtva'];
4968
-				$key.= $rate['nprtva'] ? '*': '';
4969
-				if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')';
4970
-				if ($mode < 0) $key = $rate['rowid'];
4971
-
4972
-				$return.= '<option value="'.$key.'"';
4973
-				if (! $selectedfound)
4974
-				{
4975
-					if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
4976
-					{
4977
-						if ($defaultcode == $rate['code'])
4978
-						{
4979
-							$return.= ' selected';
4980
-							$selectedfound=true;
4981
-						}
4982
-					}
4983
-					elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
4984
-			   		{
4985
-			   			$return.= ' selected';
4986
-			   			$selectedfound=true;
4987
-					}
4988
-				}
4989
-				$return.= '>';
4990
-				//if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
4991
-				if ($mysoc->country_code == 'IN' || ! empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))
4992
-				{
4993
-					$return.= $rate['labelpositiverates'];
4994
-				}
4995
-				else
4996
-				{
4997
-					$return.= vatrate($rate['label']);
4998
-				}
4999
-				//$return.=($rate['code']?' '.$rate['code']:'');
5000
-				$return.= (empty($rate['code']) && $rate['nprtva']) ? ' *': '';         // We show the *  (old behaviour only if new vat code is not used)
5001
-
5002
-				$return.= '</option>';
5003
-			}
5004
-
5005
-			if (! $options_only) $return.= '</select>';
5006
-		}
5007
-		else
5008
-		{
5009
-			$return.= $this->error;
5010
-		}
5011
-
5012
-		$this->num = $num;
5013
-		return $return;
5014
-	}
3312
+        global $langs,$user;
3313
+
3314
+        dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
3315
+
3316
+        $filterarray=array();
3317
+        if ($filtertype == 'CRDT')  	$filterarray=array(0,2,3);
3318
+        elseif ($filtertype == 'DBIT') 	$filterarray=array(1,2,3);
3319
+        elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);
3320
+
3321
+        $this->load_cache_types_paiements();
3322
+
3323
+        print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
3324
+        if ($empty) print '<option value="">&nbsp;</option>';
3325
+        foreach($this->cache_types_paiements as $id => $arraytypes)
3326
+        {
3327
+            // If not good status
3328
+            if ($active >= 0 && $arraytypes['active'] != $active) continue;
3329
+
3330
+            // On passe si on a demande de filtrer sur des modes de paiments particuliers
3331
+            if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;
3332
+
3333
+            // We discard empty line if showempty is on because an empty line has already been output.
3334
+            if ($empty && empty($arraytypes['code'])) continue;
3335
+
3336
+            if ($format == 0) print '<option value="'.$id.'"';
3337
+            elseif ($format == 1) print '<option value="'.$arraytypes['code'].'"';
3338
+            elseif ($format == 2) print '<option value="'.$arraytypes['code'].'"';
3339
+            elseif ($format == 3) print '<option value="'.$id.'"';
3340
+            // Si selected est text, on compare avec code, sinon avec id
3341
+            if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';
3342
+            elseif ($selected == $id) print ' selected';
3343
+            print '>';
3344
+            if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3345
+            elseif ($format == 1) $value=$arraytypes['code'];
3346
+            elseif ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3347
+            elseif ($format == 3) $value=$arraytypes['code'];
3348
+            print $value?$value:'&nbsp;';
3349
+            print '</option>';
3350
+        }
3351
+        print '</select>';
3352
+        if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3353
+    }
3354
+
3355
+
3356
+    /**
3357
+     *  Selection HT or TTC
3358
+     *
3359
+     *  @param	string	$selected       Id pre-selectionne
3360
+     *  @param  string	$htmlname       Nom de la zone select
3361
+     * 	@return	string					Code of HTML select to chose tax or not
3362
+     */
3363
+    function selectPriceBaseType($selected='',$htmlname='price_base_type')
3364
+    {
3365
+        global $langs;
3366
+
3367
+        $return='';
3368
+
3369
+        $return.= '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3370
+        $options = array(
3371
+            'HT'=>$langs->trans("HT"),
3372
+            'TTC'=>$langs->trans("TTC")
3373
+        );
3374
+        foreach($options as $id => $value)
3375
+        {
3376
+            if ($selected == $id)
3377
+            {
3378
+                $return.= '<option value="'.$id.'" selected>'.$value;
3379
+            }
3380
+            else
3381
+            {
3382
+                $return.= '<option value="'.$id.'">'.$value;
3383
+            }
3384
+            $return.= '</option>';
3385
+        }
3386
+        $return.= '</select>';
3387
+
3388
+        return $return;
3389
+    }
3390
+
3391
+    /**
3392
+     *  Return a HTML select list of shipping mode
3393
+     *
3394
+     *  @param	string	$selected          Id shipping mode pre-selected
3395
+     *  @param  string	$htmlname          Name of select zone
3396
+     *  @param  string	$filtre            To filter list
3397
+     *  @param  int		$useempty          1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3398
+     *  @param  string	$moreattrib        To add more attribute on select
3399
+     * 	@return	void
3400
+     */
3401
+    function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='')
3402
+    {
3403
+        global $langs, $conf, $user;
3404
+
3405
+        $langs->load("admin");
3406
+        $langs->load("deliveries");
3407
+
3408
+        $sql = "SELECT rowid, code, libelle as label";
3409
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
3410
+        $sql.= " WHERE active > 0";
3411
+        if ($filtre) $sql.=" AND ".$filtre;
3412
+        $sql.= " ORDER BY libelle ASC";
3413
+
3414
+        dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
3415
+        $result = $this->db->query($sql);
3416
+        if ($result) {
3417
+            $num = $this->db->num_rows($result);
3418
+            $i = 0;
3419
+            if ($num) {
3420
+                print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
3421
+                if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
3422
+                    print '<option value="-1">&nbsp;</option>';
3423
+                }
3424
+                while ($i < $num) {
3425
+                    $obj = $this->db->fetch_object($result);
3426
+                    if ($selected == $obj->rowid) {
3427
+                        print '<option value="'.$obj->rowid.'" selected>';
3428
+                    } else {
3429
+                        print '<option value="'.$obj->rowid.'">';
3430
+                    }
3431
+                    print ($langs->trans("SendingMethod".strtoupper($obj->code)) != "SendingMethod".strtoupper($obj->code)) ? $langs->trans("SendingMethod".strtoupper($obj->code)) : $obj->label;
3432
+                    print '</option>';
3433
+                    $i++;
3434
+                }
3435
+                print "</select>";
3436
+                if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3437
+            } else {
3438
+                print $langs->trans("NoShippingMethodDefined");
3439
+            }
3440
+        } else {
3441
+            dol_print_error($this->db);
3442
+        }
3443
+    }
3444
+
3445
+    /**
3446
+     *    Display form to select shipping mode
3447
+     *
3448
+     *    @param	string	$page        Page
3449
+     *    @param    int		$selected    Id of shipping mode
3450
+     *    @param    string	$htmlname    Name of select html field
3451
+     *    @param    int		$addempty    1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3452
+     *    @return	void
3453
+     */
3454
+    function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0)
3455
+    {
3456
+        global $langs, $db;
3457
+
3458
+        $langs->load("deliveries");
3459
+
3460
+        if ($htmlname != "none") {
3461
+            print '<form method="POST" action="'.$page.'">';
3462
+            print '<input type="hidden" name="action" value="setshippingmethod">';
3463
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
3464
+            $this->selectShippingMethod($selected, $htmlname, '', $addempty);
3465
+            print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
3466
+            print '</form>';
3467
+        } else {
3468
+            if ($selected) {
3469
+                $code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
3470
+                print $langs->trans("SendingMethod".strtoupper($code));
3471
+            } else {
3472
+                print "&nbsp;";
3473
+            }
3474
+        }
3475
+    }
3476
+
3477
+    /**
3478
+     * Creates HTML last in cycle situation invoices selector
3479
+     *
3480
+     * @param     string  $selected   		Preselected ID
3481
+     * @param     int     $socid      		Company ID
3482
+     *
3483
+     * @return    string                     HTML select
3484
+     */
3485
+    function selectSituationInvoices($selected = '', $socid = 0)
3486
+    {
3487
+        global $langs;
3488
+
3489
+        $langs->load('bills');
3490
+
3491
+        $opt = '<option value ="" selected></option>';
3492
+        $sql = 'SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_counter>=1';
3493
+        $sql.= ' ORDER by situation_cycle_ref, situation_counter desc';
3494
+        $resql = $this->db->query($sql);
3495
+        if ($resql && $this->db->num_rows($resql) > 0) {
3496
+            // Last seen cycle
3497
+            $ref = 0;
3498
+            while ($obj = $this->db->fetch_object($resql)){
3499
+                //Same company ?
3500
+                if ($socid == $obj->fk_soc) {
3501
+                    //Same cycle ?
3502
+                    if ($obj->situation_cycle_ref != $ref) {
3503
+                        // Just seen this cycle
3504
+                        $ref = $obj->situation_cycle_ref;
3505
+                        //not final ?
3506
+                        if ($obj->situation_final != 1) {
3507
+                            //Not prov?
3508
+                            if (substr($obj->ref, 1, 4) != 'PROV') {
3509
+                                if ($selected == $obj->rowid) {
3510
+                                    $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
3511
+                                } else {
3512
+                                    $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
3513
+                                }
3514
+                            }
3515
+                        }
3516
+                    }
3517
+                }
3518
+            }
3519
+        }
3520
+        else
3521
+        {
3522
+                dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
3523
+        }
3524
+        if ($opt == '<option value ="" selected></option>')
3525
+        {
3526
+            $opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
3527
+        }
3528
+        return $opt;
3529
+    }
3530
+
3531
+    /**
3532
+     *      Creates HTML units selector (code => label)
3533
+     *
3534
+     *      @param	string	$selected       Preselected Unit ID
3535
+     *      @param  string	$htmlname       Select name
3536
+     *      @param	int		$showempty		Add a nempty line
3537
+     * 		@return	string                  HTML select
3538
+     */
3539
+    function selectUnits($selected = '', $htmlname = 'units', $showempty=0)
3540
+    {
3541
+        global $langs;
3542
+
3543
+        $langs->load('products');
3544
+
3545
+        $return= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
3546
+
3547
+        $sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';
3548
+        $sql.= ' WHERE active > 0';
3549
+
3550
+        $resql = $this->db->query($sql);
3551
+        if($resql && $this->db->num_rows($resql) > 0)
3552
+        {
3553
+            if ($showempty) $return .= '<option value="none"></option>';
3554
+
3555
+            while($res = $this->db->fetch_object($resql))
3556
+            {
3557
+                $unitLabel = $res->label;
3558
+                if (! empty($langs->tab_translate['unit'.$res->code]))	// check if Translation is available before
3559
+                {
3560
+                    $unitLabel = $langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label;
3561
+                }
3562
+
3563
+                if ($selected == $res->rowid)
3564
+                {
3565
+                    $return.='<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
3566
+                }
3567
+                else
3568
+                {
3569
+                    $return.='<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
3570
+                }
3571
+            }
3572
+            $return.='</select>';
3573
+        }
3574
+        return $return;
3575
+    }
3576
+
3577
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3578
+    /**
3579
+     *  Return a HTML select list of bank accounts
3580
+     *
3581
+     *  @param	string	$selected           Id account pre-selected
3582
+     *  @param  string	$htmlname           Name of select zone
3583
+     *  @param  int		$statut             Status of searched accounts (0=open, 1=closed, 2=both)
3584
+     *  @param  string	$filtre             To filter list
3585
+     *  @param  int		$useempty           1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3586
+     *  @param  string	$moreattrib         To add more attribute on select
3587
+     *  @param	int		$showcurrency		Show currency in label
3588
+     * 	@return	int							<0 if error, Num of bank account found if OK (0, 1, 2, ...)
3589
+     */
3590
+    function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='',$showcurrency=0)
3591
+    {
3592
+        // phpcs:enable
3593
+        global $langs, $conf;
3594
+
3595
+        $langs->load("admin");
3596
+        $num = 0;
3597
+
3598
+        $sql = "SELECT rowid, label, bank, clos as status, currency_code";
3599
+        $sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
3600
+        $sql.= " WHERE entity IN (".getEntity('bank_account').")";
3601
+        if ($statut != 2) $sql.= " AND clos = '".$statut."'";
3602
+        if ($filtre) $sql.=" AND ".$filtre;
3603
+        $sql.= " ORDER BY label";
3604
+
3605
+        dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
3606
+        $result = $this->db->query($sql);
3607
+        if ($result)
3608
+        {
3609
+            $num = $this->db->num_rows($result);
3610
+            $i = 0;
3611
+            if ($num)
3612
+            {
3613
+                print '<select id="select'.$htmlname.'" class="flat selectbankaccount" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
3614
+                if ($useempty == 1 || ($useempty == 2 && $num > 1))
3615
+                {
3616
+                    print '<option value="-1">&nbsp;</option>';
3617
+                }
3618
+
3619
+                while ($i < $num)
3620
+                {
3621
+                    $obj = $this->db->fetch_object($result);
3622
+                    if ($selected == $obj->rowid)
3623
+                    {
3624
+                        print '<option value="'.$obj->rowid.'" selected>';
3625
+                    }
3626
+                    else
3627
+                    {
3628
+                        print '<option value="'.$obj->rowid.'">';
3629
+                    }
3630
+                    print trim($obj->label);
3631
+                    if ($showcurrency) print ' ('.$obj->currency_code.')';
3632
+                    if ($statut == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
3633
+                    print '</option>';
3634
+                    $i++;
3635
+                }
3636
+                print "</select>";
3637
+            }
3638
+            else
3639
+            {
3640
+                if ($statut == 0) print '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
3641
+                else print '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
3642
+            }
3643
+        }
3644
+        else {
3645
+            dol_print_error($this->db);
3646
+        }
3647
+
3648
+        return $num;
3649
+    }
3650
+
3651
+    /**
3652
+     *    Display form to select bank account
3653
+     *
3654
+     *    @param	string	$page        Page
3655
+     *    @param    int		$selected    Id of bank account
3656
+     *    @param    string	$htmlname    Name of select html field
3657
+     *    @param    int		$addempty    1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3658
+     *    @return	void
3659
+     */
3660
+    function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0)
3661
+    {
3662
+        global $langs;
3663
+        if ($htmlname != "none") {
3664
+            print '<form method="POST" action="'.$page.'">';
3665
+            print '<input type="hidden" name="action" value="setbankaccount">';
3666
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
3667
+            $nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
3668
+            if ($nbaccountfound > 0) print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
3669
+            print '</form>';
3670
+        } else {
3671
+
3672
+            $langs->load('banks');
3673
+
3674
+            if ($selected) {
3675
+                require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php';
3676
+                $bankstatic=new Account($this->db);
3677
+                $result = $bankstatic->fetch($selected);
3678
+                if ($result) print $bankstatic->getNomUrl(1);
3679
+            } else {
3680
+                print "&nbsp;";
3681
+            }
3682
+        }
3683
+    }
3684
+
3685
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3686
+    /**
3687
+     *    Return list of categories having choosed type
3688
+     *
3689
+     *    @param	string|int	$type				Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated.
3690
+     *    @param    string		$selected    		Id of category preselected or 'auto' (autoselect category if there is only one element)
3691
+     *    @param    string		$htmlname			HTML field name
3692
+     *    @param    int			$maxlength      	Maximum length for labels
3693
+     *    @param    int			$excludeafterid 	Exclude all categories after this leaf in category tree.
3694
+     *    @param	int			$outputmode			0=HTML select string, 1=Array
3695
+     *    @return	string
3696
+     *    @see select_categories
3697
+     */
3698
+    function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0)
3699
+    {
3700
+        // phpcs:enable
3701
+        global $conf, $langs;
3702
+        $langs->load("categories");
3703
+
3704
+        include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
3705
+
3706
+        // For backward compatibility
3707
+        if (is_numeric($type))
3708
+        {
3709
+            dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
3710
+        }
3711
+
3712
+        if ($type === Categorie::TYPE_BANK_LINE)
3713
+        {
3714
+            // TODO Move this into common category feature
3715
+            $categids=array();
3716
+            $sql = "SELECT c.label, c.rowid";
3717
+            $sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
3718
+            $sql.= " WHERE entity = ".$conf->entity;
3719
+            $sql.= " ORDER BY c.label";
3720
+            $result = $this->db->query($sql);
3721
+            if ($result)
3722
+            {
3723
+                $num = $this->db->num_rows($result);
3724
+                $i = 0;
3725
+                while ($i < $num)
3726
+                {
3727
+                    $objp = $this->db->fetch_object($result);
3728
+                    if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
3729
+                    $i++;
3730
+                }
3731
+                $this->db->free($result);
3732
+            }
3733
+            else dol_print_error($this->db);
3734
+        }
3735
+        else
3736
+        {
3737
+            $cat = new Categorie($this->db);
3738
+            $cate_arbo = $cat->get_full_arbo($type, $excludeafterid);
3739
+        }
3740
+
3741
+        $output = '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
3742
+        $outarray=array();
3743
+        if (is_array($cate_arbo))
3744
+        {
3745
+            if (! count($cate_arbo)) $output.= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
3746
+            else
3747
+            {
3748
+                $output.= '<option value="-1">&nbsp;</option>';
3749
+                foreach($cate_arbo as $key => $value)
3750
+                {
3751
+                    if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
3752
+                    {
3753
+                        $add = 'selected ';
3754
+                    }
3755
+                    else
3756
+                    {
3757
+                        $add = '';
3758
+                    }
3759
+                    $output.= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'],$maxlength,'middle').'</option>';
3760
+
3761
+                    $outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
3762
+                }
3763
+            }
3764
+        }
3765
+        $output.= '</select>';
3766
+        $output.= "\n";
3767
+
3768
+        if ($outputmode) return $outarray;
3769
+        return $output;
3770
+    }
3771
+
3772
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3773
+    /**
3774
+     *     Show a confirmation HTML form or AJAX popup
3775
+     *
3776
+     *     @param	string		$page        	   	Url of page to call if confirmation is OK
3777
+     *     @param	string		$title       	   	Title
3778
+     *     @param	string		$question    	   	Question
3779
+     *     @param 	string		$action      	   	Action
3780
+     *	   @param	array		$formquestion	   	An array with forms complementary inputs
3781
+     * 	   @param	string		$selectedchoice		"" or "no" or "yes"
3782
+     * 	   @param	int			$useajax		   	0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=preoutput confirm box with div id=dialog-confirm-xxx
3783
+     *     @param	int			$height          	Force height of box
3784
+     *     @param	int			$width				Force width of box
3785
+     *     @return 	void
3786
+     *     @deprecated
3787
+     *     @see formconfirm()
3788
+     */
3789
+    function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500)
3790
+    {
3791
+        // phpcs:enable
3792
+        dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
3793
+        print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
3794
+    }
3795
+
3796
+    /**
3797
+     *     Show a confirmation HTML form or AJAX popup.
3798
+     *     Easiest way to use this is with useajax=1.
3799
+     *     If you use useajax='xxx', you must also add jquery code to trigger opening of box (with correct parameters)
3800
+     *     just after calling this method. For example:
3801
+     *       print '<script type="text/javascript">'."\n";
3802
+     *       print 'jQuery(document).ready(function() {'."\n";
3803
+     *       print 'jQuery(".xxxlink").click(function(e) { jQuery("#aparamid").val(jQuery(this).attr("rel")); jQuery("#dialog-confirm-xxx").dialog("open"); return false; });'."\n";
3804
+     *       print '});'."\n";
3805
+     *       print '</script>'."\n";
3806
+     *
3807
+     *     @param  	string		$page        	   	Url of page to call if confirmation is OK. Can contains paramaters (param 'action' and 'confirm' will be reformated)
3808
+     *     @param	string		$title       	   	Title
3809
+     *     @param	string		$question    	   	Question
3810
+     *     @param 	string		$action      	   	Action
3811
+     *	   @param  	array		$formquestion	   	An array with complementary inputs to add into forms: array(array('label'=> ,'type'=> , ))
3812
+     *												type can be 'hidden', 'text', 'password', 'checkbox', 'radio', 'date', 'morecss', ...
3813
+     * 	   @param  	string		$selectedchoice  	'' or 'no', or 'yes' or '1' or '0'
3814
+     * 	   @param  	int			$useajax		   	0=No, 1=Yes, 2=Yes but submit page with &confirm=no if choice is No, 'xxx'=Yes and preoutput confirm box with div id=dialog-confirm-xxx
3815
+     *     @param  	int			$height          	Force height of box
3816
+     *     @param	int			$width				Force width of box ('999' or '90%'). Ignored and forced to 90% on smartphones.
3817
+     *     @param	int			$disableformtag		1=Disable form tag. Can be used if we are already inside a <form> section.
3818
+     *     @return 	string      	    			HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
3819
+     */
3820
+    function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice='', $useajax=0, $height=210, $width=500, $disableformtag=0)
3821
+    {
3822
+        global $langs,$conf;
3823
+        global $useglobalvars;
3824
+
3825
+        $more='';
3826
+        $formconfirm='';
3827
+        $inputok=array();
3828
+        $inputko=array();
3829
+
3830
+        // Clean parameters
3831
+        $newselectedchoice=empty($selectedchoice)?"no":$selectedchoice;
3832
+        if ($conf->browser->layout == 'phone') $width='95%';
3833
+
3834
+        if (is_array($formquestion) && ! empty($formquestion))
3835
+        {
3836
+            // First add hidden fields and value
3837
+            foreach ($formquestion as $key => $input)
3838
+            {
3839
+                if (is_array($input) && ! empty($input))
3840
+                {
3841
+                    if ($input['type'] == 'hidden')
3842
+                    {
3843
+                        $more.='<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
3844
+                    }
3845
+                }
3846
+            }
3847
+
3848
+            // Now add questions
3849
+            $more.='<table class="paddingtopbottomonly" width="100%">'."\n";
3850
+            if (! empty($formquestion['text'])) $more.='<tr><td colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
3851
+            foreach ($formquestion as $key => $input)
3852
+            {
3853
+                if (is_array($input) && ! empty($input))
3854
+                {
3855
+                    $size=(! empty($input['size'])?' size="'.$input['size'].'"':'');
3856
+                    $moreattr=(! empty($input['moreattr'])?' '.$input['moreattr']:'');
3857
+                    $morecss=(! empty($input['morecss'])?' '.$input['morecss']:'');
3858
+
3859
+                    if ($input['type'] == 'text')
3860
+                    {
3861
+                        $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="text" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3862
+                    }
3863
+                    elseif ($input['type'] == 'password')
3864
+                    {
3865
+                        $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="password" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3866
+                    }
3867
+                    elseif ($input['type'] == 'select')
3868
+                    {
3869
+                        $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
3870
+                        if (! empty($input['label'])) $more.=$input['label'].'</td><td class="tdtop" align="left">';
3871
+                        $more.=$this->selectarray($input['name'],$input['values'],$input['default'],1,0,0,$moreattr,0,0,0,'',$morecss);
3872
+                        $more.='</td></tr>'."\n";
3873
+                    }
3874
+                    elseif ($input['type'] == 'checkbox')
3875
+                    {
3876
+                        $more.='<tr>';
3877
+                        $more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].' </td><td align="left">';
3878
+                        $more.='<input type="checkbox" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$moreattr;
3879
+                        if (! is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') $more.=' checked';
3880
+                        if (is_bool($input['value']) && $input['value']) $more.=' checked';
3881
+                        if (isset($input['disabled'])) $more.=' disabled';
3882
+                        $more.=' /></td>';
3883
+                        $more.='</tr>'."\n";
3884
+                    }
3885
+                    elseif ($input['type'] == 'radio')
3886
+                    {
3887
+                        $i=0;
3888
+                        foreach($input['values'] as $selkey => $selval)
3889
+                        {
3890
+                            $more.='<tr>';
3891
+                            if ($i==0) $more.='<td'.(empty($input['tdclass'])?' class="tdtop"':(' class="tdtop '.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3892
+                            else $more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>&nbsp;</td>';
3893
+                            $more.='<td><input type="radio" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"'.$moreattr;
3894
+                            if ($input['disabled']) $more.=' disabled';
3895
+                            $more.=' /> ';
3896
+                            $more.=$selval;
3897
+                            $more.='</td></tr>'."\n";
3898
+                            $i++;
3899
+                        }
3900
+                    }
3901
+                    elseif ($input['type'] == 'date')
3902
+                    {
3903
+                        $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3904
+                        $more.='<td align="left">';
3905
+                        $more.=$this->selectDate($input['value'],$input['name'],0,0,0,'',1,0);
3906
+                        $more.='</td></tr>'."\n";
3907
+                        $formquestion[] = array('name'=>$input['name'].'day');
3908
+                        $formquestion[] = array('name'=>$input['name'].'month');
3909
+                        $formquestion[] = array('name'=>$input['name'].'year');
3910
+                        $formquestion[] = array('name'=>$input['name'].'hour');
3911
+                        $formquestion[] = array('name'=>$input['name'].'min');
3912
+                    }
3913
+                    elseif ($input['type'] == 'other')
3914
+                    {
3915
+                        $more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
3916
+                        if (! empty($input['label'])) $more.=$input['label'].'</td><td align="left">';
3917
+                        $more.=$input['value'];
3918
+                        $more.='</td></tr>'."\n";
3919
+                    }
3920
+
3921
+                    elseif ($input['type'] == 'onecolumn')
3922
+                    {
3923
+                        $more.='<tr><td colspan="2" align="left">';
3924
+                        $more.=$input['value'];
3925
+                        $more.='</td></tr>'."\n";
3926
+                    }
3927
+                }
3928
+            }
3929
+            $more.='</table>'."\n";
3930
+        }
3931
+
3932
+        // JQUI method dialog is broken with jmobile, we use standard HTML.
3933
+        // Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx
3934
+        // See page product/card.php for example
3935
+        if (! empty($conf->dol_use_jmobile)) $useajax=0;
3936
+        if (empty($conf->use_javascript_ajax)) $useajax=0;
3937
+
3938
+        if ($useajax)
3939
+        {
3940
+            $autoOpen=true;
3941
+            $dialogconfirm='dialog-confirm';
3942
+            $button='';
3943
+            if (! is_numeric($useajax))
3944
+            {
3945
+                $button=$useajax;
3946
+                $useajax=1;
3947
+                $autoOpen=false;
3948
+                $dialogconfirm.='-'.$button;
3949
+            }
3950
+            $pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes';
3951
+            $pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':'');
3952
+            // Add input fields into list of fields to read during submit (inputok and inputko)
3953
+            if (is_array($formquestion))
3954
+            {
3955
+                foreach ($formquestion as $key => $input)
3956
+                {
3957
+                    //print "xx ".$key." rr ".is_array($input)."<br>\n";
3958
+                    if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']);
3959
+                    if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']);
3960
+                }
3961
+            }
3962
+            // Show JQuery confirm box. Note that global var $useglobalvars is used inside this template
3963
+            $formconfirm.= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
3964
+            if (! empty($more)) {
3965
+                $formconfirm.= '<div class="confirmquestions">'.$more.'</div>';
3966
+            }
3967
+            $formconfirm.= ($question ? '<div class="confirmmessage">'.img_help('','').' '.$question . '</div>': '');
3968
+            $formconfirm.= '</div>'."\n";
3969
+
3970
+            $formconfirm.= "\n<!-- begin ajax formconfirm page=".$page." -->\n";
3971
+            $formconfirm.= '<script type="text/javascript">'."\n";
3972
+            $formconfirm.= 'jQuery(document).ready(function() {
3973
+            $(function() {
3974
+            	$( "#'.$dialogconfirm.'" ).dialog(
3975
+            	{
3976
+                    autoOpen: '.($autoOpen ? "true" : "false").',';
3977
+            if ($newselectedchoice == 'no')
3978
+            {
3979
+                $formconfirm.='
3980
+						open: function() {
3981
+            				$(this).parent().find("button.ui-button:eq(2)").focus();
3982
+						},';
3983
+            }
3984
+            $formconfirm.='
3985
+                    resizable: false,
3986
+                    height: "'.$height.'",
3987
+                    width: "'.$width.'",
3988
+                    modal: true,
3989
+                    closeOnEscape: false,
3990
+                    buttons: {
3991
+                        "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
3992
+                        	var options="";
3993
+                        	var inputok = '.json_encode($inputok).';
3994
+                         	var pageyes = "'.dol_escape_js(! empty($pageyes)?$pageyes:'').'";
3995
+                         	if (inputok.length>0) {
3996
+                         		$.each(inputok, function(i, inputname) {
3997
+                         			var more = "";
3998
+                         			if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
3999
+                         		    if ($("#" + inputname).attr("type") == "radio") { more = ":checked"; }
4000
+                         			var inputvalue = $("#" + inputname + more).val();
4001
+                         			if (typeof inputvalue == "undefined") { inputvalue=""; }
4002
+                         			options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
4003
+                         		});
4004
+                         	}
4005
+                         	var urljump = pageyes + (pageyes.indexOf("?") < 0 ? "?" : "") + options;
4006
+                         	//alert(urljump);
4007
+            				if (pageyes.length > 0) { location.href = urljump; }
4008
+                            $(this).dialog("close");
4009
+                        },
4010
+                        "'.dol_escape_js($langs->transnoentities("No")).'": function() {
4011
+                        	var options = "";
4012
+                         	var inputko = '.json_encode($inputko).';
4013
+                         	var pageno="'.dol_escape_js(! empty($pageno)?$pageno:'').'";
4014
+                         	if (inputko.length>0) {
4015
+                         		$.each(inputko, function(i, inputname) {
4016
+                         			var more = "";
4017
+                         			if ($("#" + inputname).attr("type") == "checkbox") { more = ":checked"; }
4018
+                         			var inputvalue = $("#" + inputname + more).val();
4019
+                         			if (typeof inputvalue == "undefined") { inputvalue=""; }
4020
+                         			options += "&" + inputname + "=" + encodeURIComponent(inputvalue);
4021
+                         		});
4022
+                         	}
4023
+                         	var urljump=pageno + (pageno.indexOf("?") < 0 ? "?" : "") + options;
4024
+                         	//alert(urljump);
4025
+            				if (pageno.length > 0) { location.href = urljump; }
4026
+                            $(this).dialog("close");
4027
+                        }
4028
+                    }
4029
+                }
4030
+                );
4031
+
4032
+            	var button = "'.$button.'";
4033
+            	if (button.length > 0) {
4034
+                	$( "#" + button ).click(function() {
4035
+                		$("#'.$dialogconfirm.'").dialog("open");
4036
+        			});
4037
+                }
4038
+            });
4039
+            });
4040
+            </script>';
4041
+            $formconfirm.= "<!-- end ajax formconfirm -->\n";
4042
+        }
4043
+        else
4044
+        {
4045
+            $formconfirm.= "\n<!-- begin formconfirm page=".$page." -->\n";
4046
+
4047
+            if (empty($disableformtag)) $formconfirm.= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
4048
+
4049
+            $formconfirm.= '<input type="hidden" name="action" value="'.$action.'">'."\n";
4050
+            if (empty($disableformtag)) $formconfirm.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
4051
+
4052
+            $formconfirm.= '<table width="100%" class="valid">'."\n";
4053
+
4054
+            // Line title
4055
+            $formconfirm.= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('','recent').' '.$title.'</td></tr>'."\n";
4056
+
4057
+            // Line form fields
4058
+            if ($more)
4059
+            {
4060
+                $formconfirm.='<tr class="valid"><td class="valid" colspan="3">'."\n";
4061
+                $formconfirm.=$more;
4062
+                $formconfirm.='</td></tr>'."\n";
4063
+            }
4064
+
4065
+            // Line with question
4066
+            $formconfirm.= '<tr class="valid">';
4067
+            $formconfirm.= '<td class="valid">'.$question.'</td>';
4068
+            $formconfirm.= '<td class="valid">';
4069
+            $formconfirm.= $this->selectyesno("confirm",$newselectedchoice);
4070
+            $formconfirm.= '</td>';
4071
+            $formconfirm.= '<td class="valid" align="center"><input class="button valignmiddle" type="submit" value="'.$langs->trans("Validate").'"></td>';
4072
+            $formconfirm.= '</tr>'."\n";
4073
+
4074
+            $formconfirm.= '</table>'."\n";
4075
+
4076
+            if (empty($disableformtag)) $formconfirm.= "</form>\n";
4077
+            $formconfirm.= '<br>';
4078
+
4079
+            $formconfirm.= "<!-- end formconfirm -->\n";
4080
+        }
4081
+
4082
+        return $formconfirm;
4083
+    }
4084
+
4085
+
4086
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4087
+    /**
4088
+     *    Show a form to select a project
4089
+     *
4090
+     *    @param	int		$page        		Page
4091
+     *    @param	int		$socid       		Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
4092
+     *    @param    int		$selected    		Id pre-selected project
4093
+     *    @param    string	$htmlname    		Name of select field
4094
+     *    @param	int		$discard_closed		Discard closed projects (0=Keep,1=hide completely except $selected,2=Disable)
4095
+     *    @param	int		$maxlength			Max length
4096
+     *    @param	int		$forcefocus			Force focus on field (works with javascript only)
4097
+     *    @param    int     $nooutput           No print is done. String is returned.
4098
+     *    @return	string                      Return html content
4099
+     */
4100
+    function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0)
4101
+    {
4102
+        // phpcs:enable
4103
+        global $langs;
4104
+
4105
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
4106
+        require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
4107
+
4108
+        $out='';
4109
+
4110
+        $formproject=new FormProjets($this->db);
4111
+
4112
+        $langs->load("project");
4113
+        if ($htmlname != "none")
4114
+        {
4115
+            $out.="\n";
4116
+            $out.='<form method="post" action="'.$page.'">';
4117
+            $out.='<input type="hidden" name="action" value="classin">';
4118
+            $out.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4119
+            $out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
4120
+            $out.='<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4121
+            $out.='</form>';
4122
+        }
4123
+        else
4124
+        {
4125
+            if ($selected)
4126
+            {
4127
+                $projet = new Project($this->db);
4128
+                $projet->fetch($selected);
4129
+                //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
4130
+                $out.=$projet->getNomUrl(0,'',1);
4131
+            }
4132
+            else
4133
+            {
4134
+                $out.="&nbsp;";
4135
+            }
4136
+        }
4137
+
4138
+        if (empty($nooutput))
4139
+        {
4140
+            print $out;
4141
+            return '';
4142
+        }
4143
+        return $out;
4144
+    }
4145
+
4146
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4147
+    /**
4148
+     *	Show a form to select payment conditions
4149
+     *
4150
+     *  @param	int		$page        	Page
4151
+     *  @param  string	$selected    	Id condition pre-selectionne
4152
+     *  @param  string	$htmlname    	Name of select html field
4153
+     *	@param	int		$addempty		Add empty entry
4154
+     *  @return	void
4155
+     */
4156
+    function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0)
4157
+    {
4158
+        // phpcs:enable
4159
+        global $langs;
4160
+        if ($htmlname != "none")
4161
+        {
4162
+            print '<form method="post" action="'.$page.'">';
4163
+            print '<input type="hidden" name="action" value="setconditions">';
4164
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4165
+            $this->select_conditions_paiements($selected,$htmlname,-1,$addempty);
4166
+            print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4167
+            print '</form>';
4168
+        }
4169
+        else
4170
+        {
4171
+            if ($selected)
4172
+            {
4173
+                $this->load_cache_conditions_paiements();
4174
+                print $this->cache_conditions_paiements[$selected]['label'];
4175
+            } else {
4176
+                print "&nbsp;";
4177
+            }
4178
+        }
4179
+    }
4180
+
4181
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4182
+    /**
4183
+     *  Show a form to select a delivery delay
4184
+     *
4185
+     *  @param  int		$page        	Page
4186
+     *  @param  string	$selected    	Id condition pre-selectionne
4187
+     *  @param  string	$htmlname    	Name of select html field
4188
+     *	@param	int		$addempty		Ajoute entree vide
4189
+     *  @return	void
4190
+     */
4191
+    function form_availability($page, $selected='', $htmlname='availability', $addempty=0)
4192
+    {
4193
+        // phpcs:enable
4194
+        global $langs;
4195
+        if ($htmlname != "none")
4196
+        {
4197
+            print '<form method="post" action="'.$page.'">';
4198
+            print '<input type="hidden" name="action" value="setavailability">';
4199
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4200
+            $this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty);
4201
+            print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4202
+            print '</form>';
4203
+        }
4204
+        else
4205
+        {
4206
+            if ($selected)
4207
+            {
4208
+                $this->load_cache_availability();
4209
+                print $this->cache_availability[$selected]['label'];
4210
+            } else {
4211
+                print "&nbsp;";
4212
+            }
4213
+        }
4214
+    }
4215
+
4216
+    /**
4217
+     *	Output HTML form to select list of input reason (events that triggered an object creation, like after sending an emailing, making an advert, ...)
4218
+     *  List found into table c_input_reason loaded by loadCacheInputReason
4219
+     *
4220
+     *  @param  string	$page        	Page
4221
+     *  @param  string	$selected    	Id condition pre-selectionne
4222
+     *  @param  string	$htmlname    	Name of select html field
4223
+     *	@param	int		$addempty		Add empty entry
4224
+     *  @return	void
4225
+     */
4226
+    function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0)
4227
+    {
4228
+        global $langs;
4229
+        if ($htmlname != "none")
4230
+        {
4231
+            print '<form method="post" action="'.$page.'">';
4232
+            print '<input type="hidden" name="action" value="setdemandreason">';
4233
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4234
+            $this->selectInputReason($selected,$htmlname,-1,$addempty);
4235
+            print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4236
+            print '</form>';
4237
+        }
4238
+        else
4239
+        {
4240
+            if ($selected)
4241
+            {
4242
+                $this->loadCacheInputReason();
4243
+                foreach ($this->cache_demand_reason as $key => $val)
4244
+                {
4245
+                    if ($val['id'] == $selected)
4246
+                    {
4247
+                        print $val['label'];
4248
+                        break;
4249
+                    }
4250
+                }
4251
+            } else {
4252
+                print "&nbsp;";
4253
+            }
4254
+        }
4255
+    }
4256
+
4257
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4258
+    /**
4259
+     *    Show a form + html select a date
4260
+     *
4261
+     *    @param	string		$page        	Page
4262
+     *    @param	string		$selected    	Date preselected
4263
+     *    @param    string		$htmlname    	Html name of date input fields or 'none'
4264
+     *    @param    int			$displayhour 	Display hour selector
4265
+     *    @param    int			$displaymin		Display minutes selector
4266
+     *    @param	int			$nooutput		1=No print output, return string
4267
+     *    @return	string
4268
+     *    @see		selectDate
4269
+     */
4270
+    function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0)
4271
+    {
4272
+        // phpcs:enable
4273
+        global $langs;
4274
+
4275
+        $ret='';
4276
+
4277
+        if ($htmlname != "none")
4278
+        {
4279
+            $ret.='<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
4280
+            $ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
4281
+            $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4282
+            $ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
4283
+            $ret.='<tr><td>';
4284
+            $ret.=$this->selectDate($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0);
4285
+            $ret.='</td>';
4286
+            $ret.='<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
4287
+            $ret.='</tr></table></form>';
4288
+        }
4289
+        else
4290
+        {
4291
+            if ($displayhour) $ret.=dol_print_date($selected,'dayhour');
4292
+            else $ret.=dol_print_date($selected,'day');
4293
+        }
4294
+
4295
+        if (empty($nooutput)) print $ret;
4296
+        return $ret;
4297
+    }
4298
+
4299
+
4300
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4301
+    /**
4302
+     *  Show a select form to choose a user
4303
+     *
4304
+     *  @param	string	$page        	Page
4305
+     *  @param  string	$selected    	Id of user preselected
4306
+     *  @param  string	$htmlname    	Name of input html field. If 'none', we just output the user link.
4307
+     *  @param  array	$exclude		List of users id to exclude
4308
+     *  @param  array	$include        List of users id to include
4309
+     *  @return	void
4310
+     */
4311
+    function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='')
4312
+    {
4313
+        // phpcs:enable
4314
+        global $langs;
4315
+
4316
+        if ($htmlname != "none")
4317
+        {
4318
+            print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
4319
+            print '<input type="hidden" name="action" value="set'.$htmlname.'">';
4320
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4321
+            print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include);
4322
+            print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4323
+            print '</form>';
4324
+        }
4325
+        else
4326
+        {
4327
+            if ($selected)
4328
+            {
4329
+                require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';
4330
+                $theuser=new User($this->db);
4331
+                $theuser->fetch($selected);
4332
+                print $theuser->getNomUrl(1);
4333
+            } else {
4334
+                print "&nbsp;";
4335
+            }
4336
+        }
4337
+    }
4338
+
4339
+
4340
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4341
+    /**
4342
+     *    Show form with payment mode
4343
+     *
4344
+     *    @param	string	$page        	Page
4345
+     *    @param    int		$selected    	Id mode pre-selectionne
4346
+     *    @param    string	$htmlname    	Name of select html field
4347
+     *    @param  	string	$filtertype		To filter on field type in llx_c_paiement (array('code'=>xx,'label'=>zz))
4348
+     *    @param    int     $active         Active or not, -1 = all
4349
+     *    @return	void
4350
+     */
4351
+    function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1)
4352
+    {
4353
+        // phpcs:enable
4354
+        global $langs;
4355
+        if ($htmlname != "none")
4356
+        {
4357
+            print '<form method="POST" action="'.$page.'">';
4358
+            print '<input type="hidden" name="action" value="setmode">';
4359
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4360
+            $this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active);
4361
+            print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4362
+            print '</form>';
4363
+        }
4364
+        else
4365
+        {
4366
+            if ($selected)
4367
+            {
4368
+                $this->load_cache_types_paiements();
4369
+                print $this->cache_types_paiements[$selected]['label'];
4370
+            } else {
4371
+                print "&nbsp;";
4372
+            }
4373
+        }
4374
+    }
4375
+
4376
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4377
+    /**
4378
+     *    Show form with multicurrency code
4379
+     *
4380
+     *    @param	string	$page        	Page
4381
+     *    @param    string	$selected    	code pre-selectionne
4382
+     *    @param    string	$htmlname    	Name of select html field
4383
+     *    @return	void
4384
+     */
4385
+    function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code')
4386
+    {
4387
+        // phpcs:enable
4388
+        global $langs;
4389
+        if ($htmlname != "none")
4390
+        {
4391
+            print '<form method="POST" action="'.$page.'">';
4392
+            print '<input type="hidden" name="action" value="setmulticurrencycode">';
4393
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4394
+            print $this->selectMultiCurrency($selected, $htmlname, 0);
4395
+            print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4396
+            print '</form>';
4397
+        }
4398
+        else
4399
+        {
4400
+            dol_include_once('/core/lib/company.lib.php');
4401
+            print !empty($selected) ? currency_name($selected,1) : '&nbsp;';
4402
+        }
4403
+    }
4404
+
4405
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4406
+    /**
4407
+     *    Show form with multicurrency rate
4408
+     *
4409
+     *    @param	string	$page        	Page
4410
+     *    @param    double	$rate	    	Current rate
4411
+     *    @param    string	$htmlname    	Name of select html field
4412
+     *    @param    string  $currency       Currency code to explain the rate
4413
+     *    @return	void
4414
+     */
4415
+    function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='')
4416
+    {
4417
+        // phpcs:enable
4418
+        global $langs, $mysoc, $conf;
4419
+
4420
+        if ($htmlname != "none")
4421
+        {
4422
+            print '<form method="POST" action="'.$page.'">';
4423
+            print '<input type="hidden" name="action" value="setmulticurrencyrate">';
4424
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4425
+            print '<input type="text" name="'.$htmlname.'" value="'.(!empty($rate) ? price($rate) : 1).'" size="10" /> ';
4426
+            print '<select name="calculation_mode">';
4427
+            print '<option value="1">'.$currency.' > '.$conf->currency.'</option>';
4428
+            print '<option value="2">'.$conf->currency.' > '.$currency.'</option>';
4429
+            print '</select> ';
4430
+            print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4431
+            print '</form>';
4432
+        }
4433
+        else
4434
+        {
4435
+            if (! empty($rate))
4436
+            {
4437
+                print price($rate, 1, $langs, 1, 0);
4438
+                if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
4439
+            }
4440
+            else
4441
+            {
4442
+                print 1;
4443
+            }
4444
+        }
4445
+    }
4446
+
4447
+
4448
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4449
+    /**
4450
+     *	Show a select box with available absolute discounts
4451
+     *
4452
+     *  @param  string	$page        	Page URL where form is shown
4453
+     *  @param  int		$selected    	Value pre-selected
4454
+     *	@param  string	$htmlname    	Name of SELECT component. If 'none', not changeable. Example 'remise_id'.
4455
+     *	@param	int		$socid			Third party id
4456
+     * 	@param	float	$amount			Total amount available
4457
+     * 	@param	string	$filter			SQL filter on discounts
4458
+     * 	@param	int		$maxvalue		Max value for lines that can be selected
4459
+     *  @param  string	$more           More string to add
4460
+     *  @param  int     $hidelist       1=Hide list
4461
+     *  @param	int		$discount_type	0 => customer discount, 1 => supplier discount
4462
+     *  @return	void
4463
+     */
4464
+    function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $discount_type=0)
4465
+    {
4466
+        // phpcs:enable
4467
+        global $conf,$langs;
4468
+        if ($htmlname != "none")
4469
+        {
4470
+            print '<form method="post" action="'.$page.'">';
4471
+            print '<input type="hidden" name="action" value="setabsolutediscount">';
4472
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4473
+            print '<div class="inline-block">';
4474
+            if(! empty($discount_type)) {
4475
+                if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4476
+                {
4477
+                    if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier';    // If we want deposit to be substracted to payments only and not to total of final invoice
4478
+                    else $translationKey = 'HasCreditNoteFromSupplier';
4479
+                }
4480
+                else
4481
+                {
4482
+                    if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier';
4483
+                    else $translationKey = 'HasCreditNoteFromSupplier';
4484
+                }
4485
+            } else {
4486
+                if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4487
+                {
4488
+                    if (! $filter || $filter=="fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount';    // If we want deposit to be substracted to payments only and not to total of final invoice
4489
+                    else $translationKey = 'CompanyHasCreditNote';
4490
+                }
4491
+                else
4492
+                {
4493
+                    if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount';
4494
+                    else $translationKey = 'CompanyHasCreditNote';
4495
+                }
4496
+            }
4497
+            print $langs->trans($translationKey,price($amount,0,$langs,0,0,-1,$conf->currency));
4498
+            if (empty($hidelist)) print ': ';
4499
+            print '</div>';
4500
+            if (empty($hidelist))
4501
+            {
4502
+                print '<div class="inline-block" style="padding-right: 10px">';
4503
+                $newfilter = 'discount_type='.intval($discount_type);
4504
+                if(! empty($discount_type)) {
4505
+                    $newfilter.= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
4506
+                } else {
4507
+                    $newfilter.= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
4508
+                }
4509
+                if ($filter) $newfilter.=' AND ('.$filter.')';
4510
+                $nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);
4511
+                if ($nbqualifiedlines > 0)
4512
+                {
4513
+                    print ' &nbsp; <input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
4514
+                    if(! empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')")
4515
+                        print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4516
+                    if(empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')")
4517
+                        print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4518
+
4519
+                    print '>';
4520
+                }
4521
+                print '</div>';
4522
+            }
4523
+            if ($more)
4524
+            {
4525
+                print '<div class="inline-block">';
4526
+                print $more;
4527
+                print '</div>';
4528
+            }
4529
+            print '</form>';
4530
+        }
4531
+        else
4532
+        {
4533
+            if ($selected)
4534
+            {
4535
+                print $selected;
4536
+            }
4537
+            else
4538
+            {
4539
+                print "0";
4540
+            }
4541
+        }
4542
+    }
4543
+
4544
+
4545
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4546
+    /**
4547
+     *    Show forms to select a contact
4548
+     *
4549
+     *    @param	string		$page        	Page
4550
+     *    @param	Societe		$societe		Filter on third party
4551
+     *    @param    int			$selected    	Id contact pre-selectionne
4552
+     *    @param    string		$htmlname    	Name of HTML select. If 'none', we just show contact link.
4553
+     *    @return	void
4554
+     */
4555
+    function form_contacts($page, $societe, $selected='', $htmlname='contactid')
4556
+    {
4557
+        // phpcs:enable
4558
+        global $langs, $conf;
4559
+
4560
+        if ($htmlname != "none")
4561
+        {
4562
+            print '<form method="post" action="'.$page.'">';
4563
+            print '<input type="hidden" name="action" value="set_contact">';
4564
+            print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4565
+            print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
4566
+            print '<tr><td>';
4567
+            $num=$this->select_contacts($societe->id, $selected, $htmlname);
4568
+            if ($num==0)
4569
+            {
4570
+                $addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
4571
+                print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
4572
+            }
4573
+            print '</td>';
4574
+            print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
4575
+            print '</tr></table></form>';
4576
+        }
4577
+        else
4578
+        {
4579
+            if ($selected)
4580
+            {
4581
+                require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php';
4582
+                $contact=new Contact($this->db);
4583
+                $contact->fetch($selected);
4584
+                print $contact->getFullName($langs);
4585
+            } else {
4586
+                print "&nbsp;";
4587
+            }
4588
+        }
4589
+    }
4590
+
4591
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4592
+    /**
4593
+     *  Output html select to select thirdparty
4594
+     *
4595
+     *  @param	string	$page       	Page
4596
+     *  @param  string	$selected   	Id preselected
4597
+     *  @param  string	$htmlname		Name of HTML select
4598
+     *  @param  string	$filter         optional filters criteras
4599
+     *	@param	int		$showempty		Add an empty field
4600
+     * 	@param	int		$showtype		Show third party type in combolist (customer, prospect or supplier)
4601
+     * 	@param	int		$forcecombo		Force to use combo box
4602
+     *  @param	array	$events			Event options. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
4603
+     *  @param  int     $nooutput       No print output. Return it only.
4604
+     *  @return	void
4605
+     */
4606
+    function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array(), $nooutput=0)
4607
+    {
4608
+        // phpcs:enable
4609
+        global $langs;
4610
+
4611
+        $out = '';
4612
+        if ($htmlname != "none")
4613
+        {
4614
+            $out.='<form method="post" action="'.$page.'">';
4615
+            $out.= '<input type="hidden" name="action" value="set_thirdparty">';
4616
+            $out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4617
+            $out.= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
4618
+            $out.= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4619
+            $out.= '</form>';
4620
+        }
4621
+        else
4622
+        {
4623
+            if ($selected)
4624
+            {
4625
+                require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
4626
+                $soc = new Societe($this->db);
4627
+                $soc->fetch($selected);
4628
+                $out.= $soc->getNomUrl($langs);
4629
+            }
4630
+            else
4631
+            {
4632
+                $out.= "&nbsp;";
4633
+            }
4634
+        }
4635
+
4636
+        if ($nooutput) return $out;
4637
+        else print $out;
4638
+    }
4639
+
4640
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4641
+    /**
4642
+     *    Retourne la liste des devises, dans la langue de l'utilisateur
4643
+     *
4644
+     *    @param	string	$selected    preselected currency code
4645
+     *    @param    string	$htmlname    name of HTML select list
4646
+     *    @deprecated
4647
+     *    @return	void
4648
+     */
4649
+    function select_currency($selected='',$htmlname='currency_id')
4650
+    {
4651
+        // phpcs:enable
4652
+        print $this->selectCurrency($selected,$htmlname);
4653
+    }
4654
+
4655
+    /**
4656
+     *  Retourne la liste des devises, dans la langue de l'utilisateur
4657
+     *
4658
+     *  @param	string	$selected    preselected currency code
4659
+     *  @param  string	$htmlname    name of HTML select list
4660
+     * 	@return	string
4661
+     */
4662
+    function selectCurrency($selected='',$htmlname='currency_id')
4663
+    {
4664
+        global $conf,$langs,$user;
4665
+
4666
+        $langs->loadCacheCurrencies('');
4667
+
4668
+        $out='';
4669
+
4670
+        if ($selected=='euro' || $selected=='euros') $selected='EUR';   // Pour compatibilite
4671
+
4672
+        $out.= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
4673
+        foreach ($langs->cache_currencies as $code_iso => $currency)
4674
+        {
4675
+            if ($selected && $selected == $code_iso)
4676
+            {
4677
+                $out.= '<option value="'.$code_iso.'" selected>';
4678
+            }
4679
+            else
4680
+            {
4681
+                $out.= '<option value="'.$code_iso.'">';
4682
+            }
4683
+            $out.= $currency['label'];
4684
+            $out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
4685
+            $out.= '</option>';
4686
+        }
4687
+        $out.= '</select>';
4688
+        if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
4689
+
4690
+        // Make select dynamic
4691
+        include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4692
+        $out .= ajax_combobox($htmlname);
4693
+
4694
+        return $out;
4695
+    }
4696
+
4697
+    /**
4698
+     *	Return array of currencies in user language
4699
+     *
4700
+     *  @param	string	$selected    preselected currency code
4701
+     *  @param  string	$htmlname    name of HTML select list
4702
+     *  @param  integer	$useempty    1=Add empty line
4703
+     * 	@return	string
4704
+     */
4705
+    function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0)
4706
+    {
4707
+        global $db,$conf,$langs,$user;
4708
+
4709
+        $langs->loadCacheCurrencies('');        // Load ->cache_currencies
4710
+
4711
+        $TCurrency = array();
4712
+
4713
+        $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
4714
+        $sql.= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
4715
+        $resql = $db->query($sql);
4716
+        if ($resql)
4717
+        {
4718
+            while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
4719
+        }
4720
+
4721
+        $out='';
4722
+        $out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
4723
+        if ($useempty) $out .= '<option value=""></option>';
4724
+        // If company current currency not in table, we add it into list. Should always be available.
4725
+        if (! in_array($conf->currency, $TCurrency))
4726
+        {
4727
+            $TCurrency[$conf->currency] = $conf->currency;
4728
+        }
4729
+        if (count($TCurrency) > 0)
4730
+        {
4731
+            foreach ($langs->cache_currencies as $code_iso => $currency)
4732
+            {
4733
+                if (isset($TCurrency[$code_iso]))
4734
+                {
4735
+                    if (!empty($selected) && $selected == $code_iso) $out.= '<option value="'.$code_iso.'" selected="selected">';
4736
+                    else $out.= '<option value="'.$code_iso.'">';
4737
+
4738
+                    $out.= $currency['label'];
4739
+                    $out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
4740
+                    $out.= '</option>';
4741
+                }
4742
+            }
4743
+        }
4744
+
4745
+        $out.= '</select>';
4746
+        // Make select dynamic
4747
+        include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4748
+        $out.= ajax_combobox($htmlname);
4749
+
4750
+        return $out;
4751
+    }
4752
+
4753
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4754
+    /**
4755
+     *	Load into the cache vat rates of a country
4756
+     *
4757
+     *	@param	string	$country_code		Country code with quotes ("'CA'", or "'CA,IN,...'")
4758
+     *	@return	int							Nb of loaded lines, 0 if already loaded, <0 if KO
4759
+     */
4760
+    function load_cache_vatrates($country_code)
4761
+    {
4762
+        // phpcs:enable
4763
+        global $langs;
4764
+
4765
+        $num = count($this->cache_vatrates);
4766
+        if ($num > 0) return $num;    // Cache already loaded
4767
+
4768
+        dol_syslog(__METHOD__, LOG_DEBUG);
4769
+
4770
+        $sql  = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
4771
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4772
+        $sql.= " WHERE t.fk_pays = c.rowid";
4773
+        $sql.= " AND t.active > 0";
4774
+        $sql.= " AND c.code IN (".$country_code.")";
4775
+        $sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
4776
+
4777
+        $resql=$this->db->query($sql);
4778
+        if ($resql)
4779
+        {
4780
+            $num = $this->db->num_rows($resql);
4781
+            if ($num)
4782
+            {
4783
+                for ($i = 0; $i < $num; $i++)
4784
+                {
4785
+                    $obj = $this->db->fetch_object($resql);
4786
+                    $this->cache_vatrates[$i]['rowid']	= $obj->rowid;
4787
+                    $this->cache_vatrates[$i]['code']	= $obj->code;
4788
+                    $this->cache_vatrates[$i]['txtva']	= $obj->taux;
4789
+                    $this->cache_vatrates[$i]['nprtva']	= $obj->recuperableonly;
4790
+                    $this->cache_vatrates[$i]['localtax1']	    = $obj->localtax1;
4791
+                    $this->cache_vatrates[$i]['localtax1_type']	= $obj->localtax1_type;
4792
+                    $this->cache_vatrates[$i]['localtax2']	    = $obj->localtax2;
4793
+                    $this->cache_vatrates[$i]['localtax2_type']	= $obj->localtax1_type;
4794
+
4795
+                    $this->cache_vatrates[$i]['label']	= $obj->taux.'%'.($obj->code?' ('.$obj->code.')':'');   // Label must contains only 0-9 , . % or *
4796
+                    $this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':'');	// Must never be used as key, only label
4797
+                    $positiverates='';
4798
+                    if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux;
4799
+                    if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1;
4800
+                    if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2;
4801
+                    if (empty($positiverates)) $positiverates='0';
4802
+                    $this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':'');	// Must never be used as key, only label
4803
+                }
4804
+
4805
+                return $num;
4806
+            }
4807
+            else
4808
+            {
4809
+                $this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).'</font>';
4810
+                return -1;
4811
+            }
4812
+        }
4813
+        else
4814
+        {
4815
+            $this->error = '<font class="error">'.$this->db->error().'</font>';
4816
+            return -2;
4817
+        }
4818
+    }
4819
+
4820
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4821
+    /**
4822
+     *  Output an HTML select vat rate.
4823
+     *  The name of this function should be selectVat. We keep bad name for compatibility purpose.
4824
+     *
4825
+     *  @param	string	      $htmlname           Name of HTML select field
4826
+     *  @param  float|string  $selectedrate       Force preselected vat rate. Can be '8.5' or '8.5 (NOO)' for example. Use '' for no forcing.
4827
+     *  @param  Societe	      $societe_vendeuse   Thirdparty seller
4828
+     *  @param  Societe	      $societe_acheteuse  Thirdparty buyer
4829
+     *  @param  int		      $idprod             Id product. O if unknown of NA.
4830
+     *  @param  int		      $info_bits          Miscellaneous information on line (1 for NPR)
4831
+     *  @param  int|string    $type               ''=Unknown, 0=Product, 1=Service (Used if idprod not defined)
4832
+     *                  		                  Si vendeur non assujeti a TVA, TVA par defaut=0. Fin de regle.
4833
+     *                  					      Si le (pays vendeur = pays acheteur) alors la TVA par defaut=TVA du produit vendu. Fin de regle.
4834
+     *                  					      Si (vendeur et acheteur dans Communaute europeenne) et bien vendu = moyen de transports neuf (auto, bateau, avion), TVA par defaut=0 (La TVA doit etre paye par l'acheteur au centre d'impots de son pays et non au vendeur). Fin de regle.
4835
+     *                                            Si vendeur et acheteur dans Communauté européenne et acheteur= particulier alors TVA par défaut=TVA du produit vendu. Fin de règle.
4836
+     *                                            Si vendeur et acheteur dans Communauté européenne et acheteur= entreprise alors TVA par défaut=0. Fin de règle.
4837
+     *                  					      Sinon la TVA proposee par defaut=0. Fin de regle.
4838
+     *  @param	bool	     $options_only		  Return HTML options lines only (for ajax treatment)
4839
+     *  @param  int          $mode                0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key
4840
+     *  @return	string
4841
+     */
4842
+    function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0)
4843
+    {
4844
+        // phpcs:enable
4845
+        global $langs,$conf,$mysoc;
4846
+
4847
+        $langs->load('errors');
4848
+
4849
+        $return='';
4850
+
4851
+        // Define defaultnpr, defaultttx and defaultcode
4852
+        $defaultnpr=($info_bits & 0x01);
4853
+        $defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr);
4854
+        $defaulttx=str_replace('*','',$selectedrate);
4855
+        $defaultcode='';
4856
+        if (preg_match('/\((.*)\)/', $defaulttx, $reg))
4857
+        {
4858
+            $defaultcode=$reg[1];
4859
+            $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
4860
+        }
4861
+        //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
4862
+
4863
+        // Check parameters
4864
+        if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)
4865
+        {
4866
+            if ($societe_vendeuse->id == $mysoc->id)
4867
+            {
4868
+                $return.= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</div>';
4869
+            }
4870
+            else
4871
+            {
4872
+                $return.= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</div>';
4873
+            }
4874
+            return $return;
4875
+        }
4876
+
4877
+        //var_dump($societe_acheteuse);
4878
+        //print "name=$name, selectedrate=$selectedrate, seller=".$societe_vendeuse->country_code." buyer=".$societe_acheteuse->country_code." buyer is company=".$societe_acheteuse->isACompany()." idprod=$idprod, info_bits=$info_bits type=$type";
4879
+        //exit;
4880
+
4881
+        // Define list of countries to use to search VAT rates to show
4882
+        // First we defined code_country to use to find list
4883
+        if (is_object($societe_vendeuse))
4884
+        {
4885
+            $code_country="'".$societe_vendeuse->country_code."'";
4886
+        }
4887
+        else
4888
+        {
4889
+            $code_country="'".$mysoc->country_code."'";   // Pour compatibilite ascendente
4890
+        }
4891
+        if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))    // If option to have vat for end customer for services is on
4892
+        {
4893
+            require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4894
+            if (! isInEEC($societe_vendeuse) && (! is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && ! $societe_acheteuse->isACompany())))
4895
+            {
4896
+                // We also add the buyer
4897
+                if (is_numeric($type))
4898
+                {
4899
+                    if ($type == 1) // We know product is a service
4900
+                    {
4901
+                        $code_country.=",'".$societe_acheteuse->country_code."'";
4902
+                    }
4903
+                }
4904
+                else if (! $idprod)  // We don't know type of product
4905
+                {
4906
+                    $code_country.=",'".$societe_acheteuse->country_code."'";
4907
+                }
4908
+                else
4909
+                {
4910
+                    $prodstatic=new Product($this->db);
4911
+                    $prodstatic->fetch($idprod);
4912
+                    if ($prodstatic->type == Product::TYPE_SERVICE)   // We know product is a service
4913
+                    {
4914
+                        $code_country.=",'".$societe_acheteuse->country_code."'";
4915
+                    }
4916
+                }
4917
+            }
4918
+        }
4919
+
4920
+        // Now we get list
4921
+        $num = $this->load_cache_vatrates($code_country);   // If no vat defined, return -1 with message into this->error
4922
+
4923
+        if ($num > 0)
4924
+        {
4925
+            // Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
4926
+            if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
4927
+            {
4928
+                $tmpthirdparty=new Societe($this->db);
4929
+                $defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
4930
+                $defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
4931
+                if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
4932
+                    $defaultcode=$reg[1];
4933
+                    $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
4934
+                }
4935
+                if (empty($defaulttx)) $defaultnpr=0;
4936
+            }
4937
+
4938
+            // Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
4939
+            // Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
4940
+            if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
4941
+            {
4942
+                if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva'];
4943
+                else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
4944
+            }
4945
+
4946
+            // Disabled if seller is not subject to VAT
4947
+            $disabled=false; $title='';
4948
+            if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0")
4949
+            {
4950
+                // Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses
4951
+                if (empty($conf->global->OVERRIDE_VAT_FOR_EXPENSE_REPORT))
4952
+                {
4953
+                    $title=' title="'.$langs->trans('VATIsNotUsed').'"';
4954
+                    $disabled=true;
4955
+                }
4956
+            }
4957
+
4958
+            if (! $options_only) $return.= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$title.'>';
4959
+
4960
+            $selectedfound=false;
4961
+            foreach ($this->cache_vatrates as $rate)
4962
+            {
4963
+                // Keep only 0 if seller is not subject to VAT
4964
+                if ($disabled && $rate['txtva'] != 0) continue;
4965
+
4966
+                // Define key to use into select list
4967
+                $key = $rate['txtva'];
4968
+                $key.= $rate['nprtva'] ? '*': '';
4969
+                if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')';
4970
+                if ($mode < 0) $key = $rate['rowid'];
4971
+
4972
+                $return.= '<option value="'.$key.'"';
4973
+                if (! $selectedfound)
4974
+                {
4975
+                    if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
4976
+                    {
4977
+                        if ($defaultcode == $rate['code'])
4978
+                        {
4979
+                            $return.= ' selected';
4980
+                            $selectedfound=true;
4981
+                        }
4982
+                    }
4983
+                    elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
4984
+                        {
4985
+                            $return.= ' selected';
4986
+                            $selectedfound=true;
4987
+                    }
4988
+                }
4989
+                $return.= '>';
4990
+                //if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
4991
+                if ($mysoc->country_code == 'IN' || ! empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))
4992
+                {
4993
+                    $return.= $rate['labelpositiverates'];
4994
+                }
4995
+                else
4996
+                {
4997
+                    $return.= vatrate($rate['label']);
4998
+                }
4999
+                //$return.=($rate['code']?' '.$rate['code']:'');
5000
+                $return.= (empty($rate['code']) && $rate['nprtva']) ? ' *': '';         // We show the *  (old behaviour only if new vat code is not used)
5001
+
5002
+                $return.= '</option>';
5003
+            }
5004
+
5005
+            if (! $options_only) $return.= '</select>';
5006
+        }
5007
+        else
5008
+        {
5009
+            $return.= $this->error;
5010
+        }
5011
+
5012
+        $this->num = $num;
5013
+        return $return;
5014
+    }
5015
+
5016
+
5017
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
5018
+    /**
5019
+     *  Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
5020
+     *  Fields are preselected with :
5021
+     *            	- set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
5022
+     *            	- local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
5023
+     *            	- Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
5024
+     *
5025
+     *	@param	timestamp	$set_time 		Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
5026
+     *	@param	string		$prefix			Prefix for fields name
5027
+     *	@param	int			$h				1 or 2=Show also hours (2=hours on a new line), -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show hour always empty
5028
+     *	@param	int			$m				1=Show also minutes, -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show minutes always empty
5029
+     *	@param	int			$empty			0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
5030
+     *	@param	string		$form_name 		Not used
5031
+     *	@param	int			$d				1=Show days, month, years
5032
+     * 	@param	int			$addnowlink		Add a link "Now"
5033
+     * 	@param	int			$nooutput		Do not output html string but return it
5034
+     * 	@param 	int			$disabled		Disable input fields
5035
+     *  @param  int			$fullday        When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
5036
+     *  @param	string		$addplusone		Add a link "+1 hour". Value must be name of another select_date field.
5037
+     *  @param  datetime    $adddateof      Add a link "Date of invoice" using the following date.
5038
+     *  @return	string|void					Nothing or string if nooutput is 1
5039
+     *  @deprecated
5040
+     *  @see    form_date, select_month, select_year, select_dayofweek
5041
+     */
5042
+    function select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')
5043
+    {
5044
+        // phpcs:enable
5045
+        $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
5046
+        if (! empty($nooutput)) {
5047
+            return $retstring;
5048
+        }
5049
+        print $retstring;
5050
+        return;
5051
+    }
5052
+
5053
+    /**
5054
+     *  Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
5055
+     *  Fields are preselected with :
5056
+     *              - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
5057
+     *              - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
5058
+     *              - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
5059
+     *
5060
+     *  @param  timestamp   $set_time       Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
5061
+     *  @param	string		$prefix			Prefix for fields name
5062
+     *  @param	int			$h				1 or 2=Show also hours (2=hours on a new line), -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show hour always empty
5063
+     *	@param	int			$m				1=Show also minutes, -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show minutes always empty
5064
+     *	@param	int			$empty			0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
5065
+     *	@param	string		$form_name 		Not used
5066
+     *	@param	int			$d				1=Show days, month, years
5067
+     * 	@param	int			$addnowlink		Add a link "Now"
5068
+     * 	@param 	int			$disabled		Disable input fields
5069
+     *  @param  int			$fullday        When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
5070
+     *  @param	string		$addplusone		Add a link "+1 hour". Value must be name of another selectDate field.
5071
+     *  @param  datetime    $adddateof      Add a link "Date of invoice" using the following date.
5072
+     * 	@return string                      Html for selectDate
5073
+     *  @see    form_date, select_month, select_year, select_dayofweek
5074
+     */
5075
+    function selectDate($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')
5076
+    {
5077
+        global $conf,$langs;
5078
+
5079
+        $retstring='';
5080
+
5081
+        if ($prefix=='') $prefix='re';
5082
+        if ($h == '') $h=0;
5083
+        if ($m == '') $m=0;
5084
+        $emptydate=0;
5085
+        $emptyhours=0;
5086
+        if ($empty == 1) { $emptydate=1; $emptyhours=1; }
5087
+        if ($empty == 2) { $emptydate=0; $emptyhours=1; }
5088
+        $orig_set_time=$set_time;
5089
+
5090
+        if ($set_time === '' && $emptydate == 0)
5091
+        {
5092
+            include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5093
+            $set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone
5094
+        }
5095
+
5096
+        // Analysis of the pre-selection date
5097
+        if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg))	// deprecated usage
5098
+        {
5099
+            // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
5100
+            $syear	= (! empty($reg[1])?$reg[1]:'');
5101
+            $smonth	= (! empty($reg[2])?$reg[2]:'');
5102
+            $sday	= (! empty($reg[3])?$reg[3]:'');
5103
+            $shour	= (! empty($reg[4])?$reg[4]:'');
5104
+            $smin	= (! empty($reg[5])?$reg[5]:'');
5105
+        }
5106
+        elseif (strval($set_time) != '' && $set_time != -1)
5107
+        {
5108
+            // set_time est un timestamps (0 possible)
5109
+            $syear = dol_print_date($set_time, "%Y");
5110
+            $smonth = dol_print_date($set_time, "%m");
5111
+            $sday = dol_print_date($set_time, "%d");
5112
+            if ($orig_set_time != '')
5113
+            {
5114
+                $shour = dol_print_date($set_time, "%H");
5115
+                $smin = dol_print_date($set_time, "%M");
5116
+                $ssec = dol_print_date($set_time, "%S");
5117
+            }
5118
+            else
5119
+            {
5120
+                $shour = '';
5121
+                $smin = '';
5122
+                $ssec = '';
5123
+            }
5124
+        }
5125
+        else
5126
+        {
5127
+            // Date est '' ou vaut -1
5128
+            $syear = '';
5129
+            $smonth = '';
5130
+            $sday = '';
5131
+            $shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
5132
+            $smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
5133
+            $ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
5134
+        }
5135
+        if ($h == 3) $shour = '';
5136
+        if ($m == 3) $smin = '';
5137
+
5138
+        // You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
5139
+        $usecalendar='combo';
5140
+        if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
5141
+            $usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy')?'jquery':$conf->global->MAIN_POPUP_CALENDAR);
5142
+        }
5143
+
5144
+        if ($d)
5145
+        {
5146
+            // Show date with popup
5147
+            if ($usecalendar != 'combo')
5148
+            {
5149
+                $formated_date='';
5150
+                //print "e".$set_time." t ".$conf->format_date_short;
5151
+                if (strval($set_time) != '' && $set_time != -1)
5152
+                {
5153
+                    //$formated_date=dol_print_date($set_time,$conf->format_date_short);
5154
+                    $formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput"));  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5155
+                }
5156
+
5157
+                // Calendrier popup version eldy
5158
+                if ($usecalendar == "eldy")
5159
+                {
5160
+                    // Zone de saisie manuelle de la date
5161
+                    $retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
5162
+                    $retstring.=($disabled?' disabled':'');
5163
+                    $retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "';  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5164
+                    $retstring.='>';
5165
+
5166
+                    // Icone calendrier
5167
+                    if (! $disabled)
5168
+                    {
5169
+                        $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
5170
+                        $base=DOL_URL_ROOT.'/core/';
5171
+                        $retstring.=' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
5172
+                        $retstring.='>'.img_object($langs->trans("SelectDate"),'calendarday','class="datecallink"').'</button>';
5173
+                    }
5174
+                    else $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5175
+
5176
+                    $retstring.='<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5177
+                    $retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5178
+                    $retstring.='<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5179
+                }
5180
+                elseif ($usecalendar == 'jquery')
5181
+                {
5182
+                    if (! $disabled)
5183
+                    {
5184
+                        // Output javascript for datepicker
5185
+                        $retstring.="<script type='text/javascript'>";
5186
+                        $retstring.="$(function(){ $('#".$prefix."').datepicker({
5187
+							dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
5188
+							autoclose: true,
5189
+							todayHighlight: true,";
5190
+                            if (! empty($conf->dol_use_jmobile))
5191
+                            {
5192
+                                $retstring.="
5193
+								beforeShow: function (input, datePicker) {
5194
+									input.disabled = true;
5195
+								},
5196
+								onClose: function (dateText, datePicker) {
5197
+									this.disabled = false;
5198
+								},
5199
+								";
5200
+                            }
5201
+                            // Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
5202
+                            if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS))
5203
+                            {
5204
+                            $retstring.="
5205
+								showOn: 'button',
5206
+								buttonImage: '".DOL_URL_ROOT."/theme/".$conf->theme."/img/object_calendarday.png',
5207
+								buttonImageOnly: true";
5208
+                            }
5209
+                            $retstring.="
5210
+							}) });";
5211
+                        $retstring.="</script>";
5212
+                    }
5213
+
5214
+                    // Zone de saisie manuelle de la date
5215
+                    $retstring.='<div class="nowrap inline-block">';
5216
+                    $retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
5217
+                    $retstring.=($disabled?' disabled':'');
5218
+                    $retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "';  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5219
+                    $retstring.='>';
5220
+
5221
+                    // Icone calendrier
5222
+                    if (! $disabled)
5223
+                    {
5224
+                        /* Not required. Managed by option buttonImage of jquery
5225
+                		$retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
5226
+                		$retstring.="<script type='text/javascript'>";
5227
+                		$retstring.="jQuery(document).ready(function() {";
5228
+                		$retstring.='	jQuery("#'.$prefix.'id").click(function() {';
5229
+                		$retstring.="    	jQuery('#".$prefix."').focus();";
5230
+                		$retstring.='    });';
5231
+                		$retstring.='});';
5232
+                		$retstring.="</script>";*/
5233
+                    }
5234
+                    else
5235
+                    {
5236
+                        $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5237
+                    }
5238
+
5239
+                    $retstring.='</div>';
5240
+                    $retstring.='<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5241
+                    $retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5242
+                    $retstring.='<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5243
+                }
5244
+                else
5245
+                {
5246
+                    $retstring.="Bad value of MAIN_POPUP_CALENDAR";
5247
+                }
5248
+            }
5249
+            // Show date with combo selects
5250
+            else
5251
+            {
5252
+                //$retstring.='<div class="inline-block">';
5253
+                // Day
5254
+                $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
5255
+
5256
+                if ($emptydate || $set_time == -1)
5257
+                {
5258
+                    $retstring.='<option value="0" selected>&nbsp;</option>';
5259
+                }
5260
+
5261
+                for ($day = 1 ; $day <= 31; $day++)
5262
+                {
5263
+                    $retstring.='<option value="'.$day.'"'.($day == $sday ? ' selected':'').'>'.$day.'</option>';
5264
+                }
5265
+
5266
+                $retstring.="</select>";
5267
+
5268
+                $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
5269
+                if ($emptydate || $set_time == -1)
5270
+                {
5271
+                    $retstring.='<option value="0" selected>&nbsp;</option>';
5272
+                }
5273
+
5274
+                // Month
5275
+                for ($month = 1 ; $month <= 12 ; $month++)
5276
+                {
5277
+                    $retstring.='<option value="'.$month.'"'.($month == $smonth?' selected':'').'>';
5278
+                    $retstring.=dol_print_date(mktime(12,0,0,$month,1,2000),"%b");
5279
+                    $retstring.="</option>";
5280
+                }
5281
+                $retstring.="</select>";
5282
+
5283
+                // Year
5284
+                if ($emptydate || $set_time == -1)
5285
+                {
5286
+                    $retstring.='<input'.($disabled?' disabled':'').' placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" class="flat maxwidth50imp valignmiddle" type="number" min="0" max="3000" maxlength="4" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">';
5287
+                }
5288
+                else
5289
+                {
5290
+                    $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
5291
+
5292
+                    for ($year = $syear - 10; $year < $syear + 10 ; $year++)
5293
+                    {
5294
+                        $retstring.='<option value="'.$year.'"'.($year == $syear ? ' selected':'').'>'.$year.'</option>';
5295
+                    }
5296
+                    $retstring.="</select>\n";
5297
+                }
5298
+                //$retstring.='</div>';
5299
+            }
5300
+        }
5301
+
5302
+        if ($d && $h) $retstring.=($h==2?'<br>':' ');
5303
+
5304
+        if ($h)
5305
+        {
5306
+            // Show hour
5307
+            $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'hour':'').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
5308
+            if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
5309
+            for ($hour = 0; $hour < 24; $hour++)
5310
+            {
5311
+                if (strlen($hour) < 2) $hour = "0" . $hour;
5312
+                $retstring.='<option value="'.$hour.'"'.(($hour == $shour)?' selected':'').'>'.$hour.(empty($conf->dol_optimize_smallscreen)?'':'H').'</option>';
5313
+            }
5314
+            $retstring.='</select>';
5315
+            if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":";
5316
+        }
5317
+
5318
+        if ($m)
5319
+        {
5320
+            // Show minutes
5321
+            $retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'min':'').'" id="'.$prefix.'min" name="'.$prefix.'min">';
5322
+            if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
5323
+            for ($min = 0; $min < 60 ; $min++)
5324
+            {
5325
+                if (strlen($min) < 2) $min = "0" . $min;
5326
+                $retstring.='<option value="'.$min.'"'.(($min == $smin)?' selected':'').'>'.$min.(empty($conf->dol_optimize_smallscreen)?'':'').'</option>';
5327
+            }
5328
+            $retstring.='</select>';
5329
+
5330
+            $retstring.='<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
5331
+        }
5332
+
5333
+        // Add a "Now" link
5334
+        if ($conf->use_javascript_ajax && $addnowlink)
5335
+        {
5336
+            // Script which will be inserted in the onClick of the "Now" link
5337
+            $reset_scripts = "";
5338
+
5339
+            // Generate the date part, depending on the use or not of the javascript calendar
5340
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
5341
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
5342
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
5343
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
5344
+            /*if ($usecalendar == "eldy")
5345
+            {
5346
+                $base=DOL_URL_ROOT.'/core/';
5347
+                $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
5348
+            }
5349
+            else
5350
+            {
5351
+                $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
5352
+                $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
5353
+                $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
5354
+            }*/
5355
+            // Update the hour part
5356
+            if ($h)
5357
+            {
5358
+                if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5359
+                //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
5360
+                $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
5361
+                if ($fullday) $reset_scripts .= ' } ';
5362
+            }
5363
+            // Update the minute part
5364
+            if ($m)
5365
+            {
5366
+                if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5367
+                //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
5368
+                $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
5369
+                if ($fullday) $reset_scripts .= ' } ';
5370
+            }
5371
+            // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
5372
+            if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
5373
+            {
5374
+                $retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
5375
+                $retstring.=$langs->trans("Now");
5376
+                $retstring.='</button> ';
5377
+            }
5378
+        }
5379
+
5380
+        // Add a "Plus one hour" link
5381
+        if ($conf->use_javascript_ajax && $addplusone)
5382
+        {
5383
+            // Script which will be inserted in the onClick of the "Add plusone" link
5384
+            $reset_scripts = "";
5385
+
5386
+            // Generate the date part, depending on the use or not of the javascript calendar
5387
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
5388
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
5389
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
5390
+            $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
5391
+            // Update the hour part
5392
+            if ($h)
5393
+            {
5394
+                if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5395
+                $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
5396
+                if ($fullday) $reset_scripts .= ' } ';
5397
+            }
5398
+            // Update the minute part
5399
+            if ($m)
5400
+            {
5401
+                if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5402
+                $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
5403
+                if ($fullday) $reset_scripts .= ' } ';
5404
+            }
5405
+            // If reset_scripts is not empty, print the link with the reset_scripts in the onClick
5406
+            if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
5407
+            {
5408
+                $retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
5409
+                $retstring.=$langs->trans("DateStartPlusOne");
5410
+                $retstring.='</button> ';
5411
+            }
5412
+        }
5413
+
5414
+        // Add a "Plus one hour" link
5415
+        if ($conf->use_javascript_ajax && $adddateof)
5416
+        {
5417
+            $tmparray=dol_getdate($adddateof);
5418
+            $retstring.=' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="jQuery(\'#re\').val(\''.dol_print_date($adddateof,'day').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$langs->trans("DateInvoice").'</a>';
5419
+        }
5420
+
5421
+        return $retstring;
5422
+    }
5423
+
5424
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
5425
+    /**
5426
+     *	Function to show a form to select a duration on a page
5427
+     *
5428
+     *	@param	string	$prefix   		Prefix for input fields
5429
+     *	@param  int	$iSecond  		    Default preselected duration (number of seconds or '')
5430
+     * 	@param	int	$disabled           Disable the combo box
5431
+     * 	@param	string	$typehour		If 'select' then input hour and input min is a combo,
5432
+     *						            if 'text' input hour is in text and input min is a text,
5433
+     *						            if 'textselect' input hour is in text and input min is a combo
5434
+     *  @param	integer	$minunderhours	If 1, show minutes selection under the hours
5435
+     * 	@param	int	$nooutput		    Do not output html string but return it
5436
+     *  @return	string|void
5437
+     */
5438
+    function select_duration($prefix, $iSecond='', $disabled=0, $typehour='select', $minunderhours=0, $nooutput=0)
5439
+    {
5440
+        // phpcs:enable
5441
+        global $langs;
5442
+
5443
+        $retstring='';
5444
+
5445
+        $hourSelected=0; $minSelected=0;
5446
+
5447
+        // Hours
5448
+        if ($iSecond != '')
5449
+        {
5450
+            require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5451
+
5452
+            $hourSelected = convertSecondToTime($iSecond,'allhour');
5453
+            $minSelected = convertSecondToTime($iSecond,'min');
5454
+        }
5455
+
5456
+        if ($typehour=='select' )
5457
+        {
5458
+            $retstring.='<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled?' disabled':'').'>';
5459
+            for ($hour = 0; $hour < 25; $hour++)	// For a duration, we allow 24 hours
5460
+            {
5461
+                $retstring.='<option value="'.$hour.'"';
5462
+                if ($hourSelected == $hour)
5463
+                {
5464
+                    $retstring.=" selected";
5465
+                }
5466
+                $retstring.=">".$hour."</option>";
5467
+            }
5468
+            $retstring.="</select>";
5469
+        }
5470
+        elseif ($typehour=='text' || $typehour=='textselect')
5471
+        {
5472
+            $retstring.='<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" size="1" name="'.$prefix.'hour"'.($disabled?' disabled':'').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '')?((int) $hourSelected):'').'">';
5473
+        }
5474
+        else return 'BadValueForParameterTypeHour';
5475
+
5476
+        if ($typehour!='text') $retstring.=' '.$langs->trans('HourShort');
5477
+        else $retstring.='<span class="hideonsmartphone">:</span>';
5478
+
5479
+        // Minutes
5480
+        if ($minunderhours) $retstring.='<br>';
5481
+        else $retstring.='<span class="hideonsmartphone">&nbsp;</span>';
5482
+
5483
+        if ($typehour=='select' || $typehour=='textselect')
5484
+        {
5485
+            $retstring.='<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled?' disabled':'').'>';
5486
+            for ($min = 0; $min <= 55; $min=$min+5)
5487
+            {
5488
+                $retstring.='<option value="'.$min.'"';
5489
+                if ($minSelected == $min) $retstring.=' selected';
5490
+                $retstring.='>'.$min.'</option>';
5491
+            }
5492
+            $retstring.="</select>";
5493
+        }
5494
+        elseif ($typehour=='text' )
5495
+        {
5496
+            $retstring.='<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" size="1" name="'.$prefix.'min"'.($disabled?' disabled':'').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '')?((int) $minSelected):'').'">';
5497
+        }
5498
+
5499
+        if ($typehour!='text') $retstring.=' '.$langs->trans('MinuteShort');
5500
+
5501
+        //$retstring.="&nbsp;";
5502
+
5503
+        if (! empty($nooutput)) return $retstring;
5504
+
5505
+        print $retstring;
5506
+        return;
5507
+    }
5508
+
5509
+
5510
+    /**
5511
+     * Generic method to select a component from a combo list.
5512
+     * This is the generic method that will replace all specific existing methods.
5513
+     *
5514
+     * @param 	string			$objectdesc			Objectclassname:Objectclasspath
5515
+     * @param	string			$htmlname			Name of HTML select component
5516
+     * @param	int				$preselectedvalue	Preselected value (ID of element)
5517
+     * @param	string			$showempty			''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
5518
+     * @param	string			$searchkey			Search criteria
5519
+     * @param	string			$placeholder		Place holder
5520
+     * @param	string			$morecss			More CSS
5521
+     * @param	string			$moreparams			More params provided to ajax call
5522
+     * @param	int				$forcecombo			Force to load all values and output a standard combobox (with no beautification)
5523
+     * @return	string								Return HTML string
5524
+     * @see selectForFormsList select_thirdparty
5525
+     */
5526
+    function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0)
5527
+    {
5528
+        global $conf, $user;
5529
+
5530
+        $objecttmp = null;
5531
+
5532
+        $InfoFieldList = explode(":", $objectdesc);
5533
+        $classname=$InfoFieldList[0];
5534
+        $classpath=$InfoFieldList[1];
5535
+        if (! empty($classpath))
5536
+        {
5537
+            dol_include_once($classpath);
5538
+            if ($classname && class_exists($classname))
5539
+            {
5540
+                $objecttmp = new $classname($this->db);
5541
+            }
5542
+        }
5543
+        if (! is_object($objecttmp))
5544
+        {
5545
+            dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
5546
+            return 'Error bad setup of type for field '.join(',', $InfoFieldList);
5547
+        }
5548
+
5549
+        $prefixforautocompletemode=$objecttmp->element;
5550
+        if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
5551
+        $confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';	// For example COMPANY_USE_SEARCH_TO_SELECT
5552
+
5553
+        dol_syslog(get_class($this)."::selectForForms", LOG_DEBUG);
5554
+
5555
+        $out='';
5556
+        if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->$confkeyforautocompletemode) && ! $forcecombo)
5557
+        {
5558
+            $objectdesc=$classname.':'.$classpath;
5559
+            $urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
5560
+            //if ($objecttmp->element == 'societe') $urlforajaxcall = DOL_URL_ROOT.'/societe/ajax/company.php';
5561
+
5562
+            // No immediate load of all database
5563
+            $urloption='htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.($moreparams?$moreparams:'');
5564
+            // Activate the auto complete using ajax call.
5565
+            $out.=  ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
5566
+            $out.= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
5567
+            if ($placeholder) $placeholder=' placeholder="'.$placeholder.'"';
5568
+            $out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$preselectedvalue.'"'.$placeholder.' />';
5569
+        }
5570
+        else
5571
+        {
5572
+            // Immediate load of all database
5573
+            $out.=$this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo);
5574
+        }
5575
+
5576
+        return $out;
5577
+    }
5578
+
5579
+    /**
5580
+     * Output html form to select an object.
5581
+     * Note, this function is called by selectForForms or by ajax selectobject.php
5582
+     *
5583
+     * @param 	Object			$objecttmp			Object
5584
+     * @param	string			$htmlname			Name of HTML select component
5585
+     * @param	int				$preselectedvalue	Preselected value (ID of element)
5586
+     * @param	string			$showempty			''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
5587
+     * @param	string			$searchkey			Search value
5588
+     * @param	string			$placeholder		Place holder
5589
+     * @param	string			$morecss			More CSS
5590
+     * @param	string			$moreparams			More params provided to ajax call
5591
+     * @param	int				$forcecombo			Force to load all values and output a standard combobox (with no beautification)
5592
+     * @param	int				$outputmode			0=HTML select string, 1=Array
5593
+     * @return	string								Return HTML string
5594
+     * @see selectForForms
5595
+     */
5596
+    function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0, $outputmode=0)
5597
+    {
5598
+        global $conf, $langs, $user;
5599
+
5600
+        $prefixforautocompletemode=$objecttmp->element;
5601
+        if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
5602
+        $confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';	// For example COMPANY_USE_SEARCH_TO_SELECT
5603
+
5604
+        $fieldstoshow='t.ref';
5605
+        if (! empty($objecttmp->fields))	// For object that declare it, it is better to use declared fields ( like societe, contact, ...)
5606
+        {
5607
+            $tmpfieldstoshow='';
5608
+            foreach($objecttmp->fields as $key => $val)
5609
+            {
5610
+                if ($val['showoncombobox']) $tmpfieldstoshow.=($tmpfieldstoshow?',':'').'t.'.$key;
5611
+            }
5612
+            if ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow;
5613
+        }
5614
+
5615
+        $out='';
5616
+        $outarray=array();
5617
+
5618
+        $num=0;
5619
+
5620
+        // Search data
5621
+        $sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX .$objecttmp->table_element." as t";
5622
+        if ($objecttmp->ismultientitymanaged == 2)
5623
+            if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
5624
+        $sql.= " WHERE 1=1";
5625
+        if(! empty($objecttmp->ismultientitymanaged)) $sql.= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
5626
+        if ($objecttmp->ismultientitymanaged == 1 && ! empty($user->societe_id))
5627
+        {
5628
+            if ($objecttmp->element == 'societe') $sql.= " AND t.rowid = ".$user->societe_id;
5629
+                else $sql.= " AND t.fk_soc = ".$user->societe_id;
5630
+        }
5631
+        if ($searchkey != '') $sql.=natural_search(explode(',',$fieldstoshow), $searchkey);
5632
+        if ($objecttmp->ismultientitymanaged == 2)
5633
+            if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND t.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
5634
+        $sql.=$this->db->order($fieldstoshow,"ASC");
5635
+        //$sql.=$this->db->plimit($limit, 0);
5636
+
5637
+        // Build output string
5638
+        $resql=$this->db->query($sql);
5639
+        if ($resql)
5640
+        {
5641
+            if (! $forcecombo)
5642
+            {
5643
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5644
+                $out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode);
5645
+            }
5646
+
5647
+            // Construct $out and $outarray
5648
+            $out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparams?' '.$moreparams:'').' name="'.$htmlname.'">'."\n";
5649
+
5650
+            // Warning: Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'. Seems it is no more true with selec2 v4
5651
+            $textifempty='&nbsp;';
5652
+
5653
+            //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
5654
+            if (! empty($conf->global->$confkeyforautocompletemode))
5655
+            {
5656
+                if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
5657
+                else $textifempty.=$langs->trans("All");
5658
+            }
5659
+            if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
5660
+
5661
+            $num = $this->db->num_rows($resql);
5662
+            $i = 0;
5663
+            if ($num)
5664
+            {
5665
+                while ($i < $num)
5666
+                {
5667
+                    $obj = $this->db->fetch_object($resql);
5668
+                    $label='';
5669
+                    $tmparray=explode(',', $fieldstoshow);
5670
+                    foreach($tmparray as $key => $val)
5671
+                    {
5672
+                        $val = preg_replace('/t\./','',$val);
5673
+                        $label .= (($label && $obj->$val)?' - ':'').$obj->$val;
5674
+                    }
5675
+                    if (empty($outputmode))
5676
+                    {
5677
+                        if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid)
5678
+                        {
5679
+                            $out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
5680
+                        }
5681
+                        else
5682
+                        {
5683
+                            $out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
5684
+                        }
5685
+                    }
5686
+                    else
5687
+                    {
5688
+                        array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
5689
+                    }
5690
+
5691
+                    $i++;
5692
+                    if (($i % 10) == 0) $out.="\n";
5693
+                }
5694
+            }
5695
+
5696
+            $out.= '</select>'."\n";
5697
+        }
5698
+        else
5699
+        {
5700
+            dol_print_error($this->db);
5701
+        }
5702
+
5703
+        $this->result=array('nbofelement'=>$num);
5704
+
5705
+        if ($outputmode) return $outarray;
5706
+        return $out;
5707
+    }
5015 5708
 
5016 5709
 
5017
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
5018 5710
     /**
5019
-     *  Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
5020
-	 *  Fields are preselected with :
5021
-	 *            	- set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
5022
-	 *            	- local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
5023
-	 *            	- Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
5024
-	 *
5025
-	 *	@param	timestamp	$set_time 		Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
5026
-	 *	@param	string		$prefix			Prefix for fields name
5027
-	 *	@param	int			$h				1 or 2=Show also hours (2=hours on a new line), -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show hour always empty
5028
-	 *	@param	int			$m				1=Show also minutes, -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show minutes always empty
5029
-	 *	@param	int			$empty			0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
5030
-	 *	@param	string		$form_name 		Not used
5031
-	 *	@param	int			$d				1=Show days, month, years
5032
-	 * 	@param	int			$addnowlink		Add a link "Now"
5033
-	 * 	@param	int			$nooutput		Do not output html string but return it
5034
-	 * 	@param 	int			$disabled		Disable input fields
5035
-	 *  @param  int			$fullday        When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
5036
-	 *  @param	string		$addplusone		Add a link "+1 hour". Value must be name of another select_date field.
5037
-	 *  @param  datetime    $adddateof      Add a link "Date of invoice" using the following date.
5038
-	 *  @return	string|void					Nothing or string if nooutput is 1
5039
-     *  @deprecated
5040
-	 *  @see    form_date, select_month, select_year, select_dayofweek
5041
-	 */
5042
-    function select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')
5711
+     *	Return a HTML select string, built from an array of key+value.
5712
+     *  Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
5713
+     *
5714
+     *	@param	string			$htmlname			Name of html select area. Must start with "multi" if this is a multiselect
5715
+     *	@param	array			$array				Array (key => value)
5716
+     *	@param	string|string[]	$id					Preselected key or preselected keys for multiselect
5717
+     *	@param	int|string		$show_empty			0 no empty value allowed, 1 or string to add an empty value into list (key is -1 and value is '' or '&nbsp;' if 1, key is -1 and value is text if string), <0 to add an empty value with key that is this value.
5718
+     *	@param	int				$key_in_label		1 to show key into label with format "[key] value"
5719
+     *	@param	int				$value_as_key		1 to use value as key
5720
+     *	@param  string			$moreparam			Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
5721
+     *	@param  int				$translate			1=Translate and encode value
5722
+     * 	@param	int				$maxlen				Length maximum for labels
5723
+     * 	@param	int				$disabled			Html select box is disabled
5724
+     *  @param	string			$sort				'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
5725
+     *  @param	string			$morecss			Add more class to css styles
5726
+     *  @param	int				$addjscombo			Add js combo
5727
+     *  @param  string          $moreparamonempty	Add more param on the empty option line. Not used if show_empty not set
5728
+     *  @param  int             $disablebademail	Check if an email is found into value and if not disable and colorize entry
5729
+     *  @param  int             $nohtmlescape		No html escaping.
5730
+     * 	@return	string								HTML select string.
5731
+     *  @see multiselectarray
5732
+     */
5733
+    static function selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='', $addjscombo=0, $moreparamonempty='',$disablebademail=0, $nohtmlescape=0)
5043 5734
     {
5044
-        // phpcs:enable
5045
-        $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
5046
-        if (! empty($nooutput)) {
5047
-            return $retstring;
5735
+        global $conf, $langs;
5736
+
5737
+        // Do we want a multiselect ?
5738
+        //$jsbeautify = 0;
5739
+        //if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
5740
+        $jsbeautify = 1;
5741
+
5742
+        if ($value_as_key) $array=array_combine($array, $array);
5743
+
5744
+        $out='';
5745
+
5746
+        // Add code for jquery to use multiselect
5747
+        if ($addjscombo && $jsbeautify)
5748
+        {
5749
+            $minLengthToAutocomplete=0;
5750
+            $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?(constant('REQUIRE_JQUERY_MULTISELECT')?constant('REQUIRE_JQUERY_MULTISELECT'):'select2'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
5751
+
5752
+            // Enhance with select2
5753
+            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5754
+            $out .= ajax_combobox($htmlname);
5048 5755
         }
5049
-        print $retstring;
5050
-        return;
5051
-    }
5052 5756
 
5053
-    /**
5054
-     *  Show a HTML widget to input a date or combo list for day, month, years and optionaly hours and minutes.
5055
-	 *  Fields are preselected with :
5056
-	 *              - set_time date (must be a local PHP server timestamp or string date with format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM')
5057
-	 *              - local date in user area, if set_time is '' (so if set_time is '', output may differs when done from two different location)
5058
-	 *              - Empty (fields empty), if set_time is -1 (in this case, parameter empty must also have value 1)
5059
-	 *
5060
-	 *  @param  timestamp   $set_time       Pre-selected date (must be a local PHP server timestamp), -1 to keep date not preselected, '' to use current date with 00:00 hour (Parameter 'empty' must be 0 or 2).
5061
-	 *  @param	string		$prefix			Prefix for fields name
5062
-	 *  @param	int			$h				1 or 2=Show also hours (2=hours on a new line), -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show hour always empty
5063
-	 *	@param	int			$m				1=Show also minutes, -1 has same effect but hour and minutes are prefilled with 23:59 if date is empty, 3 show minutes always empty
5064
-	 *	@param	int			$empty			0=Fields required, 1=Empty inputs are allowed, 2=Empty inputs are allowed for hours only
5065
-	 *	@param	string		$form_name 		Not used
5066
-	 *	@param	int			$d				1=Show days, month, years
5067
-	 * 	@param	int			$addnowlink		Add a link "Now"
5068
-	 * 	@param 	int			$disabled		Disable input fields
5069
-	 *  @param  int			$fullday        When a checkbox with this html name is on, hour and day are set with 00:00 or 23:59
5070
-	 *  @param	string		$addplusone		Add a link "+1 hour". Value must be name of another selectDate field.
5071
-	 *  @param  datetime    $adddateof      Add a link "Date of invoice" using the following date.
5072
-	 * 	@return string                      Html for selectDate
5073
-	 *  @see    form_date, select_month, select_year, select_dayofweek
5074
-	 */
5075
-	function selectDate($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')
5076
-	{
5077
-		global $conf,$langs;
5078
-
5079
-		$retstring='';
5080
-
5081
-		if ($prefix=='') $prefix='re';
5082
-		if ($h == '') $h=0;
5083
-		if ($m == '') $m=0;
5084
-		$emptydate=0;
5085
-		$emptyhours=0;
5086
-		if ($empty == 1) { $emptydate=1; $emptyhours=1; }
5087
-		if ($empty == 2) { $emptydate=0; $emptyhours=1; }
5088
-		$orig_set_time=$set_time;
5089
-
5090
-		if ($set_time === '' && $emptydate == 0)
5091
-		{
5092
-			include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5093
-			$set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone
5094
-		}
5095
-
5096
-		// Analysis of the pre-selection date
5097
-		if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg))	// deprecated usage
5098
-		{
5099
-			// Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
5100
-			$syear	= (! empty($reg[1])?$reg[1]:'');
5101
-			$smonth	= (! empty($reg[2])?$reg[2]:'');
5102
-			$sday	= (! empty($reg[3])?$reg[3]:'');
5103
-			$shour	= (! empty($reg[4])?$reg[4]:'');
5104
-			$smin	= (! empty($reg[5])?$reg[5]:'');
5105
-		}
5106
-		elseif (strval($set_time) != '' && $set_time != -1)
5107
-		{
5108
-			// set_time est un timestamps (0 possible)
5109
-			$syear = dol_print_date($set_time, "%Y");
5110
-			$smonth = dol_print_date($set_time, "%m");
5111
-			$sday = dol_print_date($set_time, "%d");
5112
-			if ($orig_set_time != '')
5113
-			{
5114
-				$shour = dol_print_date($set_time, "%H");
5115
-				$smin = dol_print_date($set_time, "%M");
5116
-				$ssec = dol_print_date($set_time, "%S");
5117
-			}
5118
-			else
5119
-			{
5120
-				$shour = '';
5121
-				$smin = '';
5122
-				$ssec = '';
5123
-			}
5124
-		}
5125
-		else
5126
-		{
5127
-			// Date est '' ou vaut -1
5128
-			$syear = '';
5129
-			$smonth = '';
5130
-			$sday = '';
5131
-			$shour = !isset($conf->global->MAIN_DEFAULT_DATE_HOUR) ? ($h == -1 ? '23' : '') : $conf->global->MAIN_DEFAULT_DATE_HOUR;
5132
-			$smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
5133
-			$ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
5134
-		}
5135
-		if ($h == 3) $shour = '';
5136
-		if ($m == 3) $smin = '';
5137
-
5138
-		// You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
5139
-		$usecalendar='combo';
5140
-		if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
5141
-			$usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy')?'jquery':$conf->global->MAIN_POPUP_CALENDAR);
5142
-		}
5143
-
5144
-		if ($d)
5145
-		{
5146
-			// Show date with popup
5147
-			if ($usecalendar != 'combo')
5148
-			{
5149
-				$formated_date='';
5150
-				//print "e".$set_time." t ".$conf->format_date_short;
5151
-				if (strval($set_time) != '' && $set_time != -1)
5152
-				{
5153
-					//$formated_date=dol_print_date($set_time,$conf->format_date_short);
5154
-					$formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput"));  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5155
-				}
5156
-
5157
-				// Calendrier popup version eldy
5158
-				if ($usecalendar == "eldy")
5159
-				{
5160
-					// Zone de saisie manuelle de la date
5161
-					$retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
5162
-					$retstring.=($disabled?' disabled':'');
5163
-					$retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "';  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5164
-					$retstring.='>';
5165
-
5166
-					// Icone calendrier
5167
-					if (! $disabled)
5168
-					{
5169
-						$retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
5170
-						$base=DOL_URL_ROOT.'/core/';
5171
-						$retstring.=' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
5172
-						$retstring.='>'.img_object($langs->trans("SelectDate"),'calendarday','class="datecallink"').'</button>';
5173
-					}
5174
-					else $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5175
-
5176
-					$retstring.='<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5177
-					$retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5178
-					$retstring.='<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5179
-				}
5180
-				elseif ($usecalendar == 'jquery')
5181
-				{
5182
-					if (! $disabled)
5183
-					{
5184
-						// Output javascript for datepicker
5185
-						$retstring.="<script type='text/javascript'>";
5186
-						$retstring.="$(function(){ $('#".$prefix."').datepicker({
5187
-							dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
5188
-							autoclose: true,
5189
-							todayHighlight: true,";
5190
-							if (! empty($conf->dol_use_jmobile))
5191
-							{
5192
-								$retstring.="
5193
-								beforeShow: function (input, datePicker) {
5194
-									input.disabled = true;
5195
-								},
5196
-								onClose: function (dateText, datePicker) {
5197
-									this.disabled = false;
5198
-								},
5199
-								";
5200
-							}
5201
-							// Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
5202
-							if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS))
5203
-							{
5204
-							$retstring.="
5205
-								showOn: 'button',
5206
-								buttonImage: '".DOL_URL_ROOT."/theme/".$conf->theme."/img/object_calendarday.png',
5207
-								buttonImageOnly: true";
5208
-							}
5209
-							$retstring.="
5210
-							}) });";
5211
-						$retstring.="</script>";
5212
-					}
5757
+        $out.='<select id="'.preg_replace('/^\./','',$htmlname).'" '.($disabled?'disabled ':'').'class="flat '.(preg_replace('/^\./','',$htmlname)).($morecss?' '.$morecss:'').'"';
5758
+        $out.=' name="'.preg_replace('/^\./','',$htmlname).'" '.($moreparam?$moreparam:'');
5759
+        $out.='>';
5213 5760
 
5214
-					// Zone de saisie manuelle de la date
5215
-					$retstring.='<div class="nowrap inline-block">';
5216
-					$retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
5217
-					$retstring.=($disabled?' disabled':'');
5218
-					$retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "';  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5219
-					$retstring.='>';
5220
-
5221
-					// Icone calendrier
5222
-					if (! $disabled)
5223
-					{
5224
-						/* Not required. Managed by option buttonImage of jquery
5225
-                		$retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
5226
-                		$retstring.="<script type='text/javascript'>";
5227
-                		$retstring.="jQuery(document).ready(function() {";
5228
-                		$retstring.='	jQuery("#'.$prefix.'id").click(function() {';
5229
-                		$retstring.="    	jQuery('#".$prefix."').focus();";
5230
-                		$retstring.='    });';
5231
-                		$retstring.='});';
5232
-                		$retstring.="</script>";*/
5233
-					}
5234
-					else
5235
-					{
5236
-						$retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5237
-					}
5761
+        if ($show_empty)
5762
+        {
5763
+            $textforempty=' ';
5764
+            if (! empty($conf->use_javascript_ajax)) $textforempty='&nbsp;';	// If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
5765
+            if (! is_numeric($show_empty)) $textforempty=$show_empty;
5766
+            $out.='<option class="optiongrey" '.($moreparamonempty?$moreparamonempty.' ':'').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ?' selected':'').'>'.$textforempty.'</option>'."\n";
5767
+        }
5238 5768
 
5239
-					$retstring.='</div>';
5240
-					$retstring.='<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5241
-					$retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5242
-					$retstring.='<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5243
-				}
5244
-				else
5245
-				{
5246
-					$retstring.="Bad value of MAIN_POPUP_CALENDAR";
5247
-				}
5248
-			}
5249
-			// Show date with combo selects
5250
-			else
5251
-			{
5252
-				//$retstring.='<div class="inline-block">';
5253
-				// Day
5254
-				$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
5255
-
5256
-				if ($emptydate || $set_time == -1)
5257
-				{
5258
-					$retstring.='<option value="0" selected>&nbsp;</option>';
5259
-				}
5260
-
5261
-				for ($day = 1 ; $day <= 31; $day++)
5262
-				{
5263
-					$retstring.='<option value="'.$day.'"'.($day == $sday ? ' selected':'').'>'.$day.'</option>';
5264
-				}
5265
-
5266
-				$retstring.="</select>";
5267
-
5268
-				$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
5269
-				if ($emptydate || $set_time == -1)
5270
-				{
5271
-					$retstring.='<option value="0" selected>&nbsp;</option>';
5272
-				}
5273
-
5274
-				// Month
5275
-				for ($month = 1 ; $month <= 12 ; $month++)
5276
-				{
5277
-					$retstring.='<option value="'.$month.'"'.($month == $smonth?' selected':'').'>';
5278
-					$retstring.=dol_print_date(mktime(12,0,0,$month,1,2000),"%b");
5279
-					$retstring.="</option>";
5280
-				}
5281
-				$retstring.="</select>";
5282
-
5283
-				// Year
5284
-				if ($emptydate || $set_time == -1)
5285
-				{
5286
-					$retstring.='<input'.($disabled?' disabled':'').' placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" class="flat maxwidth50imp valignmiddle" type="number" min="0" max="3000" maxlength="4" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">';
5287
-				}
5288
-				else
5289
-				{
5290
-					$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
5291
-
5292
-					for ($year = $syear - 10; $year < $syear + 10 ; $year++)
5293
-					{
5294
-						$retstring.='<option value="'.$year.'"'.($year == $syear ? ' selected':'').'>'.$year.'</option>';
5295
-					}
5296
-					$retstring.="</select>\n";
5297
-				}
5298
-				//$retstring.='</div>';
5299
-			}
5300
-		}
5301
-
5302
-		if ($d && $h) $retstring.=($h==2?'<br>':' ');
5303
-
5304
-		if ($h)
5305
-		{
5306
-			// Show hour
5307
-			$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'hour':'').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
5308
-			if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
5309
-			for ($hour = 0; $hour < 24; $hour++)
5310
-			{
5311
-				if (strlen($hour) < 2) $hour = "0" . $hour;
5312
-				$retstring.='<option value="'.$hour.'"'.(($hour == $shour)?' selected':'').'>'.$hour.(empty($conf->dol_optimize_smallscreen)?'':'H').'</option>';
5313
-			}
5314
-			$retstring.='</select>';
5315
-			if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":";
5316
-		}
5317
-
5318
-		if ($m)
5319
-		{
5320
-			// Show minutes
5321
-			$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'min':'').'" id="'.$prefix.'min" name="'.$prefix.'min">';
5322
-			if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
5323
-			for ($min = 0; $min < 60 ; $min++)
5324
-			{
5325
-				if (strlen($min) < 2) $min = "0" . $min;
5326
-				$retstring.='<option value="'.$min.'"'.(($min == $smin)?' selected':'').'>'.$min.(empty($conf->dol_optimize_smallscreen)?'':'').'</option>';
5327
-			}
5328
-			$retstring.='</select>';
5329
-
5330
-			$retstring.='<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
5331
-		}
5332
-
5333
-		// Add a "Now" link
5334
-		if ($conf->use_javascript_ajax && $addnowlink)
5335
-		{
5336
-			// Script which will be inserted in the onClick of the "Now" link
5337
-			$reset_scripts = "";
5338
-
5339
-			// Generate the date part, depending on the use or not of the javascript calendar
5340
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
5341
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
5342
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
5343
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
5344
-			/*if ($usecalendar == "eldy")
5769
+        if (is_array($array))
5770
+        {
5771
+            // Translate
5772
+            if ($translate)
5345 5773
             {
5346
-                $base=DOL_URL_ROOT.'/core/';
5347
-                $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');';
5774
+                foreach($array as $key => $value)
5775
+                {
5776
+                    $array[$key]=$langs->trans($value);
5777
+                }
5348 5778
             }
5349
-            else
5779
+
5780
+            // Sort
5781
+            if ($sort == 'ASC') asort($array);
5782
+            elseif ($sort == 'DESC') arsort($array);
5783
+
5784
+            foreach($array as $key => $value)
5350 5785
             {
5351
-                $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); ';
5352
-                $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); ';
5353
-                $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); ';
5354
-            }*/
5355
-			// Update the hour part
5356
-			if ($h)
5357
-			{
5358
-				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5359
-				//$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
5360
-				$reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
5361
-				if ($fullday) $reset_scripts .= ' } ';
5362
-			}
5363
-			// Update the minute part
5364
-			if ($m)
5365
-			{
5366
-				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5367
-				//$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
5368
-				$reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
5369
-				if ($fullday) $reset_scripts .= ' } ';
5370
-			}
5371
-			// If reset_scripts is not empty, print the link with the reset_scripts in the onClick
5372
-			if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
5373
-			{
5374
-				$retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
5375
-				$retstring.=$langs->trans("Now");
5376
-				$retstring.='</button> ';
5377
-			}
5378
-		}
5379
-
5380
-		// Add a "Plus one hour" link
5381
-		if ($conf->use_javascript_ajax && $addplusone)
5382
-		{
5383
-			// Script which will be inserted in the onClick of the "Add plusone" link
5384
-			$reset_scripts = "";
5385
-
5386
-			// Generate the date part, depending on the use or not of the javascript calendar
5387
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
5388
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
5389
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
5390
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
5391
-			// Update the hour part
5392
-			if ($h)
5393
-			{
5394
-				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5395
-				$reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
5396
-				if ($fullday) $reset_scripts .= ' } ';
5397
-			}
5398
-			// Update the minute part
5399
-			if ($m)
5400
-			{
5401
-				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5402
-				$reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
5403
-				if ($fullday) $reset_scripts .= ' } ';
5404
-			}
5405
-			// If reset_scripts is not empty, print the link with the reset_scripts in the onClick
5406
-			if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
5407
-			{
5408
-				$retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
5409
-				$retstring.=$langs->trans("DateStartPlusOne");
5410
-				$retstring.='</button> ';
5411
-			}
5412
-		}
5413
-
5414
-		// Add a "Plus one hour" link
5415
-		if ($conf->use_javascript_ajax && $adddateof)
5416
-		{
5417
-			$tmparray=dol_getdate($adddateof);
5418
-			$retstring.=' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="jQuery(\'#re\').val(\''.dol_print_date($adddateof,'day').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$langs->trans("DateInvoice").'</a>';
5419
-		}
5420
-
5421
-		return $retstring;
5422
-	}
5786
+                $disabled=''; $style='';
5787
+                if (! empty($disablebademail))
5788
+                {
5789
+                    if (! preg_match('/&lt;.+@.+&gt;/', $value))
5790
+                    {
5791
+                        //$value=preg_replace('/'.preg_quote($a,'/').'/', $b, $value);
5792
+                        $disabled=' disabled';
5793
+                        $style=' class="warning"';
5794
+                    }
5795
+                }
5423 5796
 
5424
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
5425
-	/**
5426
-	 *	Function to show a form to select a duration on a page
5427
-	 *
5428
-	 *	@param	string	$prefix   		Prefix for input fields
5429
-	 *	@param  int	$iSecond  		    Default preselected duration (number of seconds or '')
5430
-	 * 	@param	int	$disabled           Disable the combo box
5431
-	 * 	@param	string	$typehour		If 'select' then input hour and input min is a combo,
5432
-	 *						            if 'text' input hour is in text and input min is a text,
5433
-	 *						            if 'textselect' input hour is in text and input min is a combo
5434
-	 *  @param	integer	$minunderhours	If 1, show minutes selection under the hours
5435
-	 * 	@param	int	$nooutput		    Do not output html string but return it
5436
-	 *  @return	string|void
5437
-	 */
5438
-	function select_duration($prefix, $iSecond='', $disabled=0, $typehour='select', $minunderhours=0, $nooutput=0)
5439
-	{
5440
-        // phpcs:enable
5441
-		global $langs;
5442
-
5443
-		$retstring='';
5444
-
5445
-		$hourSelected=0; $minSelected=0;
5446
-
5447
-		// Hours
5448
-		if ($iSecond != '')
5449
-		{
5450
-			require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5451
-
5452
-			$hourSelected = convertSecondToTime($iSecond,'allhour');
5453
-			$minSelected = convertSecondToTime($iSecond,'min');
5454
-		}
5455
-
5456
-		if ($typehour=='select' )
5457
-		{
5458
-			$retstring.='<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled?' disabled':'').'>';
5459
-			for ($hour = 0; $hour < 25; $hour++)	// For a duration, we allow 24 hours
5460
-			{
5461
-				$retstring.='<option value="'.$hour.'"';
5462
-				if ($hourSelected == $hour)
5463
-				{
5464
-					$retstring.=" selected";
5465
-				}
5466
-				$retstring.=">".$hour."</option>";
5467
-			}
5468
-			$retstring.="</select>";
5469
-		}
5470
-		elseif ($typehour=='text' || $typehour=='textselect')
5471
-		{
5472
-			$retstring.='<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" size="1" name="'.$prefix.'hour"'.($disabled?' disabled':'').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '')?((int) $hourSelected):'').'">';
5473
-		}
5474
-		else return 'BadValueForParameterTypeHour';
5475
-
5476
-		if ($typehour!='text') $retstring.=' '.$langs->trans('HourShort');
5477
-		else $retstring.='<span class="hideonsmartphone">:</span>';
5478
-
5479
-		// Minutes
5480
-		if ($minunderhours) $retstring.='<br>';
5481
-		else $retstring.='<span class="hideonsmartphone">&nbsp;</span>';
5482
-
5483
-		if ($typehour=='select' || $typehour=='textselect')
5484
-		{
5485
-			$retstring.='<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled?' disabled':'').'>';
5486
-			for ($min = 0; $min <= 55; $min=$min+5)
5487
-			{
5488
-				$retstring.='<option value="'.$min.'"';
5489
-				if ($minSelected == $min) $retstring.=' selected';
5490
-				$retstring.='>'.$min.'</option>';
5491
-			}
5492
-			$retstring.="</select>";
5493
-		}
5494
-		elseif ($typehour=='text' )
5495
-		{
5496
-			$retstring.='<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" size="1" name="'.$prefix.'min"'.($disabled?' disabled':'').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '')?((int) $minSelected):'').'">';
5497
-		}
5498
-
5499
-		if ($typehour!='text') $retstring.=' '.$langs->trans('MinuteShort');
5500
-
5501
-		//$retstring.="&nbsp;";
5502
-
5503
-		if (! empty($nooutput)) return $retstring;
5504
-
5505
-		print $retstring;
5506
-		return;
5507
-	}
5508
-
5509
-
5510
-	/**
5511
-	 * Generic method to select a component from a combo list.
5512
-	 * This is the generic method that will replace all specific existing methods.
5513
-	 *
5514
-	 * @param 	string			$objectdesc			Objectclassname:Objectclasspath
5515
-	 * @param	string			$htmlname			Name of HTML select component
5516
-	 * @param	int				$preselectedvalue	Preselected value (ID of element)
5517
-	 * @param	string			$showempty			''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
5518
-	 * @param	string			$searchkey			Search criteria
5519
-	 * @param	string			$placeholder		Place holder
5520
-	 * @param	string			$morecss			More CSS
5521
-	 * @param	string			$moreparams			More params provided to ajax call
5522
-	 * @param	int				$forcecombo			Force to load all values and output a standard combobox (with no beautification)
5523
-	 * @return	string								Return HTML string
5524
-	 * @see selectForFormsList select_thirdparty
5525
-	 */
5526
-	function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0)
5527
-	{
5528
-		global $conf, $user;
5529
-
5530
-		$objecttmp = null;
5531
-
5532
-		$InfoFieldList = explode(":", $objectdesc);
5533
-		$classname=$InfoFieldList[0];
5534
-		$classpath=$InfoFieldList[1];
5535
-		if (! empty($classpath))
5536
-		{
5537
-			dol_include_once($classpath);
5538
-			if ($classname && class_exists($classname))
5539
-			{
5540
-				$objecttmp = new $classname($this->db);
5541
-			}
5542
-		}
5543
-		if (! is_object($objecttmp))
5544
-		{
5545
-			dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
5546
-			return 'Error bad setup of type for field '.join(',', $InfoFieldList);
5547
-		}
5548
-
5549
-		$prefixforautocompletemode=$objecttmp->element;
5550
-		if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
5551
-		$confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';	// For example COMPANY_USE_SEARCH_TO_SELECT
5552
-
5553
-		dol_syslog(get_class($this)."::selectForForms", LOG_DEBUG);
5554
-
5555
-		$out='';
5556
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->$confkeyforautocompletemode) && ! $forcecombo)
5557
-		{
5558
-			$objectdesc=$classname.':'.$classpath;
5559
-			$urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
5560
-			//if ($objecttmp->element == 'societe') $urlforajaxcall = DOL_URL_ROOT.'/societe/ajax/company.php';
5561
-
5562
-			// No immediate load of all database
5563
-			$urloption='htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.($moreparams?$moreparams:'');
5564
-			// Activate the auto complete using ajax call.
5565
-			$out.=  ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
5566
-			$out.= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
5567
-			if ($placeholder) $placeholder=' placeholder="'.$placeholder.'"';
5568
-			$out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$preselectedvalue.'"'.$placeholder.' />';
5569
-		}
5570
-		else
5571
-		{
5572
-			// Immediate load of all database
5573
-			$out.=$this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo);
5574
-		}
5575
-
5576
-		return $out;
5577
-	}
5578
-
5579
-	/**
5580
-	 * Output html form to select an object.
5581
-	 * Note, this function is called by selectForForms or by ajax selectobject.php
5582
-	 *
5583
-	 * @param 	Object			$objecttmp			Object
5584
-	 * @param	string			$htmlname			Name of HTML select component
5585
-	 * @param	int				$preselectedvalue	Preselected value (ID of element)
5586
-	 * @param	string			$showempty			''=empty values not allowed, 'string'=value show if we allow empty values (for example 'All', ...)
5587
-	 * @param	string			$searchkey			Search value
5588
-	 * @param	string			$placeholder		Place holder
5589
-	 * @param	string			$morecss			More CSS
5590
-	 * @param	string			$moreparams			More params provided to ajax call
5591
-	 * @param	int				$forcecombo			Force to load all values and output a standard combobox (with no beautification)
5592
-	 * @param	int				$outputmode			0=HTML select string, 1=Array
5593
-	 * @return	string								Return HTML string
5594
-	 * @see selectForForms
5595
-	 */
5596
-	function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0, $outputmode=0)
5597
-	{
5598
-		global $conf, $langs, $user;
5599
-
5600
-		$prefixforautocompletemode=$objecttmp->element;
5601
-		if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
5602
-		$confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';	// For example COMPANY_USE_SEARCH_TO_SELECT
5603
-
5604
-		$fieldstoshow='t.ref';
5605
-		if (! empty($objecttmp->fields))	// For object that declare it, it is better to use declared fields ( like societe, contact, ...)
5606
-		{
5607
-			$tmpfieldstoshow='';
5608
-			foreach($objecttmp->fields as $key => $val)
5609
-			{
5610
-				if ($val['showoncombobox']) $tmpfieldstoshow.=($tmpfieldstoshow?',':'').'t.'.$key;
5611
-			}
5612
-			if ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow;
5613
-		}
5614
-
5615
-		$out='';
5616
-		$outarray=array();
5617
-
5618
-		$num=0;
5619
-
5620
-		// Search data
5621
-		$sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX .$objecttmp->table_element." as t";
5622
-		if ($objecttmp->ismultientitymanaged == 2)
5623
-			if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
5624
-		$sql.= " WHERE 1=1";
5625
-		if(! empty($objecttmp->ismultientitymanaged)) $sql.= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
5626
-		if ($objecttmp->ismultientitymanaged == 1 && ! empty($user->societe_id))
5627
-		{
5628
-			if ($objecttmp->element == 'societe') $sql.= " AND t.rowid = ".$user->societe_id;
5629
-				else $sql.= " AND t.fk_soc = ".$user->societe_id;
5630
-		}
5631
-		if ($searchkey != '') $sql.=natural_search(explode(',',$fieldstoshow), $searchkey);
5632
-		if ($objecttmp->ismultientitymanaged == 2)
5633
-			if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND t.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
5634
-		$sql.=$this->db->order($fieldstoshow,"ASC");
5635
-		//$sql.=$this->db->plimit($limit, 0);
5636
-
5637
-		// Build output string
5638
-		$resql=$this->db->query($sql);
5639
-		if ($resql)
5640
-		{
5641
-			if (! $forcecombo)
5642
-			{
5643
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5644
-				$out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode);
5645
-			}
5646
-
5647
-			// Construct $out and $outarray
5648
-			$out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparams?' '.$moreparams:'').' name="'.$htmlname.'">'."\n";
5649
-
5650
-			// Warning: Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'. Seems it is no more true with selec2 v4
5651
-			$textifempty='&nbsp;';
5652
-
5653
-			//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
5654
-			if (! empty($conf->global->$confkeyforautocompletemode))
5655
-			{
5656
-				if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
5657
-				else $textifempty.=$langs->trans("All");
5658
-			}
5659
-			if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
5660
-
5661
-			$num = $this->db->num_rows($resql);
5662
-			$i = 0;
5663
-			if ($num)
5664
-			{
5665
-				while ($i < $num)
5666
-				{
5667
-					$obj = $this->db->fetch_object($resql);
5668
-					$label='';
5669
-					$tmparray=explode(',', $fieldstoshow);
5670
-					foreach($tmparray as $key => $val)
5671
-					{
5672
-						$val = preg_replace('/t\./','',$val);
5673
-						$label .= (($label && $obj->$val)?' - ':'').$obj->$val;
5674
-					}
5675
-					if (empty($outputmode))
5676
-					{
5677
-						if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid)
5678
-						{
5679
-							$out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
5680
-						}
5681
-						else
5682
-						{
5683
-							$out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
5684
-						}
5685
-					}
5686
-					else
5687
-					{
5688
-						array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
5689
-					}
5797
+                if ($key_in_label)
5798
+                {
5799
+                    if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));
5800
+                    else $selectOptionValue = $key.' - '.($maxlen?dol_trunc($value,$maxlen):$value);
5801
+                }
5802
+                else
5803
+                {
5804
+                    if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);
5805
+                    else $selectOptionValue = $maxlen?dol_trunc($value,$maxlen):$value;
5806
+                    if ($value == '' || $value == '-') $selectOptionValue='&nbsp;';
5807
+                }
5690 5808
 
5691
-					$i++;
5692
-					if (($i % 10) == 0) $out.="\n";
5693
-				}
5694
-			}
5695
-
5696
-			$out.= '</select>'."\n";
5697
-		}
5698
-		else
5699
-		{
5700
-			dol_print_error($this->db);
5701
-		}
5702
-
5703
-		$this->result=array('nbofelement'=>$num);
5704
-
5705
-		if ($outputmode) return $outarray;
5706
-		return $out;
5707
-	}
5708
-
5709
-
5710
-	/**
5711
-	 *	Return a HTML select string, built from an array of key+value.
5712
-	 *  Note: Do not apply langs->trans function on returned content, content may be entity encoded twice.
5713
-	 *
5714
-	 *	@param	string			$htmlname			Name of html select area. Must start with "multi" if this is a multiselect
5715
-	 *	@param	array			$array				Array (key => value)
5716
-	 *	@param	string|string[]	$id					Preselected key or preselected keys for multiselect
5717
-	 *	@param	int|string		$show_empty			0 no empty value allowed, 1 or string to add an empty value into list (key is -1 and value is '' or '&nbsp;' if 1, key is -1 and value is text if string), <0 to add an empty value with key that is this value.
5718
-	 *	@param	int				$key_in_label		1 to show key into label with format "[key] value"
5719
-	 *	@param	int				$value_as_key		1 to use value as key
5720
-	 *	@param  string			$moreparam			Add more parameters onto the select tag. For example 'style="width: 95%"' to avoid select2 component to go over parent container
5721
-	 *	@param  int				$translate			1=Translate and encode value
5722
-	 * 	@param	int				$maxlen				Length maximum for labels
5723
-	 * 	@param	int				$disabled			Html select box is disabled
5724
-	 *  @param	string			$sort				'ASC' or 'DESC' = Sort on label, '' or 'NONE' or 'POS' = Do not sort, we keep original order
5725
-	 *  @param	string			$morecss			Add more class to css styles
5726
-	 *  @param	int				$addjscombo			Add js combo
5727
-	 *  @param  string          $moreparamonempty	Add more param on the empty option line. Not used if show_empty not set
5728
-	 *  @param  int             $disablebademail	Check if an email is found into value and if not disable and colorize entry
5729
-	 *  @param  int             $nohtmlescape		No html escaping.
5730
-	 * 	@return	string								HTML select string.
5731
-	 *  @see multiselectarray
5732
-	 */
5733
-	static function selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='', $addjscombo=0, $moreparamonempty='',$disablebademail=0, $nohtmlescape=0)
5734
-	{
5735
-		global $conf, $langs;
5736
-
5737
-		// Do we want a multiselect ?
5738
-		//$jsbeautify = 0;
5739
-		//if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
5740
-		$jsbeautify = 1;
5741
-
5742
-		if ($value_as_key) $array=array_combine($array, $array);
5743
-
5744
-		$out='';
5745
-
5746
-		// Add code for jquery to use multiselect
5747
-		if ($addjscombo && $jsbeautify)
5748
-		{
5749
-			$minLengthToAutocomplete=0;
5750
-			$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?(constant('REQUIRE_JQUERY_MULTISELECT')?constant('REQUIRE_JQUERY_MULTISELECT'):'select2'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
5751
-
5752
-			// Enhance with select2
5753
-			include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5754
-			$out .= ajax_combobox($htmlname);
5755
-		}
5756
-
5757
-		$out.='<select id="'.preg_replace('/^\./','',$htmlname).'" '.($disabled?'disabled ':'').'class="flat '.(preg_replace('/^\./','',$htmlname)).($morecss?' '.$morecss:'').'"';
5758
-		$out.=' name="'.preg_replace('/^\./','',$htmlname).'" '.($moreparam?$moreparam:'');
5759
-		$out.='>';
5760
-
5761
-		if ($show_empty)
5762
-		{
5763
-			$textforempty=' ';
5764
-			if (! empty($conf->use_javascript_ajax)) $textforempty='&nbsp;';	// If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
5765
-			if (! is_numeric($show_empty)) $textforempty=$show_empty;
5766
-			$out.='<option class="optiongrey" '.($moreparamonempty?$moreparamonempty.' ':'').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ?' selected':'').'>'.$textforempty.'</option>'."\n";
5767
-		}
5768
-
5769
-		if (is_array($array))
5770
-		{
5771
-			// Translate
5772
-			if ($translate)
5773
-			{
5774
-				foreach($array as $key => $value)
5775
-				{
5776
-					$array[$key]=$langs->trans($value);
5777
-				}
5778
-			}
5779
-
5780
-			// Sort
5781
-			if ($sort == 'ASC') asort($array);
5782
-			elseif ($sort == 'DESC') arsort($array);
5783
-
5784
-			foreach($array as $key => $value)
5785
-			{
5786
-				$disabled=''; $style='';
5787
-				if (! empty($disablebademail))
5788
-				{
5789
-					if (! preg_match('/&lt;.+@.+&gt;/', $value))
5790
-					{
5791
-						//$value=preg_replace('/'.preg_quote($a,'/').'/', $b, $value);
5792
-						$disabled=' disabled';
5793
-						$style=' class="warning"';
5794
-					}
5795
-				}
5796
-
5797
-				if ($key_in_label)
5798
-				{
5799
-					if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));
5800
-					else $selectOptionValue = $key.' - '.($maxlen?dol_trunc($value,$maxlen):$value);
5801
-				}
5802
-				else
5803
-				{
5804
-					if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);
5805
-					else $selectOptionValue = $maxlen?dol_trunc($value,$maxlen):$value;
5806
-					if ($value == '' || $value == '-') $selectOptionValue='&nbsp;';
5807
-				}
5808
-
5809
-				$out.='<option value="'.$key.'"';
5810
-				$out.=$style.$disabled;
5811
-				if ($id != '' && $id == $key && ! $disabled) $out.=' selected';		// To preselect a value
5812
-				if ($nohtmlescape) $out.=' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
5813
-				$out.='>';
5814
-				//var_dump($selectOptionValue);
5815
-				$out.=$selectOptionValue;
5816
-				$out.="</option>\n";
5817
-			}
5818
-		}
5819
-
5820
-		$out.="</select>";
5821
-		return $out;
5822
-	}
5823
-
5824
-
5825
-	/**
5826
-	 *	Return a HTML select string, built from an array of key+value, but content returned into select come from an Ajax call of an URL.
5827
-	 *  Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
5828
-	 *
5829
-	 *	@param	string	$htmlname       		Name of html select area
5830
-	 *	@param	string	$url					Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
5831
-	 *	@param	string	$id             		Preselected key
5832
-	 *	@param  string	$moreparam      		Add more parameters onto the select tag
5833
-	 *	@param  string	$moreparamtourl 		Add more parameters onto the Ajax called URL
5834
-	 * 	@param	int		$disabled				Html select box is disabled
5835
-	 *  @param	int		$minimumInputLength		Minimum Input Length
5836
-	 *  @param	string	$morecss				Add more class to css styles
5837
-	 *  @param  int     $callurlonselect        If set to 1, some code is added so an url return by the ajax is called when value is selected.
5838
-	 *  @param  string  $placeholder            String to use as placeholder
5839
-	 *  @param  integer $acceptdelayedhtml      1 = caller is requesting to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
5840
-	 * 	@return	string   						HTML select string
5841
-	 *  @see selectArrayFilter, ajax_combobox in ajax.lib.php
5842
-	 */
5843
-	static function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
5844
-	{
5845
-		global $conf, $langs;
5846
-		global $delayedhtmlcontent;
5847
-
5848
-		// TODO Use an internal dolibarr component instead of select2
5849
-		if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
5850
-
5851
-		$out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"></select>';
5852
-
5853
-		$tmpplugin='select2';
5854
-		$outdelayed="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
5809
+                $out.='<option value="'.$key.'"';
5810
+                $out.=$style.$disabled;
5811
+                if ($id != '' && $id == $key && ! $disabled) $out.=' selected';		// To preselect a value
5812
+                if ($nohtmlescape) $out.=' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
5813
+                $out.='>';
5814
+                //var_dump($selectOptionValue);
5815
+                $out.=$selectOptionValue;
5816
+                $out.="</option>\n";
5817
+            }
5818
+        }
5819
+
5820
+        $out.="</select>";
5821
+        return $out;
5822
+    }
5823
+
5824
+
5825
+    /**
5826
+     *	Return a HTML select string, built from an array of key+value, but content returned into select come from an Ajax call of an URL.
5827
+     *  Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
5828
+     *
5829
+     *	@param	string	$htmlname       		Name of html select area
5830
+     *	@param	string	$url					Url. Must return a json_encode of array(key=>array('text'=>'A text', 'url'=>'An url'), ...)
5831
+     *	@param	string	$id             		Preselected key
5832
+     *	@param  string	$moreparam      		Add more parameters onto the select tag
5833
+     *	@param  string	$moreparamtourl 		Add more parameters onto the Ajax called URL
5834
+     * 	@param	int		$disabled				Html select box is disabled
5835
+     *  @param	int		$minimumInputLength		Minimum Input Length
5836
+     *  @param	string	$morecss				Add more class to css styles
5837
+     *  @param  int     $callurlonselect        If set to 1, some code is added so an url return by the ajax is called when value is selected.
5838
+     *  @param  string  $placeholder            String to use as placeholder
5839
+     *  @param  integer $acceptdelayedhtml      1 = caller is requesting to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
5840
+     * 	@return	string   						HTML select string
5841
+     *  @see selectArrayFilter, ajax_combobox in ajax.lib.php
5842
+     */
5843
+    static function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
5844
+    {
5845
+        global $conf, $langs;
5846
+        global $delayedhtmlcontent;
5847
+
5848
+        // TODO Use an internal dolibarr component instead of select2
5849
+        if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
5850
+
5851
+        $out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"></select>';
5852
+
5853
+        $tmpplugin='select2';
5854
+        $outdelayed="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
5855 5855
 	    	<script type="text/javascript">
5856 5856
 	    	$(document).ready(function () {
5857 5857
 
@@ -5913,57 +5913,57 @@  discard block
 block discarded – undo
5913 5913
     	   });
5914 5914
 	       </script>';
5915 5915
 
5916
-		if ($acceptdelayedhtml)
5917
-		{
5918
-			$delayedhtmlcontent.=$outdelayed;
5919
-		}
5920
-		else
5921
-		{
5922
-			$out.=$outdelayed;
5923
-		}
5924
-		return $out;
5925
-	}
5926
-
5927
-	/**
5928
-	 *	Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
5929
-	 *  Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
5930
-	 *
5931
-	 *	@param	string	$htmlname       		Name of html select area
5932
-	 *	@param	string	$array					Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
5933
-	 *	@param	string	$id             		Preselected key
5934
-	 *	@param  string	$moreparam      		Add more parameters onto the select tag
5935
-	 *	@param	int		$disableFiltering		If set to 1, results are not filtered with searched string
5936
-	 * 	@param	int		$disabled				Html select box is disabled
5937
-	 *  @param	int		$minimumInputLength		Minimum Input Length
5938
-	 *  @param	string	$morecss				Add more class to css styles
5939
-	 *  @param  int     $callurlonselect        If set to 1, some code is added so an url return by the ajax is called when value is selected.
5940
-	 *  @param  string  $placeholder            String to use as placeholder
5941
-	 *  @param  integer $acceptdelayedhtml      1 = caller is requesting to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
5942
-	 * 	@return	string   						HTML select string
5943
-	 *  @see selectArrayAjax, ajax_combobox in ajax.lib.php
5944
-	 */
5945
-	static function selectArrayFilter($htmlname, $array, $id='', $moreparam='', $disableFiltering=0, $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
5946
-	{
5947
-		global $conf, $langs;
5948
-		global $delayedhtmlcontent;
5949
-
5950
-		// TODO Use an internal dolibarr component instead of select2
5951
-		if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
5952
-
5953
-		$out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"><option></option></select>';
5954
-
5955
-		$formattedarrayresult = array();
5956
-
5957
-		foreach($array as $key => $value) {
5958
-			$o = new stdClass();
5959
-			$o->id = $key;
5960
-			$o->text = $value['text'];
5961
-			$o->url = $value['url'];
5962
-			$formattedarrayresult[] = $o;
5963
-		}
5964
-
5965
-		$tmpplugin='select2';
5966
-		$outdelayed="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
5916
+        if ($acceptdelayedhtml)
5917
+        {
5918
+            $delayedhtmlcontent.=$outdelayed;
5919
+        }
5920
+        else
5921
+        {
5922
+            $out.=$outdelayed;
5923
+        }
5924
+        return $out;
5925
+    }
5926
+
5927
+    /**
5928
+     *	Return a HTML select string, built from an array of key+value, but content returned into select is defined into $array parameter.
5929
+     *  Note: Do not apply langs->trans function on returned content of Ajax service, content may be entity encoded twice.
5930
+     *
5931
+     *	@param	string	$htmlname       		Name of html select area
5932
+     *	@param	string	$array					Array (key=>array('text'=>'A text', 'url'=>'An url'), ...)
5933
+     *	@param	string	$id             		Preselected key
5934
+     *	@param  string	$moreparam      		Add more parameters onto the select tag
5935
+     *	@param	int		$disableFiltering		If set to 1, results are not filtered with searched string
5936
+     * 	@param	int		$disabled				Html select box is disabled
5937
+     *  @param	int		$minimumInputLength		Minimum Input Length
5938
+     *  @param	string	$morecss				Add more class to css styles
5939
+     *  @param  int     $callurlonselect        If set to 1, some code is added so an url return by the ajax is called when value is selected.
5940
+     *  @param  string  $placeholder            String to use as placeholder
5941
+     *  @param  integer $acceptdelayedhtml      1 = caller is requesting to have html js content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
5942
+     * 	@return	string   						HTML select string
5943
+     *  @see selectArrayAjax, ajax_combobox in ajax.lib.php
5944
+     */
5945
+    static function selectArrayFilter($htmlname, $array, $id='', $moreparam='', $disableFiltering=0, $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
5946
+    {
5947
+        global $conf, $langs;
5948
+        global $delayedhtmlcontent;
5949
+
5950
+        // TODO Use an internal dolibarr component instead of select2
5951
+        if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
5952
+
5953
+        $out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"><option></option></select>';
5954
+
5955
+        $formattedarrayresult = array();
5956
+
5957
+        foreach($array as $key => $value) {
5958
+            $o = new stdClass();
5959
+            $o->id = $key;
5960
+            $o->text = $value['text'];
5961
+            $o->url = $value['url'];
5962
+            $formattedarrayresult[] = $o;
5963
+        }
5964
+
5965
+        $tmpplugin='select2';
5966
+        $outdelayed="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
5967 5967
 			<script type="text/javascript">
5968 5968
 			$(document).ready(function () {
5969 5969
 				var data = '.json_encode($formattedarrayresult).';
@@ -5984,31 +5984,31 @@  discard block
 block discarded – undo
5984 5984
 
5985 5985
 						if(! data.id) return null;';
5986 5986
 
5987
-		if($callurlonselect) {
5988
-			$outdelayed.='
5987
+        if($callurlonselect) {
5988
+            $outdelayed.='
5989 5989
 
5990 5990
 						var urlBase = data.url;
5991 5991
 						var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
5992 5992
 						/* console.log("params.term="+params.term); */
5993 5993
 						/* console.log("params.term encoded="+encodeURIComponent(params.term)); */
5994 5994
 						saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term);';
5995
-		}
5995
+        }
5996 5996
 
5997
-		if(! $disableFiltering) {
5998
-			$outdelayed.='
5997
+        if(! $disableFiltering) {
5998
+            $outdelayed.='
5999 5999
 
6000 6000
 						if(data.text.match(new RegExp(params.term))) {
6001 6001
 							return data;
6002 6002
 						}
6003 6003
 
6004 6004
 						return null;';
6005
-		} else {
6006
-			$outdelayed.='
6005
+        } else {
6006
+            $outdelayed.='
6007 6007
 
6008 6008
 						return data;';
6009
-		}
6009
+        }
6010 6010
 
6011
-		$outdelayed.='
6011
+        $outdelayed.='
6012 6012
 					}
6013 6013
 				});
6014 6014
 
@@ -6031,73 +6031,73 @@  discard block
 block discarded – undo
6031 6031
 			});
6032 6032
 			</script>';
6033 6033
 
6034
-		if ($acceptdelayedhtml)
6035
-		{
6036
-			$delayedhtmlcontent.=$outdelayed;
6037
-		}
6038
-		else
6039
-		{
6040
-			$out.=$outdelayed;
6041
-		}
6042
-		return $out;
6043
-	}
6044
-
6045
-	/**
6046
-	 *	Show a multiselect form from an array.
6047
-	 *
6048
-	 *	@param	string	$htmlname		Name of select
6049
-	 *	@param	array	$array			Array with key+value
6050
-	 *	@param	array	$selected		Array with key+value preselected
6051
-	 *	@param	int		$key_in_label   1 pour afficher la key dans la valeur "[key] value"
6052
-	 *	@param	int		$value_as_key   1 to use value as key
6053
-	 *	@param  string	$morecss        Add more css style
6054
-	 *	@param  int		$translate		Translate and encode value
6055
-	 *  @param	int		$width			Force width of select box. May be used only when using jquery couch. Example: 250, 95%
6056
-	 *  @param	string	$moreattrib		Add more options on select component. Example: 'disabled'
6057
-	 *  @param	string	$elemtype		Type of element we show ('category', ...)
6058
-	 *  @param	string	$placeholder	String to use as placeholder
6059
-	 *  @param	int		$addjscombo		Add js combo
6060
-	 *	@return	string					HTML multiselect string
6061
-	 *  @see selectarray
6062
-	 */
6063
-	static function multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $morecss='', $translate=0, $width=0, $moreattrib='', $elemtype='', $placeholder='', $addjscombo=1)
6064
-	{
6065
-		global $conf, $langs;
6066
-
6067
-		$out = '';
6068
-
6069
-
6070
-		// Add code for jquery to use multiselect
6071
-		if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
6072
-		{
6073
-			$out.="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
6034
+        if ($acceptdelayedhtml)
6035
+        {
6036
+            $delayedhtmlcontent.=$outdelayed;
6037
+        }
6038
+        else
6039
+        {
6040
+            $out.=$outdelayed;
6041
+        }
6042
+        return $out;
6043
+    }
6044
+
6045
+    /**
6046
+     *	Show a multiselect form from an array.
6047
+     *
6048
+     *	@param	string	$htmlname		Name of select
6049
+     *	@param	array	$array			Array with key+value
6050
+     *	@param	array	$selected		Array with key+value preselected
6051
+     *	@param	int		$key_in_label   1 pour afficher la key dans la valeur "[key] value"
6052
+     *	@param	int		$value_as_key   1 to use value as key
6053
+     *	@param  string	$morecss        Add more css style
6054
+     *	@param  int		$translate		Translate and encode value
6055
+     *  @param	int		$width			Force width of select box. May be used only when using jquery couch. Example: 250, 95%
6056
+     *  @param	string	$moreattrib		Add more options on select component. Example: 'disabled'
6057
+     *  @param	string	$elemtype		Type of element we show ('category', ...)
6058
+     *  @param	string	$placeholder	String to use as placeholder
6059
+     *  @param	int		$addjscombo		Add js combo
6060
+     *	@return	string					HTML multiselect string
6061
+     *  @see selectarray
6062
+     */
6063
+    static function multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $morecss='', $translate=0, $width=0, $moreattrib='', $elemtype='', $placeholder='', $addjscombo=1)
6064
+    {
6065
+        global $conf, $langs;
6066
+
6067
+        $out = '';
6068
+
6069
+
6070
+        // Add code for jquery to use multiselect
6071
+        if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
6072
+        {
6073
+            $out.="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
6074 6074
 						<script type="text/javascript">'."\n";
6075
-			if ($addjscombo == 1)
6076
-			{
6077
-				$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
6078
-				$out.=	'function formatResult(record) {'."\n";
6079
-				if ($elemtype == 'category')
6080
-				{
6081
-					$out.='	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6075
+            if ($addjscombo == 1)
6076
+            {
6077
+                $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
6078
+                $out.=	'function formatResult(record) {'."\n";
6079
+                if ($elemtype == 'category')
6080
+                {
6081
+                    $out.='	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6082 6082
 									  	return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
6083
-				}
6084
-				else
6085
-				{
6086
-					$out.='return record.text;';
6087
-				}
6088
-				$out.=	'};'."\n";
6089
-				$out.=	'function formatSelection(record) {'."\n";
6090
-				if ($elemtype == 'category')
6091
-				{
6092
-					$out.='	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6083
+                }
6084
+                else
6085
+                {
6086
+                    $out.='return record.text;';
6087
+                }
6088
+                $out.=	'};'."\n";
6089
+                $out.=	'function formatSelection(record) {'."\n";
6090
+                if ($elemtype == 'category')
6091
+                {
6092
+                    $out.='	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6093 6093
 									  	return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
6094
-				}
6095
-				else
6096
-				{
6097
-					$out.='return record.text;';
6098
-				}
6099
-				$out.=	'};'."\n";
6100
-				$out.=	'$(document).ready(function () {
6094
+                }
6095
+                else
6096
+                {
6097
+                    $out.='return record.text;';
6098
+                }
6099
+                $out.=	'};'."\n";
6100
+                $out.=	'$(document).ready(function () {
6101 6101
 							$(\'#'.$htmlname.'\').'.$tmpplugin.'({
6102 6102
 								dir: \'ltr\',
6103 6103
 								// Specify format function for dropdown item
@@ -6108,12 +6108,12 @@  discard block
 block discarded – undo
6108 6108
 							 	templateResult: formatSelection		/* For 4.0 */
6109 6109
 							});
6110 6110
 						});'."\n";
6111
-			}
6112
-			elseif ($addjscombo == 2)
6113
-			{
6114
-				// Add other js lib
6115
-				// ...
6116
-				$out.= '$(document).ready(function () {
6111
+            }
6112
+            elseif ($addjscombo == 2)
6113
+            {
6114
+                // Add other js lib
6115
+                // ...
6116
+                $out.= '$(document).ready(function () {
6117 6117
 							$(\'#'.$htmlname.'\').multiSelect({
6118 6118
 								containerHTML: \'<div class="multi-select-container">\',
6119 6119
 								menuHTML: \'<div class="multi-select-menu">\',
@@ -6123,91 +6123,91 @@  discard block
 block discarded – undo
6123 6123
 								noneText: \''.$placeholder.'\'
6124 6124
 							});
6125 6125
 						})';
6126
-			}
6127
-			$out.=	'</script>';
6128
-		}
6129
-
6130
-		// Try also magic suggest
6131
-
6132
-		$out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss?' '.$morecss:'').'" multiple name="'.$htmlname.'[]"'.($moreattrib?' '.$moreattrib:'').($width?' style="width: '.(preg_match('/%/',$width)?$width:$width.'px').'"':'').'>'."\n";
6133
-		if (is_array($array) && ! empty($array))
6134
-		{
6135
-			if ($value_as_key) $array=array_combine($array, $array);
6136
-
6137
-			if (! empty($array))
6138
-			{
6139
-				foreach ($array as $key => $value)
6140
-				{
6141
-					$out.= '<option value="'.$key.'"';
6142
-					if (is_array($selected) && ! empty($selected) && in_array($key, $selected) && !empty($key))
6143
-					{
6144
-						$out.= ' selected';
6145
-					}
6146
-					$out.= '>';
6147
-
6148
-					$newval = ($translate ? $langs->trans($value) : $value);
6149
-					$newval = ($key_in_label ? $key.' - '.$newval : $newval);
6150
-					$out.= dol_htmlentitiesbr($newval);
6151
-					$out.= '</option>'."\n";
6152
-				}
6153
-			}
6154
-		}
6155
-		$out.= '</select>'."\n";
6156
-
6157
-		return $out;
6158
-	}
6159
-
6160
-
6161
-	/**
6162
-	 *	Show a multiselect dropbox from an array.
6163
-	 *
6164
-	 *	@param	string	$htmlname		Name of HTML field
6165
-	 *	@param	array	$array			Array with array of fields we could show. This array may be modified according to setup of user.
6166
-	 *  @param  string  $varpage        Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
6167
-	 *	@return	string					HTML multiselect string
6168
-	 *  @see selectarray
6169
-	 */
6170
-	static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
6171
-	{
6172
-		global $conf,$langs,$user;
6173
-
6174
-		if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
6175
-
6176
-		$tmpvar="MAIN_SELECTEDFIELDS_".$varpage;
6177
-		if (! empty($user->conf->$tmpvar))
6178
-		{
6179
-			$tmparray=explode(',', $user->conf->$tmpvar);
6180
-			foreach($array as $key => $val)
6181
-			{
6182
-				//var_dump($key);
6183
-				//var_dump($tmparray);
6184
-				if (in_array($key, $tmparray)) $array[$key]['checked']=1;
6185
-				else $array[$key]['checked']=0;
6186
-			}
6187
-		}
6188
-		//var_dump($array);
6189
-
6190
-		$lis='';
6191
-		$listcheckedstring='';
6192
-
6193
-		foreach($array as $key => $val)
6194
-		{
6195
-		   /* var_dump($val);
6126
+            }
6127
+            $out.=	'</script>';
6128
+        }
6129
+
6130
+        // Try also magic suggest
6131
+
6132
+        $out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss?' '.$morecss:'').'" multiple name="'.$htmlname.'[]"'.($moreattrib?' '.$moreattrib:'').($width?' style="width: '.(preg_match('/%/',$width)?$width:$width.'px').'"':'').'>'."\n";
6133
+        if (is_array($array) && ! empty($array))
6134
+        {
6135
+            if ($value_as_key) $array=array_combine($array, $array);
6136
+
6137
+            if (! empty($array))
6138
+            {
6139
+                foreach ($array as $key => $value)
6140
+                {
6141
+                    $out.= '<option value="'.$key.'"';
6142
+                    if (is_array($selected) && ! empty($selected) && in_array($key, $selected) && !empty($key))
6143
+                    {
6144
+                        $out.= ' selected';
6145
+                    }
6146
+                    $out.= '>';
6147
+
6148
+                    $newval = ($translate ? $langs->trans($value) : $value);
6149
+                    $newval = ($key_in_label ? $key.' - '.$newval : $newval);
6150
+                    $out.= dol_htmlentitiesbr($newval);
6151
+                    $out.= '</option>'."\n";
6152
+                }
6153
+            }
6154
+        }
6155
+        $out.= '</select>'."\n";
6156
+
6157
+        return $out;
6158
+    }
6159
+
6160
+
6161
+    /**
6162
+     *	Show a multiselect dropbox from an array.
6163
+     *
6164
+     *	@param	string	$htmlname		Name of HTML field
6165
+     *	@param	array	$array			Array with array of fields we could show. This array may be modified according to setup of user.
6166
+     *  @param  string  $varpage        Id of context for page. Can be set by caller with $varpage=(empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage);
6167
+     *	@return	string					HTML multiselect string
6168
+     *  @see selectarray
6169
+     */
6170
+    static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
6171
+    {
6172
+        global $conf,$langs,$user;
6173
+
6174
+        if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
6175
+
6176
+        $tmpvar="MAIN_SELECTEDFIELDS_".$varpage;
6177
+        if (! empty($user->conf->$tmpvar))
6178
+        {
6179
+            $tmparray=explode(',', $user->conf->$tmpvar);
6180
+            foreach($array as $key => $val)
6181
+            {
6182
+                //var_dump($key);
6183
+                //var_dump($tmparray);
6184
+                if (in_array($key, $tmparray)) $array[$key]['checked']=1;
6185
+                else $array[$key]['checked']=0;
6186
+            }
6187
+        }
6188
+        //var_dump($array);
6189
+
6190
+        $lis='';
6191
+        $listcheckedstring='';
6192
+
6193
+        foreach($array as $key => $val)
6194
+        {
6195
+            /* var_dump($val);
6196 6196
             var_dump(array_key_exists('enabled', $val));
6197 6197
             var_dump(!$val['enabled']);*/
6198
-		   if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled'])
6199
-		   {
6200
-			   unset($array[$key]);     // We don't want this field
6201
-			   continue;
6202
-		   }
6203
-		   if ($val['label'])
6204
-		   {
6205
-		   	$lis.='<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.(empty($val['checked'])?'':' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
6206
-			   $listcheckedstring.=(empty($val['checked'])?'':$key.',');
6207
-		   }
6208
-		}
6209
-
6210
-		$out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
6198
+            if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled'])
6199
+            {
6200
+                unset($array[$key]);     // We don't want this field
6201
+                continue;
6202
+            }
6203
+            if ($val['label'])
6204
+            {
6205
+                $lis.='<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.(empty($val['checked'])?'':' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
6206
+                $listcheckedstring.=(empty($val['checked'])?'':$key.',');
6207
+            }
6208
+        }
6209
+
6210
+        $out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
6211 6211
 
6212 6212
         <dl class="dropdown">
6213 6213
             <dt>
@@ -6225,355 +6225,355 @@  discard block
 block discarded – undo
6225 6225
             </dd>
6226 6226
         </dl>
6227 6227
 
6228
-        <script type="text/javascript">
6229
-          jQuery(document).ready(function () {
6230
-              $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
6231
-                  console.log("A new field was added/removed")
6232
-                  $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\')
6233
-                  var title = $(this).val() + ",";
6234
-                  if ($(this).is(\':checked\')) {
6235
-                      $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
6236
-                  }
6237
-                  else {
6238
-                      $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
6239
-                  }
6240
-                  // Now, we submit page
6241
-                  $(this).parents(\'form:first\').submit();
6242
-              });
6243
-           });
6244
-        </script>
6228
+        <script type="text/javascript">
6229
+          jQuery(document).ready(function () {
6230
+              $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
6231
+                  console.log("A new field was added/removed")
6232
+                  $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\')
6233
+                  var title = $(this).val() + ",";
6234
+                  if ($(this).is(\':checked\')) {
6235
+                      $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
6236
+                  }
6237
+                  else {
6238
+                      $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
6239
+                  }
6240
+                  // Now, we submit page
6241
+                  $(this).parents(\'form:first\').submit();
6242
+              });
6243
+           });
6244
+        </script>
6245
+
6246
+        ';
6247
+        return $out;
6248
+    }
6249
+
6250
+    /**
6251
+     * 	Render list of categories linked to object with id $id and type $type
6252
+     *
6253
+     * 	@param		int		$id				Id of object
6254
+     * 	@param		string	$type			Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
6255
+     *  @param		int		$rendermode		0=Default, use multiselect. 1=Emulate multiselect (recommended)
6256
+     * 	@return		string					String with categories
6257
+     */
6258
+    function showCategories($id, $type, $rendermode=0)
6259
+    {
6260
+        global $db;
6261
+
6262
+        include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
6263
+
6264
+        $cat = new Categorie($db);
6265
+        $categories = $cat->containing($id, $type);
6266
+
6267
+        if ($rendermode == 1)
6268
+        {
6269
+            $toprint = array();
6270
+            foreach($categories as $c)
6271
+            {
6272
+                $ways = $c->print_all_ways();       // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
6273
+                foreach($ways as $way)
6274
+                {
6275
+                    $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color?' style="background: #'.$c->color.';"':' style="background: #aaa"').'>'.img_object('','category').' '.$way.'</li>';
6276
+                }
6277
+            }
6278
+            return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6279
+        }
6280
+
6281
+        if ($rendermode == 0)
6282
+        {
6283
+            $cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
6284
+            foreach($categories as $c) {
6285
+                $arrayselected[] = $c->id;
6286
+            }
6287
+
6288
+            return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
6289
+        }
6290
+
6291
+        return 'ErrorBadValueForParameterRenderMode';	// Should not happened
6292
+    }
6293
+
6294
+
6295
+    /**
6296
+     *  Show linked object block.
6297
+     *
6298
+     *  @param	CommonObject	$object		      Object we want to show links to
6299
+     *  @param  string          $morehtmlright    More html to show on right of title
6300
+     *  @param  array           $compatibleImportElementsList  Array of compatibles elements object for "import from" action
6301
+     *  @return	int							      <0 if KO, >=0 if OK
6302
+     */
6303
+    function showLinkedObjectBlock($object, $morehtmlright='',$compatibleImportElementsList=false)
6304
+    {
6305
+        global $conf,$langs,$hookmanager;
6306
+        global $bc;
6307
+
6308
+        $object->fetchObjectLinked();
6309
+
6310
+        // Bypass the default method
6311
+        $hookmanager->initHooks(array('commonobject'));
6312
+        $parameters=array(
6313
+            'morehtmlright' => $morehtmlright,
6314
+            'compatibleImportElementsList' =>& $compatibleImportElementsList,
6315
+        );
6316
+        $reshook=$hookmanager->executeHooks('showLinkedObjectBlock',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
6317
+
6318
+        if (empty($reshook))
6319
+        {
6320
+            $nbofdifferenttypes = count($object->linkedObjects);
6321
+
6322
+            print '<!-- showLinkedObjectBlock -->';
6323
+            print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
6324
+
6325
+
6326
+            print '<div class="div-table-responsive-no-min">';
6327
+            print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'"  data-elementid="'.$object->id.'"   >';
6328
+
6329
+            print '<tr class="liste_titre">';
6330
+            print '<td>'.$langs->trans("Type").'</td>';
6331
+            print '<td>'.$langs->trans("Ref").'</td>';
6332
+            print '<td align="center"></td>';
6333
+            print '<td align="center">'.$langs->trans("Date").'</td>';
6334
+            print '<td align="right">'.$langs->trans("AmountHTShort").'</td>';
6335
+            print '<td align="right">'.$langs->trans("Status").'</td>';
6336
+            print '<td></td>';
6337
+            print '</tr>';
6338
+
6339
+            $nboftypesoutput=0;
6340
+
6341
+            foreach($object->linkedObjects as $objecttype => $objects)
6342
+            {
6343
+                $tplpath = $element = $subelement = $objecttype;
6344
+
6345
+                // to display inport button on tpl
6346
+                $showImportButton=false;
6347
+                if(!empty($compatibleImportElementsList) && in_array($element,$compatibleImportElementsList)){
6348
+                    $showImportButton=true;
6349
+                }
6350
+
6351
+                if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
6352
+                {
6353
+                    $element = $regs[1];
6354
+                    $subelement = $regs[2];
6355
+                    $tplpath = $element.'/'.$subelement;
6356
+                }
6357
+                $tplname='linkedobjectblock';
6358
+
6359
+                // To work with non standard path
6360
+                if ($objecttype == 'facture')          {
6361
+                    $tplpath = 'compta/'.$element;
6362
+                    if (empty($conf->facture->enabled)) continue;	// Do not show if module disabled
6363
+                }
6364
+                else if ($objecttype == 'facturerec')          {
6365
+                    $tplpath = 'compta/facture';
6366
+                    $tplname = 'linkedobjectblockForRec';
6367
+                    if (empty($conf->facture->enabled)) continue;	// Do not show if module disabled
6368
+                }
6369
+                else if ($objecttype == 'propal')           {
6370
+                    $tplpath = 'comm/'.$element;
6371
+                    if (empty($conf->propal->enabled)) continue;	// Do not show if module disabled
6372
+                }
6373
+                else if ($objecttype == 'supplier_proposal')           {
6374
+                    if (empty($conf->supplier_proposal->enabled)) continue;	// Do not show if module disabled
6375
+                }
6376
+                else if ($objecttype == 'shipping' || $objecttype == 'shipment') {
6377
+                    $tplpath = 'expedition';
6378
+                    if (empty($conf->expedition->enabled)) continue;	// Do not show if module disabled
6379
+                }
6380
+                else if ($objecttype == 'reception') {
6381
+                    $tplpath = 'reception';
6382
+                    if (empty($conf->reception->enabled)) continue;	// Do not show if module disabled
6383
+                }
6384
+                else if ($objecttype == 'delivery')         {
6385
+                    $tplpath = 'livraison';
6386
+                    if (empty($conf->expedition->enabled)) continue;	// Do not show if module disabled
6387
+                }
6388
+                else if ($objecttype == 'invoice_supplier') {
6389
+                    $tplpath = 'fourn/facture';
6390
+                }
6391
+                else if ($objecttype == 'order_supplier')   {
6392
+                    $tplpath = 'fourn/commande';
6393
+                }
6394
+                else if ($objecttype == 'expensereport')   {
6395
+                    $tplpath = 'expensereport';
6396
+                }
6397
+                else if ($objecttype == 'subscription')   {
6398
+                    $tplpath = 'adherents';
6399
+                }
6400
+
6401
+                global $linkedObjectBlock;
6402
+                $linkedObjectBlock = $objects;
6403
+
6404
+
6405
+                // Output template part (modules that overwrite templates must declare this into descriptor)
6406
+                $dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));
6407
+                foreach($dirtpls as $reldir)
6408
+                {
6409
+                    if ($nboftypesoutput == ($nbofdifferenttypes - 1))    // No more type to show after
6410
+                    {
6411
+                        global $noMoreLinkedObjectBlockAfter;
6412
+                        $noMoreLinkedObjectBlockAfter=1;
6413
+                    }
6414
+
6415
+                    $res=@include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
6416
+                    if ($res)
6417
+                    {
6418
+                        $nboftypesoutput++;
6419
+                        break;
6420
+                    }
6421
+                }
6422
+            }
6423
+
6424
+            if (! $nboftypesoutput)
6425
+            {
6426
+                print '<tr><td class="impair opacitymedium" colspan="7">'.$langs->trans("None").'</td></tr>';
6427
+            }
6428
+
6429
+            print '</table>';
6430
+
6431
+            if(!empty($compatibleImportElementsList))
6432
+            {
6433
+                $res=@include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
6434
+            }
6435
+
6436
+
6437
+            print '</div>';
6438
+
6439
+            return $nbofdifferenttypes;
6440
+        }
6441
+    }
6442
+
6443
+    /**
6444
+     *  Show block with links to link to other objects.
6445
+     *
6446
+     *  @param	CommonObject	$object				Object we want to show links to
6447
+     *  @param	array			$restrictlinksto	Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
6448
+     *  @param	array			$excludelinksto		Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
6449
+     *  @return	string								<0 if KO, >0 if OK
6450
+     */
6451
+    function showLinkToObjectBlock($object, $restrictlinksto=array(), $excludelinksto=array())
6452
+    {
6453
+        global $conf, $langs, $hookmanager;
6454
+        global $bc;
6455
+
6456
+        $linktoelem='';
6457
+        $linktoelemlist='';
6458
+        $listofidcompanytoscan='';
6459
+
6460
+        if (! is_object($object->thirdparty)) $object->fetch_thirdparty();
6461
+
6462
+        $possiblelinks=array();
6463
+        if (is_object($object->thirdparty) && ! empty($object->thirdparty->id) && $object->thirdparty->id > 0)
6464
+        {
6465
+            $listofidcompanytoscan=$object->thirdparty->id;
6466
+            if (($object->thirdparty->parent > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan.=','.$object->thirdparty->parent;
6467
+            if (($object->fk_project > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))
6468
+            {
6469
+                include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
6470
+                $tmpproject=new Project($this->db);
6471
+                $tmpproject->fetch($object->fk_project);
6472
+                if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan.=','.$tmpproject->socid;
6473
+                unset($tmpproject);
6474
+            }
6475
+
6476
+            $possiblelinks=array(
6477
+                'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('propal').')'),
6478
+                'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande').')'),
6479
+                'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
6480
+                'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
6481
+                'contrat'=>array('enabled'=>$conf->contrat->enabled , 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'),
6482
+                'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'),
6483
+                'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled , 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'),
6484
+                'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled , 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
6485
+                'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled , 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')')
6486
+            );
6487
+        }
6488
+
6489
+        global $action;
6245 6490
 
6246
-        ';
6247
-		return $out;
6248
-	}
6249
-
6250
-	/**
6251
-	 * 	Render list of categories linked to object with id $id and type $type
6252
-	 *
6253
-	 * 	@param		int		$id				Id of object
6254
-	 * 	@param		string	$type			Type of category ('member', 'customer', 'supplier', 'product', 'contact'). Old mode (0, 1, 2, ...) is deprecated.
6255
-	 *  @param		int		$rendermode		0=Default, use multiselect. 1=Emulate multiselect (recommended)
6256
-	 * 	@return		string					String with categories
6257
-	 */
6258
-	function showCategories($id, $type, $rendermode=0)
6259
-	{
6260
-		global $db;
6261
-
6262
-		include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
6263
-
6264
-		$cat = new Categorie($db);
6265
-		$categories = $cat->containing($id, $type);
6266
-
6267
-		if ($rendermode == 1)
6268
-		{
6269
-			$toprint = array();
6270
-			foreach($categories as $c)
6271
-			{
6272
-				$ways = $c->print_all_ways();       // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
6273
-				foreach($ways as $way)
6274
-				{
6275
-					$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color?' style="background: #'.$c->color.';"':' style="background: #aaa"').'>'.img_object('','category').' '.$way.'</li>';
6276
-				}
6277
-			}
6278
-			return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6279
-		}
6280
-
6281
-		if ($rendermode == 0)
6282
-		{
6283
-			$cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
6284
-			foreach($categories as $c) {
6285
-				$arrayselected[] = $c->id;
6286
-			}
6287
-
6288
-			return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
6289
-		}
6290
-
6291
-		return 'ErrorBadValueForParameterRenderMode';	// Should not happened
6292
-	}
6293
-
6294
-
6295
-	/**
6296
-	 *  Show linked object block.
6297
-	 *
6298
-	 *  @param	CommonObject	$object		      Object we want to show links to
6299
-	 *  @param  string          $morehtmlright    More html to show on right of title
6300
-	 *  @param  array           $compatibleImportElementsList  Array of compatibles elements object for "import from" action
6301
-	 *  @return	int							      <0 if KO, >=0 if OK
6302
-	 */
6303
-	function showLinkedObjectBlock($object, $morehtmlright='',$compatibleImportElementsList=false)
6304
-	{
6305
-		global $conf,$langs,$hookmanager;
6306
-		global $bc;
6307
-
6308
-		$object->fetchObjectLinked();
6309
-
6310
-		// Bypass the default method
6311
-		$hookmanager->initHooks(array('commonobject'));
6312
-		$parameters=array(
6313
-			'morehtmlright' => $morehtmlright,
6314
-		    'compatibleImportElementsList' =>& $compatibleImportElementsList,
6315
-		);
6316
-		$reshook=$hookmanager->executeHooks('showLinkedObjectBlock',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
6317
-
6318
-		if (empty($reshook))
6319
-		{
6320
-			$nbofdifferenttypes = count($object->linkedObjects);
6321
-
6322
-			print '<!-- showLinkedObjectBlock -->';
6323
-			print load_fiche_titre($langs->trans('RelatedObjects'), $morehtmlright, '', 0, 0, 'showlinkedobjectblock');
6324
-
6325
-
6326
-			print '<div class="div-table-responsive-no-min">';
6327
-			print '<table class="noborder allwidth" data-block="showLinkedObject" data-element="'.$object->element.'"  data-elementid="'.$object->id.'"   >';
6328
-
6329
-			print '<tr class="liste_titre">';
6330
-			print '<td>'.$langs->trans("Type").'</td>';
6331
-			print '<td>'.$langs->trans("Ref").'</td>';
6332
-			print '<td align="center"></td>';
6333
-			print '<td align="center">'.$langs->trans("Date").'</td>';
6334
-			print '<td align="right">'.$langs->trans("AmountHTShort").'</td>';
6335
-			print '<td align="right">'.$langs->trans("Status").'</td>';
6336
-			print '<td></td>';
6337
-			print '</tr>';
6338
-
6339
-			$nboftypesoutput=0;
6340
-
6341
-			foreach($object->linkedObjects as $objecttype => $objects)
6342
-			{
6343
-				$tplpath = $element = $subelement = $objecttype;
6344
-
6345
-				// to display inport button on tpl
6346
-				$showImportButton=false;
6347
-				if(!empty($compatibleImportElementsList) && in_array($element,$compatibleImportElementsList)){
6348
-				    $showImportButton=true;
6349
-				}
6350
-
6351
-				if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
6352
-				{
6353
-					$element = $regs[1];
6354
-					$subelement = $regs[2];
6355
-					$tplpath = $element.'/'.$subelement;
6356
-				}
6357
-				$tplname='linkedobjectblock';
6358
-
6359
-				// To work with non standard path
6360
-				if ($objecttype == 'facture')          {
6361
-					$tplpath = 'compta/'.$element;
6362
-					if (empty($conf->facture->enabled)) continue;	// Do not show if module disabled
6363
-				}
6364
-				else if ($objecttype == 'facturerec')          {
6365
-					$tplpath = 'compta/facture';
6366
-					$tplname = 'linkedobjectblockForRec';
6367
-					if (empty($conf->facture->enabled)) continue;	// Do not show if module disabled
6368
-				}
6369
-				else if ($objecttype == 'propal')           {
6370
-					$tplpath = 'comm/'.$element;
6371
-					if (empty($conf->propal->enabled)) continue;	// Do not show if module disabled
6372
-				}
6373
-				else if ($objecttype == 'supplier_proposal')           {
6374
-					if (empty($conf->supplier_proposal->enabled)) continue;	// Do not show if module disabled
6375
-				}
6376
-				else if ($objecttype == 'shipping' || $objecttype == 'shipment') {
6377
-					$tplpath = 'expedition';
6378
-					if (empty($conf->expedition->enabled)) continue;	// Do not show if module disabled
6379
-				}
6380
-        		else if ($objecttype == 'reception') {
6381
-        			$tplpath = 'reception';
6382
-        			if (empty($conf->reception->enabled)) continue;	// Do not show if module disabled
6383
-        		}
6384
-				else if ($objecttype == 'delivery')         {
6385
-					$tplpath = 'livraison';
6386
-					if (empty($conf->expedition->enabled)) continue;	// Do not show if module disabled
6387
-				}
6388
-				else if ($objecttype == 'invoice_supplier') {
6389
-					$tplpath = 'fourn/facture';
6390
-				}
6391
-				else if ($objecttype == 'order_supplier')   {
6392
-					$tplpath = 'fourn/commande';
6393
-				}
6394
-				else if ($objecttype == 'expensereport')   {
6395
-					$tplpath = 'expensereport';
6396
-				}
6397
-				else if ($objecttype == 'subscription')   {
6398
-					$tplpath = 'adherents';
6399
-				}
6400
-
6401
-				global $linkedObjectBlock;
6402
-				$linkedObjectBlock = $objects;
6403
-
6404
-
6405
-				// Output template part (modules that overwrite templates must declare this into descriptor)
6406
-				$dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));
6407
-				foreach($dirtpls as $reldir)
6408
-				{
6409
-					if ($nboftypesoutput == ($nbofdifferenttypes - 1))    // No more type to show after
6410
-					{
6411
-						global $noMoreLinkedObjectBlockAfter;
6412
-						$noMoreLinkedObjectBlockAfter=1;
6413
-					}
6491
+        // Can complete the possiblelink array
6492
+        $hookmanager->initHooks(array('commonobject'));
6493
+        $parameters=array('listofidcompanytoscan' => $listofidcompanytoscan);
6494
+        $reshook=$hookmanager->executeHooks('showLinkToObjectBlock',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
6495
+        if (empty($reshook))
6496
+        {
6497
+            if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
6498
+            {
6499
+                $possiblelinks=array_merge($possiblelinks, $hookmanager->resArray);
6500
+            }
6501
+        }
6502
+        else if ($reshook > 0)
6503
+        {
6504
+            if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
6505
+            {
6506
+                $possiblelinks=$hookmanager->resArray;
6507
+            }
6508
+        }
6414 6509
 
6415
-					$res=@include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
6416
-					if ($res)
6417
-					{
6418
-						$nboftypesoutput++;
6419
-						break;
6420
-					}
6421
-				}
6422
-			}
6423
-
6424
-			if (! $nboftypesoutput)
6425
-			{
6426
-				print '<tr><td class="impair opacitymedium" colspan="7">'.$langs->trans("None").'</td></tr>';
6427
-			}
6428
-
6429
-			print '</table>';
6430
-
6431
-			if(!empty($compatibleImportElementsList))
6432
-			{
6433
-			    $res=@include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
6434
-			}
6435
-
6436
-
6437
-			print '</div>';
6438
-
6439
-			return $nbofdifferenttypes;
6440
-		}
6441
-	}
6442
-
6443
-	/**
6444
-	 *  Show block with links to link to other objects.
6445
-	 *
6446
-	 *  @param	CommonObject	$object				Object we want to show links to
6447
-	 *  @param	array			$restrictlinksto	Restrict links to some elements, for exemple array('order') or array('supplier_order'). null or array() if no restriction.
6448
-	 *  @param	array			$excludelinksto		Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
6449
-	 *  @return	string								<0 if KO, >0 if OK
6450
-	 */
6451
-	function showLinkToObjectBlock($object, $restrictlinksto=array(), $excludelinksto=array())
6452
-	{
6453
-		global $conf, $langs, $hookmanager;
6454
-		global $bc;
6455
-
6456
-		$linktoelem='';
6457
-		$linktoelemlist='';
6458
-		$listofidcompanytoscan='';
6459
-
6460
-		if (! is_object($object->thirdparty)) $object->fetch_thirdparty();
6461
-
6462
-		$possiblelinks=array();
6463
-		if (is_object($object->thirdparty) && ! empty($object->thirdparty->id) && $object->thirdparty->id > 0)
6464
-		{
6465
-			$listofidcompanytoscan=$object->thirdparty->id;
6466
-			if (($object->thirdparty->parent > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan.=','.$object->thirdparty->parent;
6467
-			if (($object->fk_project > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))
6468
-			{
6469
-				include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
6470
-				$tmpproject=new Project($this->db);
6471
-				$tmpproject->fetch($object->fk_project);
6472
-				if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan.=','.$tmpproject->socid;
6473
-				unset($tmpproject);
6474
-			}
6475
-
6476
-			$possiblelinks=array(
6477
-				'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('propal').')'),
6478
-				'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande').')'),
6479
-				'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
6480
-				'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
6481
-				'contrat'=>array('enabled'=>$conf->contrat->enabled , 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'),
6482
-				'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'),
6483
-				'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled , 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'),
6484
-				'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled , 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
6485
-				'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled , 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')')
6486
-			);
6487
-		}
6488
-
6489
-		global $action;
6490
-
6491
-		// Can complete the possiblelink array
6492
-		$hookmanager->initHooks(array('commonobject'));
6493
-		$parameters=array('listofidcompanytoscan' => $listofidcompanytoscan);
6494
-		$reshook=$hookmanager->executeHooks('showLinkToObjectBlock',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
6495
-		if (empty($reshook))
6496
-		{
6497
-			if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
6498
-			{
6499
-				$possiblelinks=array_merge($possiblelinks, $hookmanager->resArray);
6500
-			}
6501
-		}
6502
-		else if ($reshook > 0)
6503
-		{
6504
-			if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
6505
-			{
6506
-				$possiblelinks=$hookmanager->resArray;
6507
-			}
6508
-		}
6509
-
6510
-		foreach($possiblelinks as $key => $possiblelink)
6511
-		{
6512
-			$num = 0;
6513
-
6514
-			if (empty($possiblelink['enabled'])) continue;
6515
-
6516
-			if (! empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || ! in_array($key, $excludelinksto)))
6517
-			{
6518
-				print '<div id="'.$key.'list"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style="display:none"':'').'>';
6519
-				$sql = $possiblelink['sql'];
6520
-
6521
-				$resqllist = $this->db->query($sql);
6522
-				if ($resqllist)
6523
-				{
6524
-					$num = $this->db->num_rows($resqllist);
6525
-					$i = 0;
6526
-
6527
-					print '<br><form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
6528
-					print '<input type="hidden" name="id" value="'.$object->id.'">';
6529
-					print '<input type="hidden" name="action" value="addlink">';
6530
-					print '<input type="hidden" name="addlink" value="'.$key.'">';
6531
-					print '<table class="noborder">';
6532
-					print '<tr class="liste_titre">';
6533
-					print '<td class="nowrap"></td>';
6534
-					print '<td align="center">' . $langs->trans("Ref") . '</td>';
6535
-					print '<td align="left">' . $langs->trans("RefCustomer") . '</td>';
6536
-					print '<td align="right">' . $langs->trans("AmountHTShort") . '</td>';
6537
-					print '<td align="left">' . $langs->trans("Company") . '</td>';
6538
-					print '</tr>';
6539
-					while ($i < $num)
6540
-					{
6541
-						$objp = $this->db->fetch_object($resqllist);
6542
-
6543
-						print '<tr class="oddeven">';
6544
-						print '<td aling="left">';
6545
-						print '<input type="radio" name="idtolinkto" value=' . $objp->rowid . '>';
6546
-						print '</td>';
6547
-						print '<td align="center">' . $objp->ref . '</td>';
6548
-						print '<td>' . $objp->ref_client . '</td>';
6549
-						print '<td align="right">' . price($objp->total_ht) . '</td>';
6550
-						print '<td>' . $objp->name . '</td>';
6551
-						print '</tr>';
6552
-						$i++;
6553
-					}
6554
-					print '</table>';
6555
-					print '<div class="center"><input type="submit" class="button valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></div>';
6556
-
6557
-					print '</form>';
6558
-					$this->db->free($resqllist);
6559
-				} else {
6560
-					dol_print_error($this->db);
6561
-				}
6562
-				print '</div>';
6563
-				if ($num > 0)
6564
-				{
6565
-				}
6566
-
6567
-				//$linktoelem.=($linktoelem?' &nbsp; ':'');
6568
-				if ($num > 0) $linktoelemlist.='<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">' . $langs->trans($possiblelink['label']) .' ('.$num.')</a></li>';
6569
-				//else $linktoelem.=$langs->trans($possiblelink['label']);
6570
-				else $linktoelemlist.='<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
6571
-			}
6572
-		}
6573
-
6574
-		if ($linktoelemlist)
6575
-		{
6576
-			$linktoelem='
6510
+        foreach($possiblelinks as $key => $possiblelink)
6511
+        {
6512
+            $num = 0;
6513
+
6514
+            if (empty($possiblelink['enabled'])) continue;
6515
+
6516
+            if (! empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || ! in_array($key, $excludelinksto)))
6517
+            {
6518
+                print '<div id="'.$key.'list"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style="display:none"':'').'>';
6519
+                $sql = $possiblelink['sql'];
6520
+
6521
+                $resqllist = $this->db->query($sql);
6522
+                if ($resqllist)
6523
+                {
6524
+                    $num = $this->db->num_rows($resqllist);
6525
+                    $i = 0;
6526
+
6527
+                    print '<br><form action="'.$_SERVER["PHP_SELF"].'" method="POST" name="formlinked'.$key.'">';
6528
+                    print '<input type="hidden" name="id" value="'.$object->id.'">';
6529
+                    print '<input type="hidden" name="action" value="addlink">';
6530
+                    print '<input type="hidden" name="addlink" value="'.$key.'">';
6531
+                    print '<table class="noborder">';
6532
+                    print '<tr class="liste_titre">';
6533
+                    print '<td class="nowrap"></td>';
6534
+                    print '<td align="center">' . $langs->trans("Ref") . '</td>';
6535
+                    print '<td align="left">' . $langs->trans("RefCustomer") . '</td>';
6536
+                    print '<td align="right">' . $langs->trans("AmountHTShort") . '</td>';
6537
+                    print '<td align="left">' . $langs->trans("Company") . '</td>';
6538
+                    print '</tr>';
6539
+                    while ($i < $num)
6540
+                    {
6541
+                        $objp = $this->db->fetch_object($resqllist);
6542
+
6543
+                        print '<tr class="oddeven">';
6544
+                        print '<td aling="left">';
6545
+                        print '<input type="radio" name="idtolinkto" value=' . $objp->rowid . '>';
6546
+                        print '</td>';
6547
+                        print '<td align="center">' . $objp->ref . '</td>';
6548
+                        print '<td>' . $objp->ref_client . '</td>';
6549
+                        print '<td align="right">' . price($objp->total_ht) . '</td>';
6550
+                        print '<td>' . $objp->name . '</td>';
6551
+                        print '</tr>';
6552
+                        $i++;
6553
+                    }
6554
+                    print '</table>';
6555
+                    print '<div class="center"><input type="submit" class="button valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></div>';
6556
+
6557
+                    print '</form>';
6558
+                    $this->db->free($resqllist);
6559
+                } else {
6560
+                    dol_print_error($this->db);
6561
+                }
6562
+                print '</div>';
6563
+                if ($num > 0)
6564
+                {
6565
+                }
6566
+
6567
+                //$linktoelem.=($linktoelem?' &nbsp; ':'');
6568
+                if ($num > 0) $linktoelemlist.='<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">' . $langs->trans($possiblelink['label']) .' ('.$num.')</a></li>';
6569
+                //else $linktoelem.=$langs->trans($possiblelink['label']);
6570
+                else $linktoelemlist.='<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
6571
+            }
6572
+        }
6573
+
6574
+        if ($linktoelemlist)
6575
+        {
6576
+            $linktoelem='
6577 6577
     		<dl class="dropdown" id="linktoobjectname">
6578 6578
     		<dt><a href="#linktoobjectname">'.$langs->trans("LinkTo").'...</a></dt>
6579 6579
     		<dd>
@@ -6583,13 +6583,13 @@  discard block
 block discarded – undo
6583 6583
     		</div>
6584 6584
     		</dd>
6585 6585
     		</dl>';
6586
-		}
6587
-		else
6588
-		{
6589
-			$linktoelem='';
6590
-		}
6586
+        }
6587
+        else
6588
+        {
6589
+            $linktoelem='';
6590
+        }
6591 6591
 
6592
-		print '<!-- Add js to show linkto box -->
6592
+        print '<!-- Add js to show linkto box -->
6593 6593
 				<script type="text/javascript" language="javascript">
6594 6594
 				jQuery(document).ready(function() {
6595 6595
 					jQuery(".linkto").click(function() {
@@ -6601,584 +6601,584 @@  discard block
 block discarded – undo
6601 6601
 				</script>
6602 6602
 		';
6603 6603
 
6604
-		return $linktoelem;
6605
-	}
6606
-
6607
-	/**
6608
-	 *	Return an html string with a select combo box to choose yes or no
6609
-	 *
6610
-	 *	@param	string		$htmlname		Name of html select field
6611
-	 *	@param	string		$value			Pre-selected value
6612
-	 *	@param	int			$option			0 return yes/no, 1 return 1/0
6613
-	 *	@param	bool		$disabled		true or false
6614
-	 *  @param	int      	$useempty		1=Add empty line
6615
-	 *	@return	string						See option
6616
-	 */
6617
-	function selectyesno($htmlname, $value='', $option=0, $disabled=false, $useempty=0)
6618
-	{
6619
-		global $langs;
6620
-
6621
-		$yes="yes"; $no="no";
6622
-		if ($option)
6623
-		{
6624
-			$yes="1";
6625
-			$no="0";
6626
-		}
6627
-
6628
-		$disabled = ($disabled ? ' disabled' : '');
6629
-
6630
-		$resultyesno = '<select class="flat width75" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
6631
-		if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0)?' selected':'').'>&nbsp;</option>'."\n";
6632
-		if (("$value" == 'yes') || ($value == 1))
6633
-		{
6634
-			$resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
6635
-			$resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
6636
-		}
6637
-		else
6638
-	   {
6639
-	   		$selected=(($useempty && $value != '0' && $value != 'no')?'':' selected');
6640
-			$resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
6641
-			$resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
6642
-		}
6643
-		$resultyesno .= '</select>'."\n";
6644
-		return $resultyesno;
6645
-	}
6604
+        return $linktoelem;
6605
+    }
6606
+
6607
+    /**
6608
+     *	Return an html string with a select combo box to choose yes or no
6609
+     *
6610
+     *	@param	string		$htmlname		Name of html select field
6611
+     *	@param	string		$value			Pre-selected value
6612
+     *	@param	int			$option			0 return yes/no, 1 return 1/0
6613
+     *	@param	bool		$disabled		true or false
6614
+     *  @param	int      	$useempty		1=Add empty line
6615
+     *	@return	string						See option
6616
+     */
6617
+    function selectyesno($htmlname, $value='', $option=0, $disabled=false, $useempty=0)
6618
+    {
6619
+        global $langs;
6620
+
6621
+        $yes="yes"; $no="no";
6622
+        if ($option)
6623
+        {
6624
+            $yes="1";
6625
+            $no="0";
6626
+        }
6627
+
6628
+        $disabled = ($disabled ? ' disabled' : '');
6629
+
6630
+        $resultyesno = '<select class="flat width75" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
6631
+        if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0)?' selected':'').'>&nbsp;</option>'."\n";
6632
+        if (("$value" == 'yes') || ($value == 1))
6633
+        {
6634
+            $resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
6635
+            $resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
6636
+        }
6637
+        else
6638
+        {
6639
+                $selected=(($useempty && $value != '0' && $value != 'no')?'':' selected');
6640
+            $resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
6641
+            $resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
6642
+        }
6643
+        $resultyesno .= '</select>'."\n";
6644
+        return $resultyesno;
6645
+    }
6646 6646
 
6647 6647
 
6648 6648
 
6649 6649
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
6650
-	/**
6651
-	 *  Return list of export templates
6652
-	 *
6653
-	 *  @param	string	$selected          Id modele pre-selectionne
6654
-	 *  @param  string	$htmlname          Name of HTML select
6655
-	 *  @param  string	$type              Type of searched templates
6656
-	 *  @param  int		$useempty          Affiche valeur vide dans liste
6657
-	 *  @return	void
6658
-	 */
6659
-	function select_export_model($selected='',$htmlname='exportmodelid',$type='',$useempty=0)
6660
-	{
6650
+    /**
6651
+     *  Return list of export templates
6652
+     *
6653
+     *  @param	string	$selected          Id modele pre-selectionne
6654
+     *  @param  string	$htmlname          Name of HTML select
6655
+     *  @param  string	$type              Type of searched templates
6656
+     *  @param  int		$useempty          Affiche valeur vide dans liste
6657
+     *  @return	void
6658
+     */
6659
+    function select_export_model($selected='',$htmlname='exportmodelid',$type='',$useempty=0)
6660
+    {
6661 6661
         // phpcs:enable
6662
-		$sql = "SELECT rowid, label";
6663
-		$sql.= " FROM ".MAIN_DB_PREFIX."export_model";
6664
-		$sql.= " WHERE type = '".$type."'";
6665
-		$sql.= " ORDER BY rowid";
6666
-		$result = $this->db->query($sql);
6667
-		if ($result)
6668
-		{
6669
-			print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
6670
-			if ($useempty)
6671
-			{
6672
-				print '<option value="-1">&nbsp;</option>';
6673
-			}
6674
-
6675
-			$num = $this->db->num_rows($result);
6676
-			$i = 0;
6677
-			while ($i < $num)
6678
-			{
6679
-				$obj = $this->db->fetch_object($result);
6680
-				if ($selected == $obj->rowid)
6681
-				{
6682
-					print '<option value="'.$obj->rowid.'" selected>';
6683
-				}
6684
-				else
6685
-				{
6686
-					print '<option value="'.$obj->rowid.'">';
6687
-				}
6688
-				print $obj->label;
6689
-				print '</option>';
6690
-				$i++;
6691
-			}
6692
-			print "</select>";
6693
-		}
6694
-		else {
6695
-			dol_print_error($this->db);
6696
-		}
6697
-	}
6698
-
6699
-	/**
6700
-	 *    Return a HTML area with the reference of object and a navigation bar for a business object
6701
-	 *    Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
6702
-	 *
6703
-	 *    @param	object	$object			Object to show.
6704
-	 *    @param	string	$paramid   		Name of parameter to use to name the id into the URL next/previous link.
6705
-	 *    @param	string	$morehtml  		More html content to output just before the nav bar.
6706
-	 *    @param	int		$shownav	  	Show Condition (navigation is shown if value is 1).
6707
-	 *    @param	string	$fieldid   		Name of field id into database to use for select next and previous (we make the select max and min on this field compared to $object->ref). Use 'none' to disable next/prev.
6708
-	 *    @param	string	$fieldref   	Name of field ref of object (object->ref) to show or 'none' to not show ref.
6709
-	 *    @param	string	$morehtmlref  	More html to show after ref.
6710
-	 *    @param	string	$moreparam  	More param to add in nav link url. Must start with '&...'.
6711
-	 *	  @param	int		$nodbprefix		Do not include DB prefix to forge table name.
6712
-	 *	  @param	string	$morehtmlleft	More html code to show before ref.
6713
-	 *	  @param	string	$morehtmlstatus	More html code to show under navigation arrows (status place).
6714
-	 *	  @param	string	$morehtmlright	More html code to show after ref.
6715
-	 * 	  @return	string    				Portion HTML with ref + navigation buttons
6716
-	 */
6717
-	function showrefnav($object,$paramid,$morehtml='',$shownav=1,$fieldid='rowid',$fieldref='ref',$morehtmlref='',$moreparam='',$nodbprefix=0,$morehtmlleft='',$morehtmlstatus='',$morehtmlright='')
6718
-	{
6719
-		global $langs,$conf,$hookmanager;
6720
-
6721
-		$ret='';
6722
-		if (empty($fieldid))  $fieldid='rowid';
6723
-		if (empty($fieldref)) $fieldref='ref';
6724
-
6725
-		// Add where from hooks
6726
-		if (is_object($hookmanager))
6727
-		{
6728
-			$parameters=array();
6729
-			$reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters, $object);    // Note that $action and $object may have been modified by hook
6730
-			$object->next_prev_filter.=$hookmanager->resPrint;
6731
-		}
6732
-		$previous_ref = $next_ref = '';
6733
-		if ($shownav)
6734
-		{
6735
-			//print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
6736
-			$object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''), $fieldid, $nodbprefix);
6737
-
6738
-			$navurl = $_SERVER["PHP_SELF"];
6739
-			// Special case for project/task page
6740
-			if ($paramid == 'project_ref')
6741
-			{
6742
-				$navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/','/tasks.php',$navurl);
6743
-				$paramid='ref';
6744
-			}
6745
-
6746
-			// accesskey is for Windows or Linux:  ALT + key for chrome, ALT + SHIFT + KEY for firefox
6747
-			// accesskey is for Mac:               CTRL + key for all browsers
6748
-			$stringforfirstkey = $langs->trans("KeyboardShortcut");
6749
-			if ($conf->browser->name == 'chrome')
6750
-			{
6751
-				$stringforfirstkey .= ' ALT +';
6752
-			}
6753
-			elseif ($conf->browser->name == 'firefox')
6754
-			{
6755
-				$stringforfirstkey .= ' ALT + SHIFT +';
6756
-			}
6757
-			else
6758
-			{
6759
-				$stringforfirstkey .= ' CTL +';
6760
-			}
6761
-
6762
-			$previous_ref = $object->ref_previous?'<a accesskey="p" title="'.$stringforfirstkey.' p" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'"><i class="fa fa-chevron-left"></i></a>':'<span class="inactive"><i class="fa fa-chevron-left opacitymedium"></i></span>';
6763
-			$next_ref     = $object->ref_next?'<a accesskey="n" title="'.$stringforfirstkey.' n" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'"><i class="fa fa-chevron-right"></i></a>':'<span class="inactive"><i class="fa fa-chevron-right opacitymedium"></i></span>';
6764
-		}
6765
-
6766
-		//print "xx".$previous_ref."x".$next_ref;
6767
-		$ret.='<!-- Start banner content --><div style="vertical-align: middle">';
6768
-
6769
-		// Right part of banner
6770
-		if ($morehtmlright) $ret.='<div class="inline-block floatleft">'.$morehtmlright.'</div>';
6771
-
6772
-		if ($previous_ref || $next_ref || $morehtml)
6773
-		{
6774
-			$ret.='<div class="pagination paginationref"><ul class="right">';
6775
-		}
6776
-		if ($morehtml)
6777
-		{
6778
-			$ret.='<li class="noborder litext">'.$morehtml.'</li>';
6779
-		}
6780
-		if ($shownav && ($previous_ref || $next_ref))
6781
-		{
6782
-			$ret.='<li class="pagination">'.$previous_ref.'</li>';
6783
-			$ret.='<li class="pagination">'.$next_ref.'</li>';
6784
-		}
6785
-		if ($previous_ref || $next_ref || $morehtml)
6786
-		{
6787
-			$ret.='</ul></div>';
6788
-		}
6789
-
6790
-		$parameters=array();
6791
-		$reshook=$hookmanager->executeHooks('moreHtmlStatus',$parameters, $object);    // Note that $action and $object may have been modified by hook
6792
-		if (empty($reshook)) $morehtmlstatus.=$hookmanager->resPrint;
6793
-		else $morehtmlstatus=$hookmanager->resPrint;
6794
-		if ($morehtmlstatus) $ret.='<div class="statusref">'.$morehtmlstatus.'</div>';
6795
-
6796
-		$parameters = array();
6797
-		$reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
6798
-		if (empty($reshook)) $morehtmlref.=$hookmanager->resPrint;
6799
-		elseif ($reshook > 0) $morehtmlref=$hookmanager->resPrint;
6800
-
6801
-		// Left part of banner
6802
-		if ($morehtmlleft)
6803
-		{
6804
-			if ($conf->browser->layout == 'phone') $ret.='<div class="floatleft">'.$morehtmlleft.'</div>';    // class="center" to have photo in middle
6805
-			else $ret.='<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
6806
-		}
6807
-
6808
-		//if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
6809
-		$ret.='<div class="inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref))?' refidpadding':'').'">';
6810
-
6811
-		// For thirdparty, contact, user, member, the ref is the id, so we show something else
6812
-		if ($object->element == 'societe')
6813
-		{
6814
-			$ret.=dol_htmlentities($object->name);
6815
-		}
6816
-		else if ($object->element == 'member')
6817
-		{
6818
-			$ret.=$object->ref.'<br>';
6819
-			$fullname=$object->getFullName($langs);
6820
-			if ($object->morphy == 'mor' && $object->societe) {
6821
-				$ret.= dol_htmlentities($object->societe) . ((! empty($fullname) && $object->societe != $fullname)?' ('.dol_htmlentities($fullname).')':'');
6822
-			} else {
6823
-				$ret.= dol_htmlentities($fullname) . ((! empty($object->societe) && $object->societe != $fullname)?' ('.dol_htmlentities($object->societe).')':'');
6824
-			}
6825
-		}
6826
-		else if (in_array($object->element, array('contact', 'user', 'usergroup')))
6827
-		{
6828
-			$ret.=dol_htmlentities($object->getFullName($langs));
6829
-		}
6830
-		else if (in_array($object->element, array('action', 'agenda')))
6831
-		{
6832
-			$ret.=$object->ref.'<br>'.$object->label;
6833
-		}
6834
-		else if (in_array($object->element, array('adherent_type')))
6835
-		{
6836
-			$ret.=$object->label;
6837
-		}
6838
-		else if ($object->element == 'ecm_directories')
6839
-		{
6840
-			$ret.='';
6841
-		}
6842
-		else if ($fieldref != 'none') $ret.=dol_htmlentities($object->$fieldref);
6843
-
6844
-
6845
-		if ($morehtmlref)
6846
-		{
6847
-			$ret.=' '.$morehtmlref;
6848
-		}
6849
-		$ret.='</div>';
6850
-
6851
-		$ret.='</div><!-- End banner content -->';
6852
-
6853
-		return $ret;
6854
-	}
6855
-
6856
-
6857
-	/**
6858
-	 *    	Return HTML code to output a barcode
6859
-	 *
6860
-	 *     	@param	Object	$object		Object containing data to retrieve file name
6861
-	 * 		@param	int		$width			Width of photo
6862
-	 * 	  	@return string    				HTML code to output barcode
6863
-	 */
6864
-	function showbarcode(&$object,$width=100)
6865
-	{
6866
-		global $conf;
6867
-
6868
-		//Check if barcode is filled in the card
6869
-		if (empty($object->barcode)) return '';
6870
-
6871
-		// Complete object if not complete
6872
-		if (empty($object->barcode_type_code) || empty($object->barcode_type_coder))
6873
-		{
6874
-			$result = $object->fetch_barcode();
6875
-			//Check if fetch_barcode() failed
6876
-			if ($result < 1) return '<!-- ErrorFetchBarcode -->';
6877
-		}
6878
-
6879
-		// Barcode image
6880
-		$url=DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
6881
-		$out ='<!-- url barcode = '.$url.' -->';
6882
-		$out.='<img src="'.$url.'">';
6883
-		return $out;
6884
-	}
6885
-
6886
-	/**
6887
-	 *    	Return HTML code to output a photo
6888
-	 *
6889
-	 *    	@param	string		$modulepart			Key to define module concerned ('societe', 'userphoto', 'memberphoto')
6890
-	 *     	@param  object		$object				Object containing data to retrieve file name
6891
-	 * 		@param	int			$width				Width of photo
6892
-	 * 		@param	int			$height				Height of photo (auto if 0)
6893
-	 * 		@param	int			$caneditfield		Add edit fields
6894
-	 * 		@param	string		$cssclass			CSS name to use on img for photo
6895
-	 * 		@param	string		$imagesize		    'mini', 'small' or '' (original)
6896
-	 *      @param  int         $addlinktofullsize  Add link to fullsize image
6897
-	 *      @param  int         $cache              1=Accept to use image in cache
6898
-	 *      @param	string		$forcecapture		Force parameter capture on HTML input file element to ask a smartphone to allow to open camera to take photo. Auto if empty.
6899
-	 * 	  	@return string    						HTML code to output photo
6900
-	 */
6901
-	static function showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='')
6902
-	{
6903
-		global $conf,$langs;
6904
-
6905
-		$entity = (! empty($object->entity) ? $object->entity : $conf->entity);
6906
-		$id = (! empty($object->id) ? $object->id : $object->rowid);
6907
-
6908
-		$ret='';$dir='';$file='';$originalfile='';$altfile='';$email='';$capture='';
6909
-		if ($modulepart=='societe')
6910
-		{
6911
-			$dir=$conf->societe->multidir_output[$entity];
6912
-			if (! empty($object->logo))
6913
-			{
6914
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini');             // getImageFileNameForSize include the thumbs
6915
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
6916
-				else $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6917
-				$originalfile=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6918
-			}
6919
-			$email=$object->email;
6920
-		}
6921
-		else if ($modulepart=='contact')
6922
-		{
6923
-			$dir=$conf->societe->multidir_output[$entity].'/contact';
6924
-			if (! empty($object->photo))
6925
-			{
6926
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
6927
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
6928
-				else $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6929
-				$originalfile=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6930
-			}
6931
-			$email=$object->email;
6932
-			$capture='user';
6933
-		}
6934
-		else if ($modulepart=='userphoto')
6935
-		{
6936
-			$dir=$conf->user->dir_output;
6937
-			if (! empty($object->photo))
6938
-			{
6939
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_mini');
6940
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_small');
6941
-				else $file=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6942
-				$originalfile=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6943
-			}
6944
-			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6945
-			$email=$object->email;
6946
-			$capture='user';
6947
-		}
6948
-		else if ($modulepart=='memberphoto')
6949
-		{
6950
-			$dir=$conf->adherent->dir_output;
6951
-			if (! empty($object->photo))
6952
-			{
6953
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
6954
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
6955
-				else $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6956
-				$originalfile=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6957
-			}
6958
-			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6959
-			$email=$object->email;
6960
-			$capture='user';
6961
-		}
6962
-		else
6963
-		{
6964
-			// Generic case to show photos
6965
-			$dir=$conf->$modulepart->dir_output;
6966
-			if (! empty($object->photo))
6967
-			{
6968
-				if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
6969
-				else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
6970
-				else $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6971
-				$originalfile=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6972
-			}
6973
-			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6974
-			$email=$object->email;
6975
-		}
6976
-
6977
-		if ($forcecapture) $capture = $forcecapture;
6978
-
6979
-		if ($dir)
6980
-		{
6981
-			if ($file && file_exists($dir."/".$file))
6982
-			{
6983
-				if ($addlinktofullsize)
6984
-				{
6985
-					$urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6986
-					if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
6987
-					else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
6988
-				}
6989
-				$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($file).'&cache='.$cache.'">';
6990
-				if ($addlinktofullsize) $ret.='</a>';
6991
-			}
6992
-			else if ($altfile && file_exists($dir."/".$altfile))
6993
-			{
6994
-				if ($addlinktofullsize)
6995
-				{
6996
-					$urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6997
-					if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
6998
-					else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
6999
-				}
7000
-				$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo alt" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" class="'.$cssclass.'" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($altfile).'&cache='.$cache.'">';
7001
-				if ($addlinktofullsize) $ret.='</a>';
7002
-			}
7003
-			else
7004
-			{
7005
-				$nophoto='/public/theme/common/nophoto.png';
7006
-				if (in_array($modulepart,array('userphoto','contact')))	// For module that are "physical" users
7007
-				{
7008
-					$nophoto='/public/theme/common/user_anonymous.png';
7009
-					if ($object->gender == 'man') $nophoto='/public/theme/common/user_man.png';
7010
-					if ($object->gender == 'woman') $nophoto='/public/theme/common/user_woman.png';
7011
-				}
7012
-
7013
-				if (! empty($conf->gravatar->enabled) && $email)
7014
-				{
7015
-					/**
7016
-					 * @see https://gravatar.com/site/implement/images/php/
7017
-					 */
7018
-					global $dolibarr_main_url_root;
7019
-					$ret.='<!-- Put link to gravatar -->';
7020
-					//$defaultimg=urlencode(dol_buildpath($nophoto,3));
7021
-					$defaultimg='mm';
7022
-					$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Gravatar avatar" title="'.$email.' Gravatar avatar" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="https://www.gravatar.com/avatar/'.dol_hash(strtolower(trim($email)),3).'?s='.$width.'&d='.$defaultimg.'">';	// gravatar need md5 hash
7023
-				}
7024
-				else
7025
-				{
7026
-					$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'">';
7027
-				}
7028
-			}
7029
-
7030
-			if ($caneditfield)
7031
-			{
7032
-				if ($object->photo) $ret.="<br>\n";
7033
-				$ret.='<table class="nobordernopadding centpercent">';
7034
-				if ($object->photo) $ret.='<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
7035
-				$ret.='<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput"'.($capture?' capture="'.$capture.'"':'').'></td></tr>';
7036
-				$ret.='</table>';
7037
-			}
7038
-		}
7039
-		else dol_print_error('','Call of showphoto with wrong parameters modulepart='.$modulepart);
7040
-
7041
-		return $ret;
7042
-	}
6662
+        $sql = "SELECT rowid, label";
6663
+        $sql.= " FROM ".MAIN_DB_PREFIX."export_model";
6664
+        $sql.= " WHERE type = '".$type."'";
6665
+        $sql.= " ORDER BY rowid";
6666
+        $result = $this->db->query($sql);
6667
+        if ($result)
6668
+        {
6669
+            print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
6670
+            if ($useempty)
6671
+            {
6672
+                print '<option value="-1">&nbsp;</option>';
6673
+            }
6674
+
6675
+            $num = $this->db->num_rows($result);
6676
+            $i = 0;
6677
+            while ($i < $num)
6678
+            {
6679
+                $obj = $this->db->fetch_object($result);
6680
+                if ($selected == $obj->rowid)
6681
+                {
6682
+                    print '<option value="'.$obj->rowid.'" selected>';
6683
+                }
6684
+                else
6685
+                {
6686
+                    print '<option value="'.$obj->rowid.'">';
6687
+                }
6688
+                print $obj->label;
6689
+                print '</option>';
6690
+                $i++;
6691
+            }
6692
+            print "</select>";
6693
+        }
6694
+        else {
6695
+            dol_print_error($this->db);
6696
+        }
6697
+    }
6698
+
6699
+    /**
6700
+     *    Return a HTML area with the reference of object and a navigation bar for a business object
6701
+     *    Note: To complete search with a particular filter on select, you can set $object->next_prev_filter set to define SQL criterias.
6702
+     *
6703
+     *    @param	object	$object			Object to show.
6704
+     *    @param	string	$paramid   		Name of parameter to use to name the id into the URL next/previous link.
6705
+     *    @param	string	$morehtml  		More html content to output just before the nav bar.
6706
+     *    @param	int		$shownav	  	Show Condition (navigation is shown if value is 1).
6707
+     *    @param	string	$fieldid   		Name of field id into database to use for select next and previous (we make the select max and min on this field compared to $object->ref). Use 'none' to disable next/prev.
6708
+     *    @param	string	$fieldref   	Name of field ref of object (object->ref) to show or 'none' to not show ref.
6709
+     *    @param	string	$morehtmlref  	More html to show after ref.
6710
+     *    @param	string	$moreparam  	More param to add in nav link url. Must start with '&...'.
6711
+     *	  @param	int		$nodbprefix		Do not include DB prefix to forge table name.
6712
+     *	  @param	string	$morehtmlleft	More html code to show before ref.
6713
+     *	  @param	string	$morehtmlstatus	More html code to show under navigation arrows (status place).
6714
+     *	  @param	string	$morehtmlright	More html code to show after ref.
6715
+     * 	  @return	string    				Portion HTML with ref + navigation buttons
6716
+     */
6717
+    function showrefnav($object,$paramid,$morehtml='',$shownav=1,$fieldid='rowid',$fieldref='ref',$morehtmlref='',$moreparam='',$nodbprefix=0,$morehtmlleft='',$morehtmlstatus='',$morehtmlright='')
6718
+    {
6719
+        global $langs,$conf,$hookmanager;
6720
+
6721
+        $ret='';
6722
+        if (empty($fieldid))  $fieldid='rowid';
6723
+        if (empty($fieldref)) $fieldref='ref';
6724
+
6725
+        // Add where from hooks
6726
+        if (is_object($hookmanager))
6727
+        {
6728
+            $parameters=array();
6729
+            $reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters, $object);    // Note that $action and $object may have been modified by hook
6730
+            $object->next_prev_filter.=$hookmanager->resPrint;
6731
+        }
6732
+        $previous_ref = $next_ref = '';
6733
+        if ($shownav)
6734
+        {
6735
+            //print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
6736
+            $object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''), $fieldid, $nodbprefix);
6737
+
6738
+            $navurl = $_SERVER["PHP_SELF"];
6739
+            // Special case for project/task page
6740
+            if ($paramid == 'project_ref')
6741
+            {
6742
+                $navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/','/tasks.php',$navurl);
6743
+                $paramid='ref';
6744
+            }
6745
+
6746
+            // accesskey is for Windows or Linux:  ALT + key for chrome, ALT + SHIFT + KEY for firefox
6747
+            // accesskey is for Mac:               CTRL + key for all browsers
6748
+            $stringforfirstkey = $langs->trans("KeyboardShortcut");
6749
+            if ($conf->browser->name == 'chrome')
6750
+            {
6751
+                $stringforfirstkey .= ' ALT +';
6752
+            }
6753
+            elseif ($conf->browser->name == 'firefox')
6754
+            {
6755
+                $stringforfirstkey .= ' ALT + SHIFT +';
6756
+            }
6757
+            else
6758
+            {
6759
+                $stringforfirstkey .= ' CTL +';
6760
+            }
6761
+
6762
+            $previous_ref = $object->ref_previous?'<a accesskey="p" title="'.$stringforfirstkey.' p" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'"><i class="fa fa-chevron-left"></i></a>':'<span class="inactive"><i class="fa fa-chevron-left opacitymedium"></i></span>';
6763
+            $next_ref     = $object->ref_next?'<a accesskey="n" title="'.$stringforfirstkey.' n" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'"><i class="fa fa-chevron-right"></i></a>':'<span class="inactive"><i class="fa fa-chevron-right opacitymedium"></i></span>';
6764
+        }
6765
+
6766
+        //print "xx".$previous_ref."x".$next_ref;
6767
+        $ret.='<!-- Start banner content --><div style="vertical-align: middle">';
6768
+
6769
+        // Right part of banner
6770
+        if ($morehtmlright) $ret.='<div class="inline-block floatleft">'.$morehtmlright.'</div>';
6771
+
6772
+        if ($previous_ref || $next_ref || $morehtml)
6773
+        {
6774
+            $ret.='<div class="pagination paginationref"><ul class="right">';
6775
+        }
6776
+        if ($morehtml)
6777
+        {
6778
+            $ret.='<li class="noborder litext">'.$morehtml.'</li>';
6779
+        }
6780
+        if ($shownav && ($previous_ref || $next_ref))
6781
+        {
6782
+            $ret.='<li class="pagination">'.$previous_ref.'</li>';
6783
+            $ret.='<li class="pagination">'.$next_ref.'</li>';
6784
+        }
6785
+        if ($previous_ref || $next_ref || $morehtml)
6786
+        {
6787
+            $ret.='</ul></div>';
6788
+        }
6789
+
6790
+        $parameters=array();
6791
+        $reshook=$hookmanager->executeHooks('moreHtmlStatus',$parameters, $object);    // Note that $action and $object may have been modified by hook
6792
+        if (empty($reshook)) $morehtmlstatus.=$hookmanager->resPrint;
6793
+        else $morehtmlstatus=$hookmanager->resPrint;
6794
+        if ($morehtmlstatus) $ret.='<div class="statusref">'.$morehtmlstatus.'</div>';
6795
+
6796
+        $parameters = array();
6797
+        $reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
6798
+        if (empty($reshook)) $morehtmlref.=$hookmanager->resPrint;
6799
+        elseif ($reshook > 0) $morehtmlref=$hookmanager->resPrint;
6800
+
6801
+        // Left part of banner
6802
+        if ($morehtmlleft)
6803
+        {
6804
+            if ($conf->browser->layout == 'phone') $ret.='<div class="floatleft">'.$morehtmlleft.'</div>';    // class="center" to have photo in middle
6805
+            else $ret.='<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
6806
+        }
6807
+
6808
+        //if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
6809
+        $ret.='<div class="inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref))?' refidpadding':'').'">';
6810
+
6811
+        // For thirdparty, contact, user, member, the ref is the id, so we show something else
6812
+        if ($object->element == 'societe')
6813
+        {
6814
+            $ret.=dol_htmlentities($object->name);
6815
+        }
6816
+        else if ($object->element == 'member')
6817
+        {
6818
+            $ret.=$object->ref.'<br>';
6819
+            $fullname=$object->getFullName($langs);
6820
+            if ($object->morphy == 'mor' && $object->societe) {
6821
+                $ret.= dol_htmlentities($object->societe) . ((! empty($fullname) && $object->societe != $fullname)?' ('.dol_htmlentities($fullname).')':'');
6822
+            } else {
6823
+                $ret.= dol_htmlentities($fullname) . ((! empty($object->societe) && $object->societe != $fullname)?' ('.dol_htmlentities($object->societe).')':'');
6824
+            }
6825
+        }
6826
+        else if (in_array($object->element, array('contact', 'user', 'usergroup')))
6827
+        {
6828
+            $ret.=dol_htmlentities($object->getFullName($langs));
6829
+        }
6830
+        else if (in_array($object->element, array('action', 'agenda')))
6831
+        {
6832
+            $ret.=$object->ref.'<br>'.$object->label;
6833
+        }
6834
+        else if (in_array($object->element, array('adherent_type')))
6835
+        {
6836
+            $ret.=$object->label;
6837
+        }
6838
+        else if ($object->element == 'ecm_directories')
6839
+        {
6840
+            $ret.='';
6841
+        }
6842
+        else if ($fieldref != 'none') $ret.=dol_htmlentities($object->$fieldref);
6843
+
6844
+
6845
+        if ($morehtmlref)
6846
+        {
6847
+            $ret.=' '.$morehtmlref;
6848
+        }
6849
+        $ret.='</div>';
6850
+
6851
+        $ret.='</div><!-- End banner content -->';
6852
+
6853
+        return $ret;
6854
+    }
6855
+
6856
+
6857
+    /**
6858
+     *    	Return HTML code to output a barcode
6859
+     *
6860
+     *     	@param	Object	$object		Object containing data to retrieve file name
6861
+     * 		@param	int		$width			Width of photo
6862
+     * 	  	@return string    				HTML code to output barcode
6863
+     */
6864
+    function showbarcode(&$object,$width=100)
6865
+    {
6866
+        global $conf;
6867
+
6868
+        //Check if barcode is filled in the card
6869
+        if (empty($object->barcode)) return '';
6870
+
6871
+        // Complete object if not complete
6872
+        if (empty($object->barcode_type_code) || empty($object->barcode_type_coder))
6873
+        {
6874
+            $result = $object->fetch_barcode();
6875
+            //Check if fetch_barcode() failed
6876
+            if ($result < 1) return '<!-- ErrorFetchBarcode -->';
6877
+        }
6878
+
6879
+        // Barcode image
6880
+        $url=DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
6881
+        $out ='<!-- url barcode = '.$url.' -->';
6882
+        $out.='<img src="'.$url.'">';
6883
+        return $out;
6884
+    }
6885
+
6886
+    /**
6887
+     *    	Return HTML code to output a photo
6888
+     *
6889
+     *    	@param	string		$modulepart			Key to define module concerned ('societe', 'userphoto', 'memberphoto')
6890
+     *     	@param  object		$object				Object containing data to retrieve file name
6891
+     * 		@param	int			$width				Width of photo
6892
+     * 		@param	int			$height				Height of photo (auto if 0)
6893
+     * 		@param	int			$caneditfield		Add edit fields
6894
+     * 		@param	string		$cssclass			CSS name to use on img for photo
6895
+     * 		@param	string		$imagesize		    'mini', 'small' or '' (original)
6896
+     *      @param  int         $addlinktofullsize  Add link to fullsize image
6897
+     *      @param  int         $cache              1=Accept to use image in cache
6898
+     *      @param	string		$forcecapture		Force parameter capture on HTML input file element to ask a smartphone to allow to open camera to take photo. Auto if empty.
6899
+     * 	  	@return string    						HTML code to output photo
6900
+     */
6901
+    static function showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='')
6902
+    {
6903
+        global $conf,$langs;
6904
+
6905
+        $entity = (! empty($object->entity) ? $object->entity : $conf->entity);
6906
+        $id = (! empty($object->id) ? $object->id : $object->rowid);
6907
+
6908
+        $ret='';$dir='';$file='';$originalfile='';$altfile='';$email='';$capture='';
6909
+        if ($modulepart=='societe')
6910
+        {
6911
+            $dir=$conf->societe->multidir_output[$entity];
6912
+            if (! empty($object->logo))
6913
+            {
6914
+                if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini');             // getImageFileNameForSize include the thumbs
6915
+                else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
6916
+                else $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6917
+                $originalfile=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6918
+            }
6919
+            $email=$object->email;
6920
+        }
6921
+        else if ($modulepart=='contact')
6922
+        {
6923
+            $dir=$conf->societe->multidir_output[$entity].'/contact';
6924
+            if (! empty($object->photo))
6925
+            {
6926
+                if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
6927
+                else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
6928
+                else $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6929
+                $originalfile=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6930
+            }
6931
+            $email=$object->email;
6932
+            $capture='user';
6933
+        }
6934
+        else if ($modulepart=='userphoto')
6935
+        {
6936
+            $dir=$conf->user->dir_output;
6937
+            if (! empty($object->photo))
6938
+            {
6939
+                if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_mini');
6940
+                else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_small');
6941
+                else $file=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6942
+                $originalfile=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6943
+            }
6944
+            if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6945
+            $email=$object->email;
6946
+            $capture='user';
6947
+        }
6948
+        else if ($modulepart=='memberphoto')
6949
+        {
6950
+            $dir=$conf->adherent->dir_output;
6951
+            if (! empty($object->photo))
6952
+            {
6953
+                if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
6954
+                else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
6955
+                else $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6956
+                $originalfile=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6957
+            }
6958
+            if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6959
+            $email=$object->email;
6960
+            $capture='user';
6961
+        }
6962
+        else
6963
+        {
6964
+            // Generic case to show photos
6965
+            $dir=$conf->$modulepart->dir_output;
6966
+            if (! empty($object->photo))
6967
+            {
6968
+                if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
6969
+                else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
6970
+                else $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6971
+                $originalfile=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6972
+            }
6973
+            if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6974
+            $email=$object->email;
6975
+        }
6976
+
6977
+        if ($forcecapture) $capture = $forcecapture;
6978
+
6979
+        if ($dir)
6980
+        {
6981
+            if ($file && file_exists($dir."/".$file))
6982
+            {
6983
+                if ($addlinktofullsize)
6984
+                {
6985
+                    $urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6986
+                    if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
6987
+                    else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
6988
+                }
6989
+                $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($file).'&cache='.$cache.'">';
6990
+                if ($addlinktofullsize) $ret.='</a>';
6991
+            }
6992
+            else if ($altfile && file_exists($dir."/".$altfile))
6993
+            {
6994
+                if ($addlinktofullsize)
6995
+                {
6996
+                    $urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6997
+                    if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
6998
+                    else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
6999
+                }
7000
+                $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo alt" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" class="'.$cssclass.'" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($altfile).'&cache='.$cache.'">';
7001
+                if ($addlinktofullsize) $ret.='</a>';
7002
+            }
7003
+            else
7004
+            {
7005
+                $nophoto='/public/theme/common/nophoto.png';
7006
+                if (in_array($modulepart,array('userphoto','contact')))	// For module that are "physical" users
7007
+                {
7008
+                    $nophoto='/public/theme/common/user_anonymous.png';
7009
+                    if ($object->gender == 'man') $nophoto='/public/theme/common/user_man.png';
7010
+                    if ($object->gender == 'woman') $nophoto='/public/theme/common/user_woman.png';
7011
+                }
7012
+
7013
+                if (! empty($conf->gravatar->enabled) && $email)
7014
+                {
7015
+                    /**
7016
+                     * @see https://gravatar.com/site/implement/images/php/
7017
+                     */
7018
+                    global $dolibarr_main_url_root;
7019
+                    $ret.='<!-- Put link to gravatar -->';
7020
+                    //$defaultimg=urlencode(dol_buildpath($nophoto,3));
7021
+                    $defaultimg='mm';
7022
+                    $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Gravatar avatar" title="'.$email.' Gravatar avatar" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="https://www.gravatar.com/avatar/'.dol_hash(strtolower(trim($email)),3).'?s='.$width.'&d='.$defaultimg.'">';	// gravatar need md5 hash
7023
+                }
7024
+                else
7025
+                {
7026
+                    $ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'">';
7027
+                }
7028
+            }
7029
+
7030
+            if ($caneditfield)
7031
+            {
7032
+                if ($object->photo) $ret.="<br>\n";
7033
+                $ret.='<table class="nobordernopadding centpercent">';
7034
+                if ($object->photo) $ret.='<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
7035
+                $ret.='<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput"'.($capture?' capture="'.$capture.'"':'').'></td></tr>';
7036
+                $ret.='</table>';
7037
+            }
7038
+        }
7039
+        else dol_print_error('','Call of showphoto with wrong parameters modulepart='.$modulepart);
7040
+
7041
+        return $ret;
7042
+    }
7043 7043
 
7044 7044
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
7045
-	/**
7046
-	 *	Return select list of groups
7047
-	 *
7048
-	 *  @param	string	$selected       Id group preselected
7049
-	 *  @param  string	$htmlname       Field name in form
7050
-	 *  @param  int		$show_empty     0=liste sans valeur nulle, 1=ajoute valeur inconnue
7051
-	 *  @param  string	$exclude        Array list of groups id to exclude
7052
-	 * 	@param	int		$disabled		If select list must be disabled
7053
-	 *  @param  string	$include        Array list of groups id to include
7054
-	 * 	@param	int		$enableonly		Array list of groups id to be enabled. All other must be disabled
7055
-	 * 	@param	string	$force_entity	'0' or Ids of environment to force
7056
-	 * 	@param	bool	$multiple		add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
7057
-	 *  @return	string
7058
-	 *  @see select_dolusers
7059
-	 */
7060
-	function select_dolgroups($selected='', $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity='0', $multiple=false)
7061
-	{
7045
+    /**
7046
+     *	Return select list of groups
7047
+     *
7048
+     *  @param	string	$selected       Id group preselected
7049
+     *  @param  string	$htmlname       Field name in form
7050
+     *  @param  int		$show_empty     0=liste sans valeur nulle, 1=ajoute valeur inconnue
7051
+     *  @param  string	$exclude        Array list of groups id to exclude
7052
+     * 	@param	int		$disabled		If select list must be disabled
7053
+     *  @param  string	$include        Array list of groups id to include
7054
+     * 	@param	int		$enableonly		Array list of groups id to be enabled. All other must be disabled
7055
+     * 	@param	string	$force_entity	'0' or Ids of environment to force
7056
+     * 	@param	bool	$multiple		add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
7057
+     *  @return	string
7058
+     *  @see select_dolusers
7059
+     */
7060
+    function select_dolgroups($selected='', $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity='0', $multiple=false)
7061
+    {
7062 7062
         // phpcs:enable
7063
-		global $conf,$user,$langs;
7064
-
7065
-		// Permettre l'exclusion de groupes
7066
-		if (is_array($exclude))	$excludeGroups = implode("','",$exclude);
7067
-		// Permettre l'inclusion de groupes
7068
-		if (is_array($include))	$includeGroups = implode("','",$include);
7069
-
7070
-		if (!is_array($selected)) $selected = array($selected);
7071
-
7072
-		$out='';
7073
-
7074
-		// On recherche les groupes
7075
-		$sql = "SELECT ug.rowid, ug.nom as name";
7076
-		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
7077
-		{
7078
-			$sql.= ", e.label";
7079
-		}
7080
-		$sql.= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
7081
-		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
7082
-		{
7083
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
7084
-			if ($force_entity) $sql.= " WHERE ug.entity IN (0,".$force_entity.")";
7085
-			else $sql.= " WHERE ug.entity IS NOT NULL";
7086
-		}
7087
-		else
7088
-		{
7089
-			$sql.= " WHERE ug.entity IN (0,".$conf->entity.")";
7090
-		}
7091
-		if (is_array($exclude) && $excludeGroups) $sql.= " AND ug.rowid NOT IN ('".$excludeGroups."')";
7092
-		if (is_array($include) && $includeGroups) $sql.= " AND ug.rowid IN ('".$includeGroups."')";
7093
-		$sql.= " ORDER BY ug.nom ASC";
7094
-
7095
-		dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
7096
-		$resql=$this->db->query($sql);
7097
-		if ($resql)
7098
-		{
7099
-			// Enhance with select2
7100
-			include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
7101
-		   	$out .= ajax_combobox($htmlname);
7102
-
7103
-			$out.= '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
7104
-
7105
-			$num = $this->db->num_rows($resql);
7106
-			$i = 0;
7107
-			if ($num)
7108
-			{
7109
-				if ($show_empty && !$multiple) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'>&nbsp;</option>'."\n";
7110
-
7111
-				while ($i < $num)
7112
-				{
7113
-					$obj = $this->db->fetch_object($resql);
7114
-					$disableline=0;
7115
-					if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;
7116
-
7117
-					$out.= '<option value="'.$obj->rowid.'"';
7118
-					if ($disableline) $out.= ' disabled';
7119
-					if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (! is_object($selected[0]) && in_array($obj->rowid,$selected) ))
7120
-					{
7121
-						$out.= ' selected';
7122
-					}
7123
-					$out.= '>';
7063
+        global $conf,$user,$langs;
7124 7064
 
7125
-					$out.= $obj->name;
7126
-					if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)
7127
-					{
7128
-						$out.= " (".$obj->label.")";
7129
-					}
7065
+        // Permettre l'exclusion de groupes
7066
+        if (is_array($exclude))	$excludeGroups = implode("','",$exclude);
7067
+        // Permettre l'inclusion de groupes
7068
+        if (is_array($include))	$includeGroups = implode("','",$include);
7069
+
7070
+        if (!is_array($selected)) $selected = array($selected);
7071
+
7072
+        $out='';
7073
+
7074
+        // On recherche les groupes
7075
+        $sql = "SELECT ug.rowid, ug.nom as name";
7076
+        if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
7077
+        {
7078
+            $sql.= ", e.label";
7079
+        }
7080
+        $sql.= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
7081
+        if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
7082
+        {
7083
+            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
7084
+            if ($force_entity) $sql.= " WHERE ug.entity IN (0,".$force_entity.")";
7085
+            else $sql.= " WHERE ug.entity IS NOT NULL";
7086
+        }
7087
+        else
7088
+        {
7089
+            $sql.= " WHERE ug.entity IN (0,".$conf->entity.")";
7090
+        }
7091
+        if (is_array($exclude) && $excludeGroups) $sql.= " AND ug.rowid NOT IN ('".$excludeGroups."')";
7092
+        if (is_array($include) && $includeGroups) $sql.= " AND ug.rowid IN ('".$includeGroups."')";
7093
+        $sql.= " ORDER BY ug.nom ASC";
7094
+
7095
+        dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
7096
+        $resql=$this->db->query($sql);
7097
+        if ($resql)
7098
+        {
7099
+            // Enhance with select2
7100
+            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
7101
+                $out .= ajax_combobox($htmlname);
7102
+
7103
+            $out.= '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
7104
+
7105
+            $num = $this->db->num_rows($resql);
7106
+            $i = 0;
7107
+            if ($num)
7108
+            {
7109
+                if ($show_empty && !$multiple) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'>&nbsp;</option>'."\n";
7110
+
7111
+                while ($i < $num)
7112
+                {
7113
+                    $obj = $this->db->fetch_object($resql);
7114
+                    $disableline=0;
7115
+                    if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;
7116
+
7117
+                    $out.= '<option value="'.$obj->rowid.'"';
7118
+                    if ($disableline) $out.= ' disabled';
7119
+                    if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (! is_object($selected[0]) && in_array($obj->rowid,$selected) ))
7120
+                    {
7121
+                        $out.= ' selected';
7122
+                    }
7123
+                    $out.= '>';
7124
+
7125
+                    $out.= $obj->name;
7126
+                    if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)
7127
+                    {
7128
+                        $out.= " (".$obj->label.")";
7129
+                    }
7130
+
7131
+                    $out.= '</option>';
7132
+                    $i++;
7133
+                }
7134
+            }
7135
+            else
7136
+            {
7137
+                if ($show_empty) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'></option>'."\n";
7138
+                $out.= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
7139
+            }
7140
+            $out.= '</select>';
7141
+        }
7142
+        else
7143
+        {
7144
+            dol_print_error($this->db);
7145
+        }
7146
+
7147
+        return $out;
7148
+    }
7149
+
7150
+
7151
+    /**
7152
+     *	Return HTML to show the search and clear seach button
7153
+     *
7154
+     *  @return	string
7155
+     */
7156
+    function showFilterButtons()
7157
+    {
7158
+        global $conf, $langs;
7159
+
7160
+        $out='<div class="nowrap">';
7161
+        $out.='<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"),'search.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
7162
+        $out.='<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"),'searchclear.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
7163
+        $out.='</div>';
7164
+
7165
+        return $out;
7166
+    }
7167
+
7168
+    /**
7169
+     *	Return HTML to show the search and clear seach button
7170
+     *
7171
+     *  @param  string  $cssclass                  CSS class
7172
+     *  @param  int     $calljsfunction            0=default. 1=call function initCheckForSelect() after changing status of checkboxes
7173
+     *  @return	string
7174
+     */
7175
+    function showCheckAddButtons($cssclass='checkforaction', $calljsfunction=0)
7176
+    {
7177
+        global $conf, $langs;
7130 7178
 
7131
-					$out.= '</option>';
7132
-					$i++;
7133
-				}
7134
-			}
7135
-			else
7136
-			{
7137
-				if ($show_empty) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'></option>'."\n";
7138
-				$out.= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
7139
-			}
7140
-			$out.= '</select>';
7141
-		}
7142
-		else
7143
-		{
7144
-			dol_print_error($this->db);
7145
-		}
7146
-
7147
-		return $out;
7148
-	}
7149
-
7150
-
7151
-	/**
7152
-	 *	Return HTML to show the search and clear seach button
7153
-	 *
7154
-	 *  @return	string
7155
-	 */
7156
-	function showFilterButtons()
7157
-	{
7158
-		global $conf, $langs;
7159
-
7160
-		$out='<div class="nowrap">';
7161
-		$out.='<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"),'search.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
7162
-		$out.='<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"),'searchclear.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
7163
-		$out.='</div>';
7164
-
7165
-		return $out;
7166
-	}
7167
-
7168
-	/**
7169
-	 *	Return HTML to show the search and clear seach button
7170
-	 *
7171
-	 *  @param  string  $cssclass                  CSS class
7172
-	 *  @param  int     $calljsfunction            0=default. 1=call function initCheckForSelect() after changing status of checkboxes
7173
-	 *  @return	string
7174
-	 */
7175
-	function showCheckAddButtons($cssclass='checkforaction', $calljsfunction=0)
7176
-	{
7177
-		global $conf, $langs;
7178
-
7179
-		$out='';
7180
-		if (! empty($conf->use_javascript_ajax)) $out.='<div class="inline-block checkallactions"><input type="checkbox" id="checkallactions" name="checkallactions" class="checkallactions"></div>';
7181
-		$out.='<script type="text/javascript">
7179
+        $out='';
7180
+        if (! empty($conf->use_javascript_ajax)) $out.='<div class="inline-block checkallactions"><input type="checkbox" id="checkallactions" name="checkallactions" class="checkallactions"></div>';
7181
+        $out.='<script type="text/javascript">
7182 7182
             $(document).ready(function() {
7183 7183
             	$("#checkallactions").click(function() {
7184 7184
                     if($(this).is(\':checked\')){
@@ -7190,8 +7190,8 @@  discard block
 block discarded – undo
7190 7190
                         console.log("We uncheck all");
7191 7191
                 		$(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
7192 7192
                     }'."\n";
7193
-		if ($calljsfunction) $out.='if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
7194
-		$out.='         });
7193
+        if ($calljsfunction) $out.='if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
7194
+        $out.='         });
7195 7195
 
7196 7196
         	$(".checkforselect").change(function() {
7197 7197
 				$(this).closest("tr").toggleClass("highlight", this.checked);
@@ -7200,78 +7200,78 @@  discard block
 block discarded – undo
7200 7200
  	});
7201 7201
     </script>';
7202 7202
 
7203
-		return $out;
7204
-	}
7205
-
7206
-	/**
7207
-	 *	Return HTML to show the search and clear seach button
7208
-	 *
7209
-	 *  @param	int  	$addcheckuncheckall        Add the check all/uncheck all checkbox (use javascript) and code to manage this
7210
-	 *  @param  string  $cssclass                  CSS class
7211
-	 *  @param  int     $calljsfunction            0=default. 1=call function initCheckForSelect() after changing status of checkboxes
7212
-	 *  @return	string
7213
-	 */
7214
-	function showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0)
7215
-	{
7216
-		$out.=$this->showFilterButtons();
7217
-		if ($addcheckuncheckall)
7218
-		{
7219
-			$out.=$this->showCheckAddButtons($cssclass, $calljsfunction);
7220
-		}
7221
-		return $out;
7222
-	}
7223
-
7224
-	/**
7225
-	 * Return HTML to show the select of expense categories
7226
-	 *
7227
-	 * @param	string	$selected              preselected category
7228
-	 * @param	string	$htmlname              name of HTML select list
7229
-	 * @param	integer	$useempty              1=Add empty line
7230
-	 * @param	array	$excludeid             id to exclude
7231
-	 * @param	string	$target                htmlname of target select to bind event
7232
-	 * @param	int		$default_selected      default category to select if fk_c_type_fees change = EX_KME
7233
-	 * @param	array	$params                param to give
7234
-	 * @return	string
7235
-	 */
7236
-	function selectExpenseCategories($selected='', $htmlname='fk_c_exp_tax_cat', $useempty=0, $excludeid=array(), $target='', $default_selected=0, $params=array())
7237
-	{
7238
-		global $db, $conf, $langs, $user;
7239
-
7240
-		$sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';
7241
-		$sql.= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
7242
-		if (!empty($excludeid)) $sql.= ' AND rowid NOT IN ('.implode(',', $excludeid).')';
7243
-		$sql.= ' ORDER BY label';
7244
-
7245
-		$resql = $db->query($sql);
7246
-		if ($resql)
7247
-		{
7248
-			$out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7249
-			if ($useempty) $out.= '<option value="0">&nbsp;</option>';
7250
-
7251
-			while ($obj = $db->fetch_object($resql))
7252
-			{
7253
-				$out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
7254
-			}
7255
-			$out.= '</select>';
7256
-			if (! empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
7257
-
7258
-			if (!empty($target))
7259
-			{
7260
-				$sql = "SELECT c.id FROM ".MAIN_DB_PREFIX."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
7261
-				$resql = $db->query($sql);
7262
-				if ($resql)
7263
-				{
7264
-					if ($db->num_rows($resql) > 0)
7265
-					{
7266
-						$obj = $db->fetch_object($resql);
7267
-						$out.= '<script type="text/javascript">
7203
+        return $out;
7204
+    }
7205
+
7206
+    /**
7207
+     *	Return HTML to show the search and clear seach button
7208
+     *
7209
+     *  @param	int  	$addcheckuncheckall        Add the check all/uncheck all checkbox (use javascript) and code to manage this
7210
+     *  @param  string  $cssclass                  CSS class
7211
+     *  @param  int     $calljsfunction            0=default. 1=call function initCheckForSelect() after changing status of checkboxes
7212
+     *  @return	string
7213
+     */
7214
+    function showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0)
7215
+    {
7216
+        $out.=$this->showFilterButtons();
7217
+        if ($addcheckuncheckall)
7218
+        {
7219
+            $out.=$this->showCheckAddButtons($cssclass, $calljsfunction);
7220
+        }
7221
+        return $out;
7222
+    }
7223
+
7224
+    /**
7225
+     * Return HTML to show the select of expense categories
7226
+     *
7227
+     * @param	string	$selected              preselected category
7228
+     * @param	string	$htmlname              name of HTML select list
7229
+     * @param	integer	$useempty              1=Add empty line
7230
+     * @param	array	$excludeid             id to exclude
7231
+     * @param	string	$target                htmlname of target select to bind event
7232
+     * @param	int		$default_selected      default category to select if fk_c_type_fees change = EX_KME
7233
+     * @param	array	$params                param to give
7234
+     * @return	string
7235
+     */
7236
+    function selectExpenseCategories($selected='', $htmlname='fk_c_exp_tax_cat', $useempty=0, $excludeid=array(), $target='', $default_selected=0, $params=array())
7237
+    {
7238
+        global $db, $conf, $langs, $user;
7239
+
7240
+        $sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';
7241
+        $sql.= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
7242
+        if (!empty($excludeid)) $sql.= ' AND rowid NOT IN ('.implode(',', $excludeid).')';
7243
+        $sql.= ' ORDER BY label';
7244
+
7245
+        $resql = $db->query($sql);
7246
+        if ($resql)
7247
+        {
7248
+            $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7249
+            if ($useempty) $out.= '<option value="0">&nbsp;</option>';
7250
+
7251
+            while ($obj = $db->fetch_object($resql))
7252
+            {
7253
+                $out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
7254
+            }
7255
+            $out.= '</select>';
7256
+            if (! empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
7257
+
7258
+            if (!empty($target))
7259
+            {
7260
+                $sql = "SELECT c.id FROM ".MAIN_DB_PREFIX."c_type_fees as c WHERE c.code = 'EX_KME' AND c.active = 1";
7261
+                $resql = $db->query($sql);
7262
+                if ($resql)
7263
+                {
7264
+                    if ($db->num_rows($resql) > 0)
7265
+                    {
7266
+                        $obj = $db->fetch_object($resql);
7267
+                        $out.= '<script type="text/javascript">
7268 7268
 							$(function() {
7269 7269
 								$("select[name='.$target.']").on("change", function() {
7270 7270
 									var current_val = $(this).val();
7271 7271
 									if (current_val == '.$obj->id.') {';
7272
-						if (!empty($default_selected) || !empty($selected)) $out.= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
7272
+                        if (!empty($default_selected) || !empty($selected)) $out.= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
7273 7273
 
7274
-						$out.= '
7274
+                        $out.= '
7275 7275
 										$("select[name='.$htmlname.']").change();
7276 7276
 									}
7277 7277
 								});
@@ -7302,92 +7302,92 @@  discard block
 block discarded – undo
7302 7302
 								});
7303 7303
 							});
7304 7304
 						</script>';
7305
-					}
7306
-				}
7307
-			}
7308
-		}
7309
-		else
7310
-		{
7311
-			dol_print_error($db);
7312
-		}
7313
-
7314
-		return $out;
7315
-	}
7316
-
7317
-	/**
7318
-	 * Return HTML to show the select ranges of expense range
7319
-	 *
7320
-	 * @param	string	$selected    preselected category
7321
-	 * @param	string	$htmlname    name of HTML select list
7322
-	 * @param	integer	$useempty    1=Add empty line
7323
-	 * @return	string
7324
-	 */
7325
-	function selectExpenseRanges($selected='', $htmlname='fk_range', $useempty=0)
7326
-	{
7327
-		global $db,$conf,$langs;
7328
-
7329
-		$sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';
7330
-		$sql.= ' WHERE entity = '.$conf->entity.' AND active = 1';
7331
-
7332
-		$resql = $db->query($sql);
7333
-		if ($resql)
7334
-		{
7335
-			$out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7336
-			if ($useempty) $out.= '<option value="0"></option>';
7337
-
7338
-			while ($obj = $db->fetch_object($resql))
7339
-			{
7340
-				$out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
7341
-			}
7342
-			$out.= '</select>';
7343
-		}
7344
-		else
7345
-		{
7346
-			dol_print_error($db);
7347
-		}
7348
-
7349
-		return $out;
7350
-	}
7351
-
7352
-	/**
7353
-	 * Return HTML to show a select of expense
7354
-	 *
7355
-	 * @param	string	$selected    preselected category
7356
-	 * @param	string	$htmlname    name of HTML select list
7357
-	 * @param	integer	$useempty    1=Add empty choice
7358
-	 * @param	integer	$allchoice   1=Add all choice
7359
-	 * @param	integer	$useid       0=use 'code' as key, 1=use 'id' as key
7360
-	 * @return	string
7361
-	 */
7362
-	function selectExpense($selected='', $htmlname='fk_c_type_fees', $useempty=0, $allchoice=1, $useid=0)
7363
-	{
7364
-		global $db,$langs;
7365
-
7366
-		$sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';
7367
-		$sql.= ' WHERE active = 1';
7368
-
7369
-		$resql = $db->query($sql);
7370
-		if ($resql)
7371
-		{
7372
-			$out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7373
-			if ($useempty) $out.= '<option value="0"></option>';
7374
-			if ($allchoice) $out.= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
7375
-
7376
-			$field = 'code';
7377
-			if ($useid) $field = 'id';
7378
-
7379
-			while ($obj = $db->fetch_object($resql))
7380
-			{
7381
-				$key = $langs->trans($obj->code);
7382
-				$out.= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
7383
-			}
7384
-			$out.= '</select>';
7385
-		}
7386
-		else
7387
-		{
7388
-			dol_print_error($db);
7389
-		}
7390
-
7391
-		return $out;
7392
-	}
7305
+                    }
7306
+                }
7307
+            }
7308
+        }
7309
+        else
7310
+        {
7311
+            dol_print_error($db);
7312
+        }
7313
+
7314
+        return $out;
7315
+    }
7316
+
7317
+    /**
7318
+     * Return HTML to show the select ranges of expense range
7319
+     *
7320
+     * @param	string	$selected    preselected category
7321
+     * @param	string	$htmlname    name of HTML select list
7322
+     * @param	integer	$useempty    1=Add empty line
7323
+     * @return	string
7324
+     */
7325
+    function selectExpenseRanges($selected='', $htmlname='fk_range', $useempty=0)
7326
+    {
7327
+        global $db,$conf,$langs;
7328
+
7329
+        $sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';
7330
+        $sql.= ' WHERE entity = '.$conf->entity.' AND active = 1';
7331
+
7332
+        $resql = $db->query($sql);
7333
+        if ($resql)
7334
+        {
7335
+            $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7336
+            if ($useempty) $out.= '<option value="0"></option>';
7337
+
7338
+            while ($obj = $db->fetch_object($resql))
7339
+            {
7340
+                $out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
7341
+            }
7342
+            $out.= '</select>';
7343
+        }
7344
+        else
7345
+        {
7346
+            dol_print_error($db);
7347
+        }
7348
+
7349
+        return $out;
7350
+    }
7351
+
7352
+    /**
7353
+     * Return HTML to show a select of expense
7354
+     *
7355
+     * @param	string	$selected    preselected category
7356
+     * @param	string	$htmlname    name of HTML select list
7357
+     * @param	integer	$useempty    1=Add empty choice
7358
+     * @param	integer	$allchoice   1=Add all choice
7359
+     * @param	integer	$useid       0=use 'code' as key, 1=use 'id' as key
7360
+     * @return	string
7361
+     */
7362
+    function selectExpense($selected='', $htmlname='fk_c_type_fees', $useempty=0, $allchoice=1, $useid=0)
7363
+    {
7364
+        global $db,$langs;
7365
+
7366
+        $sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';
7367
+        $sql.= ' WHERE active = 1';
7368
+
7369
+        $resql = $db->query($sql);
7370
+        if ($resql)
7371
+        {
7372
+            $out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7373
+            if ($useempty) $out.= '<option value="0"></option>';
7374
+            if ($allchoice) $out.= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
7375
+
7376
+            $field = 'code';
7377
+            if ($useid) $field = 'id';
7378
+
7379
+            while ($obj = $db->fetch_object($resql))
7380
+            {
7381
+                $key = $langs->trans($obj->code);
7382
+                $out.= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
7383
+            }
7384
+            $out.= '</select>';
7385
+        }
7386
+        else
7387
+        {
7388
+            dol_print_error($db);
7389
+        }
7390
+
7391
+        return $out;
7392
+    }
7393 7393
 }
Please login to merge, or discard this patch.
Spacing   +1809 added lines, -1809 removed lines patch added patch discarded remove patch
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
 	/**
60 60
 	 * @var string Error code (or message)
61 61
 	 */
62
-	public $error='';
62
+	public $error = '';
63 63
 
64 64
     /**
65 65
      * @var string[]    Array of error strings
@@ -69,12 +69,12 @@  discard block
 block discarded – undo
69 69
 	public $num;
70 70
 
71 71
 	// Cache arrays
72
-	public $cache_types_paiements=array();
73
-	public $cache_conditions_paiements=array();
74
-	public $cache_availability=array();
75
-	public $cache_demand_reason=array();
76
-	public $cache_types_fees=array();
77
-	public $cache_vatrates=array();
72
+	public $cache_types_paiements = array();
73
+	public $cache_conditions_paiements = array();
74
+	public $cache_availability = array();
75
+	public $cache_demand_reason = array();
76
+	public $cache_types_fees = array();
77
+	public $cache_vatrates = array();
78 78
 
79 79
 
80 80
 	/**
@@ -102,45 +102,45 @@  discard block
 block discarded – undo
102 102
 	 * @param	string	$paramid		Key of parameter for id ('id', 'socid')
103 103
 	 * @return	string					HTML edit field
104 104
 	 */
105
-	function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata='string', $moreparam='', $fieldrequired=0, $notabletag=0, $paramid='id')
105
+	function editfieldkey($text, $htmlname, $preselected, $object, $perm, $typeofdata = 'string', $moreparam = '', $fieldrequired = 0, $notabletag = 0, $paramid = 'id')
106 106
 	{
107
-		global $conf,$langs;
107
+		global $conf, $langs;
108 108
 
109
-		$ret='';
109
+		$ret = '';
110 110
 
111 111
 		// TODO change for compatibility
112
-		if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;/',$typeofdata))
112
+		if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;/', $typeofdata))
113 113
 		{
114
-			if (! empty($perm))
114
+			if (!empty($perm))
115 115
 			{
116
-				$tmp=explode(':',$typeofdata);
117
-				$ret.= '<div class="editkey_'.$tmp[0].(! empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
118
-				if ($fieldrequired) $ret.='<span class="fieldrequired">';
119
-				$ret.= $langs->trans($text);
120
-				if ($fieldrequired) $ret.='</span>';
121
-				$ret.= '</div>'."\n";
116
+				$tmp = explode(':', $typeofdata);
117
+				$ret .= '<div class="editkey_'.$tmp[0].(!empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
118
+				if ($fieldrequired) $ret .= '<span class="fieldrequired">';
119
+				$ret .= $langs->trans($text);
120
+				if ($fieldrequired) $ret .= '</span>';
121
+				$ret .= '</div>'."\n";
122 122
 			}
123 123
 			else
124 124
 			{
125
-				if ($fieldrequired) $ret.='<span class="fieldrequired">';
126
-				$ret.= $langs->trans($text);
127
-				if ($fieldrequired) $ret.='</span>';
125
+				if ($fieldrequired) $ret .= '<span class="fieldrequired">';
126
+				$ret .= $langs->trans($text);
127
+				if ($fieldrequired) $ret .= '</span>';
128 128
 			}
129 129
 		}
130 130
 		else
131 131
 		{
132
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
133
-			if ($fieldrequired) $ret.='<span class="fieldrequired">';
134
-			$ret.=$langs->trans($text);
135
-			if ($fieldrequired) $ret.='</span>';
136
-			if (! empty($notabletag)) $ret.=' ';
137
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
138
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<td align="right">';
139
-			if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
140
-			if (! empty($notabletag) && $notabletag == 1) $ret.=' : ';
141
-			if (! empty($notabletag) && $notabletag == 3) $ret.=' ';
142
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
143
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</tr></table>';
132
+			if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
133
+			if ($fieldrequired) $ret .= '<span class="fieldrequired">';
134
+			$ret .= $langs->trans($text);
135
+			if ($fieldrequired) $ret .= '</span>';
136
+			if (!empty($notabletag)) $ret .= ' ';
137
+			if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '</td>';
138
+			if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '<td align="right">';
139
+			if ($htmlname && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '<a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
140
+			if (!empty($notabletag) && $notabletag == 1) $ret .= ' : ';
141
+			if (!empty($notabletag) && $notabletag == 3) $ret .= ' ';
142
+			if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '</td>';
143
+			if (empty($notabletag) && GETPOST('action', 'aZ09') != 'edit'.$htmlname && $perm) $ret .= '</tr></table>';
144 144
 		}
145 145
 
146 146
 		return $ret;
@@ -164,129 +164,129 @@  discard block
 block discarded – undo
164 164
 	 * @param	string	$paramid		Key of parameter for id ('id', 'socid')
165 165
 	 * @return  string					HTML edit field
166 166
 	 */
167
-	function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata='string', $editvalue='', $extObject=null, $custommsg=null, $moreparam='', $notabletag=0, $formatfunc='', $paramid='id')
167
+	function editfieldval($text, $htmlname, $value, $object, $perm, $typeofdata = 'string', $editvalue = '', $extObject = null, $custommsg = null, $moreparam = '', $notabletag = 0, $formatfunc = '', $paramid = 'id')
168 168
 	{
169
-		global $conf,$langs,$db;
169
+		global $conf, $langs, $db;
170 170
 
171
-		$ret='';
171
+		$ret = '';
172 172
 
173 173
 		// Check parameters
174 174
 		if (empty($typeofdata)) return 'ErrorBadParameter';
175 175
 
176 176
 		// When option to edit inline is activated
177
-		if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker
177
+		if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !preg_match('/^select;|datehourpicker/', $typeofdata)) // TODO add jquery timepicker
178 178
 		{
179
-			$ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
179
+			$ret .= $this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
180 180
 		}
181 181
 		else
182 182
 		{
183
-			if (GETPOST('action','aZ09') == 'edit'.$htmlname)
183
+			if (GETPOST('action', 'aZ09') == 'edit'.$htmlname)
184 184
 			{
185
-				$ret.="\n";
186
-				$ret.='<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam?'?'.$moreparam:'').'">';
187
-				$ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
188
-				$ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
189
-				$ret.='<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
190
-				if (empty($notabletag)) $ret.='<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
191
-				if (empty($notabletag)) $ret.='<tr><td>';
192
-				if (preg_match('/^(string|email)/',$typeofdata))
185
+				$ret .= "\n";
186
+				$ret .= '<form method="post" action="'.$_SERVER["PHP_SELF"].($moreparam ? '?'.$moreparam : '').'">';
187
+				$ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
188
+				$ret .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
189
+				$ret .= '<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
190
+				if (empty($notabletag)) $ret .= '<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
191
+				if (empty($notabletag)) $ret .= '<tr><td>';
192
+				if (preg_match('/^(string|email)/', $typeofdata))
193 193
 				{
194
-					$tmp=explode(':',$typeofdata);
195
-					$ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue?$editvalue:$value).'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
194
+					$tmp = explode(':', $typeofdata);
195
+					$ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue ? $editvalue : $value).'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').'>';
196 196
 				}
197
-				else if (preg_match('/^(numeric|amount)/',$typeofdata))
197
+				else if (preg_match('/^(numeric|amount)/', $typeofdata))
198 198
 				{
199
-					$tmp=explode(':',$typeofdata);
200
-					$valuetoshow=price2num($editvalue?$editvalue:$value);
201
-					$ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow!=''?price($valuetoshow):'').'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
199
+					$tmp = explode(':', $typeofdata);
200
+					$valuetoshow = price2num($editvalue ? $editvalue : $value);
201
+					$ret .= '<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow != '' ?price($valuetoshow) : '').'"'.($tmp[1] ? ' size="'.$tmp[1].'"' : '').'>';
202 202
 				}
203
-				else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))
203
+				else if (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata))
204 204
 				{
205
-					$tmp=explode(':',$typeofdata);
206
-					$cols=$tmp[2];
207
-					$morealt='';
208
-					if (preg_match('/%/',$cols))
205
+					$tmp = explode(':', $typeofdata);
206
+					$cols = $tmp[2];
207
+					$morealt = '';
208
+					if (preg_match('/%/', $cols))
209 209
 					{
210
-						$morealt=' style="width: '.$cols.'"';
211
-						$cols='';
210
+						$morealt = ' style="width: '.$cols.'"';
211
+						$cols = '';
212 212
 					}
213 213
 
214
-					$valuetoshow = ($editvalue?$editvalue:$value);
214
+					$valuetoshow = ($editvalue ? $editvalue : $value);
215 215
 
216
-					$ret.='<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1]?$tmp[1]:'20').'"'.($cols?' cols="'.$cols.'"':'class="quatrevingtpercent"').$morealt.'">';
217
-					$ret.=dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
218
-					$ret.='</textarea>';
216
+					$ret .= '<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1] ? $tmp[1] : '20').'"'.($cols ? ' cols="'.$cols.'"' : 'class="quatrevingtpercent"').$morealt.'">';
217
+					$ret .= dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
218
+					$ret .= '</textarea>';
219 219
 				}
220 220
 				else if ($typeofdata == 'day' || $typeofdata == 'datepicker')
221 221
 				{
222
-					$ret.=$this->selectDate($value,$htmlname,0,0,1,'form'.$htmlname,1,0);
222
+					$ret .= $this->selectDate($value, $htmlname, 0, 0, 1, 'form'.$htmlname, 1, 0);
223 223
 				}
224 224
 				else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
225 225
 				{
226
-					$ret.=$this->selectDate($value,$htmlname,1,1,1,'form'.$htmlname,1,0);
226
+					$ret .= $this->selectDate($value, $htmlname, 1, 1, 1, 'form'.$htmlname, 1, 0);
227 227
 				}
228
-				else if (preg_match('/^select;/',$typeofdata))
228
+				else if (preg_match('/^select;/', $typeofdata))
229 229
 				{
230
-					 $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
231
-					 foreach($arraydata as $val)
230
+					 $arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
231
+					 foreach ($arraydata as $val)
232 232
 					 {
233
-						 $tmp=explode(':',$val);
234
-						 $arraylist[$tmp[0]]=$tmp[1];
233
+						 $tmp = explode(':', $val);
234
+						 $arraylist[$tmp[0]] = $tmp[1];
235 235
 					 }
236
-					 $ret.=$this->selectarray($htmlname,$arraylist,$value);
236
+					 $ret .= $this->selectarray($htmlname, $arraylist, $value);
237 237
 				}
238
-				else if (preg_match('/^ckeditor/',$typeofdata))
238
+				else if (preg_match('/^ckeditor/', $typeofdata))
239 239
 				{
240
-					$tmp=explode(':',$typeofdata);		// Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols
240
+					$tmp = explode(':', $typeofdata); // Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols
241 241
 					require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
242
-					$doleditor=new DolEditor($htmlname, ($editvalue?$editvalue:$value), ($tmp[2]?$tmp[2]:''), ($tmp[3]?$tmp[3]:'100'), ($tmp[1]?$tmp[1]:'dolibarr_notes'), 'In', ($tmp[5]?$tmp[5]:0), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100'));
243
-					$ret.=$doleditor->Create(1);
242
+					$doleditor = new DolEditor($htmlname, ($editvalue ? $editvalue : $value), ($tmp[2] ? $tmp[2] : ''), ($tmp[3] ? $tmp[3] : '100'), ($tmp[1] ? $tmp[1] : 'dolibarr_notes'), 'In', ($tmp[5] ? $tmp[5] : 0), true, true, ($tmp[6] ? $tmp[6] : '20'), ($tmp[7] ? $tmp[7] : '100'));
243
+					$ret .= $doleditor->Create(1);
244 244
 				}
245
-				if (empty($notabletag)) $ret.='</td>';
245
+				if (empty($notabletag)) $ret .= '</td>';
246 246
 
247
-				if (empty($notabletag)) $ret.='<td align="left">';
247
+				if (empty($notabletag)) $ret .= '<td align="left">';
248 248
 				//else $ret.='<div class="clearboth"></div>';
249
-			   	$ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="modify" value="'.$langs->trans("Modify").'">';
250
-			   	if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='<br>'."\n";
251
-			   	$ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
252
-			   	if (empty($notabletag)) $ret.='</td>';
249
+			   	$ret .= '<input type="submit" class="button'.(empty($notabletag) ? '' : ' ').'" name="modify" value="'.$langs->trans("Modify").'">';
250
+			   	if (preg_match('/ckeditor|textarea/', $typeofdata) && empty($notabletag)) $ret .= '<br>'."\n";
251
+			   	$ret .= '<input type="submit" class="button'.(empty($notabletag) ? '' : ' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
252
+			   	if (empty($notabletag)) $ret .= '</td>';
253 253
 
254
-			   	if (empty($notabletag)) $ret.='</tr></table>'."\n";
255
-				$ret.='</form>'."\n";
254
+			   	if (empty($notabletag)) $ret .= '</tr></table>'."\n";
255
+				$ret .= '</form>'."\n";
256 256
 			}
257 257
 			else
258 258
 			{
259
-				if (preg_match('/^(email)/',$typeofdata))              $ret.=dol_print_email($value,0,0,0,0,1);
260
-				elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');
261
-				elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))  $ret.=dol_htmlentitiesbr($value);
262
-				elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');
263
-				elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour');
264
-				else if (preg_match('/^select;/',$typeofdata))
259
+				if (preg_match('/^(email)/', $typeofdata))              $ret .= dol_print_email($value, 0, 0, 0, 0, 1);
260
+				elseif (preg_match('/^(amount|numeric)/', $typeofdata)) $ret .= ($value != '' ? price($value, '', $langs, 0, -1, -1, $conf->currency) : '');
261
+				elseif (preg_match('/^text/', $typeofdata) || preg_match('/^note/', $typeofdata))  $ret .= dol_htmlentitiesbr($value);
262
+				elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret .= dol_print_date($value, 'day');
263
+				elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret .= dol_print_date($value, 'dayhour');
264
+				else if (preg_match('/^select;/', $typeofdata))
265 265
 				{
266
-					$arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
267
-					foreach($arraydata as $val)
266
+					$arraydata = explode(',', preg_replace('/^select;/', '', $typeofdata));
267
+					foreach ($arraydata as $val)
268 268
 					{
269
-						$tmp=explode(':',$val);
270
-						$arraylist[$tmp[0]]=$tmp[1];
269
+						$tmp = explode(':', $val);
270
+						$arraylist[$tmp[0]] = $tmp[1];
271 271
 					}
272
-					$ret.=$arraylist[$value];
272
+					$ret .= $arraylist[$value];
273 273
 				}
274
-				else if (preg_match('/^ckeditor/',$typeofdata))
274
+				else if (preg_match('/^ckeditor/', $typeofdata))
275 275
 				{
276
-					$tmpcontent=dol_htmlentitiesbr($value);
277
-					if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
276
+					$tmpcontent = dol_htmlentitiesbr($value);
277
+					if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB))
278 278
 					{
279
-						$firstline=preg_replace('/<br>.*/','',$tmpcontent);
280
-						$firstline=preg_replace('/[\n\r].*/','',$firstline);
281
-						$tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');
279
+						$firstline = preg_replace('/<br>.*/', '', $tmpcontent);
280
+						$firstline = preg_replace('/[\n\r].*/', '', $firstline);
281
+						$tmpcontent = $firstline.((strlen($firstline) != strlen($tmpcontent)) ? '...' : '');
282 282
 					}
283
-					$ret.=$tmpcontent;
283
+					$ret .= $tmpcontent;
284 284
 				}
285
-				else $ret.=$value;
285
+				else $ret .= $value;
286 286
 
287 287
 				if ($formatfunc && method_exists($object, $formatfunc))
288 288
 				{
289
-					$ret=$object->$formatfunc($ret);
289
+					$ret = $object->$formatfunc($ret);
290 290
 				}
291 291
 			}
292 292
 		}
@@ -306,27 +306,27 @@  discard block
 block discarded – undo
306 306
 	 * @param	mixed	$custommsg		String or Array of custom messages : eg array('success' => 'MyMessage', 'error' => 'MyMessage')
307 307
 	 * @return	string   		      	HTML edit in place
308 308
 	 */
309
-	private function editInPlace($object, $value, $htmlname, $condition, $inputType='textarea', $editvalue=null, $extObject=null, $custommsg=null)
309
+	private function editInPlace($object, $value, $htmlname, $condition, $inputType = 'textarea', $editvalue = null, $extObject = null, $custommsg = null)
310 310
 	{
311 311
 		global $conf;
312 312
 
313
-		$out='';
313
+		$out = '';
314 314
 
315 315
 		// Check parameters
316
-		if (preg_match('/^text/',$inputType)) $value = dol_nl2br($value);
317
-		else if (preg_match('/^numeric/',$inputType)) $value = price($value);
316
+		if (preg_match('/^text/', $inputType)) $value = dol_nl2br($value);
317
+		else if (preg_match('/^numeric/', $inputType)) $value = price($value);
318 318
 		else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');
319 319
 
320 320
 		if ($condition)
321 321
 		{
322
-			$element		= false;
323
-			$table_element	= false;
322
+			$element = false;
323
+			$table_element = false;
324 324
 			$fk_element		= false;
325 325
 			$loadmethod		= false;
326 326
 			$savemethod		= false;
327 327
 			$ext_element	= false;
328 328
 			$button_only	= false;
329
-			$inputOption    = '';
329
+			$inputOption = '';
330 330
 
331 331
 			if (is_object($object))
332 332
 			{
@@ -340,48 +340,48 @@  discard block
 block discarded – undo
340 340
 				$ext_element = $extObject->element;
341 341
 			}
342 342
 
343
-			if (preg_match('/^(string|email|numeric)/',$inputType))
343
+			if (preg_match('/^(string|email|numeric)/', $inputType))
344 344
 			{
345
-				$tmp=explode(':',$inputType);
346
-				$inputType=$tmp[0];
347
-				if (! empty($tmp[1])) $inputOption=$tmp[1];
348
-				if (! empty($tmp[2])) $savemethod=$tmp[2];
349
-				$out.= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
345
+				$tmp = explode(':', $inputType);
346
+				$inputType = $tmp[0];
347
+				if (!empty($tmp[1])) $inputOption = $tmp[1];
348
+				if (!empty($tmp[2])) $savemethod = $tmp[2];
349
+				$out .= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
350 350
 			}
351
-			else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))
351
+			else if ((preg_match('/^day$/', $inputType)) || (preg_match('/^datepicker/', $inputType)) || (preg_match('/^datehourpicker/', $inputType)))
352 352
 			{
353
-				$tmp=explode(':',$inputType);
354
-				$inputType=$tmp[0];
355
-				if (! empty($tmp[1])) $inputOption=$tmp[1];
356
-				if (! empty($tmp[2])) $savemethod=$tmp[2];
353
+				$tmp = explode(':', $inputType);
354
+				$inputType = $tmp[0];
355
+				if (!empty($tmp[1])) $inputOption = $tmp[1];
356
+				if (!empty($tmp[2])) $savemethod = $tmp[2];
357 357
 
358
-				$out.= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
358
+				$out .= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
359 359
 			}
360
-			else if (preg_match('/^(select|autocomplete)/',$inputType))
360
+			else if (preg_match('/^(select|autocomplete)/', $inputType))
361 361
 			{
362
-				$tmp=explode(':',$inputType);
363
-				$inputType=$tmp[0]; $loadmethod=$tmp[1];
364
-				if (! empty($tmp[2])) $savemethod=$tmp[2];
365
-				if (! empty($tmp[3])) $button_only=true;
362
+				$tmp = explode(':', $inputType);
363
+				$inputType = $tmp[0]; $loadmethod = $tmp[1];
364
+				if (!empty($tmp[2])) $savemethod = $tmp[2];
365
+				if (!empty($tmp[3])) $button_only = true;
366 366
 			}
367
-			else if (preg_match('/^textarea/',$inputType))
367
+			else if (preg_match('/^textarea/', $inputType))
368 368
 			{
369
-				$tmp=explode(':',$inputType);
370
-				$inputType=$tmp[0];
371
-				$rows=(empty($tmp[1])?'8':$tmp[1]);
372
-				$cols=(empty($tmp[2])?'80':$tmp[2]);
369
+				$tmp = explode(':', $inputType);
370
+				$inputType = $tmp[0];
371
+				$rows = (empty($tmp[1]) ? '8' : $tmp[1]);
372
+				$cols = (empty($tmp[2]) ? '80' : $tmp[2]);
373 373
 			}
374
-			else if (preg_match('/^ckeditor/',$inputType))
374
+			else if (preg_match('/^ckeditor/', $inputType))
375 375
 			{
376
-				$tmp=explode(':',$inputType);
377
-				$inputType=$tmp[0]; $toolbar=$tmp[1];
378
-				if (! empty($tmp[2])) $width=$tmp[2];
379
-				if (! empty($tmp[3])) $heigth=$tmp[3];
380
-				if (! empty($tmp[4])) $savemethod=$tmp[4];
376
+				$tmp = explode(':', $inputType);
377
+				$inputType = $tmp[0]; $toolbar = $tmp[1];
378
+				if (!empty($tmp[2])) $width = $tmp[2];
379
+				if (!empty($tmp[3])) $heigth = $tmp[3];
380
+				if (!empty($tmp[4])) $savemethod = $tmp[4];
381 381
 
382
-				if (! empty($conf->fckeditor->enabled))
382
+				if (!empty($conf->fckeditor->enabled))
383 383
 				{
384
-					$out.= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
384
+					$out .= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
385 385
 				}
386 386
 				else
387 387
 				{
@@ -389,30 +389,30 @@  discard block
 block discarded – undo
389 389
 				}
390 390
 			}
391 391
 
392
-			$out.= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
393
-			$out.= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
394
-			$out.= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
395
-			$out.= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
396
-			if (! empty($savemethod))	$out.= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
397
-			if (! empty($ext_element))	$out.= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
398
-			if (! empty($custommsg))
392
+			$out .= '<input id="element_'.$htmlname.'" value="'.$element.'" type="hidden"/>'."\n";
393
+			$out .= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
394
+			$out .= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
395
+			$out .= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
396
+			if (!empty($savemethod))	$out .= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
397
+			if (!empty($ext_element))	$out .= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
398
+			if (!empty($custommsg))
399 399
 			{
400 400
 				if (is_array($custommsg))
401 401
 				{
402 402
 					if (!empty($custommsg['success']))
403
-						$out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
403
+						$out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
404 404
 					if (!empty($custommsg['error']))
405
-						$out.= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
405
+						$out .= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
406 406
 				}
407 407
 				else
408
-					$out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
408
+					$out .= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
409 409
 			}
410 410
 			if ($inputType == 'textarea') {
411
-				$out.= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
412
-				$out.= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
411
+				$out .= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
412
+				$out .= '<input id="textarea_'.$htmlname.'_cols" value="'.$cols.'" type="hidden"/>'."\n";
413 413
 			}
414
-			$out.= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
415
-			$out.= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(! empty($editvalue) ? $editvalue : $value).'</span>'."\n";
414
+			$out .= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
415
+			$out .= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(!empty($editvalue) ? $editvalue : $value).'</span>'."\n";
416 416
 		}
417 417
 		else
418 418
 		{
@@ -441,73 +441,73 @@  discard block
 block discarded – undo
441 441
 	 *	@see	Use function textwithpicto if you can.
442 442
 	 *  TODO Move this as static as soon as everybody use textwithpicto or @Form::textwithtooltip
443 443
 	 */
444
-	function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger='', $forcenowrap=0)
444
+	function textwithtooltip($text, $htmltext, $tooltipon = 1, $direction = 0, $img = '', $extracss = '', $notabs = 2, $incbefore = '', $noencodehtmltext = 0, $tooltiptrigger = '', $forcenowrap = 0)
445 445
 	{
446 446
 		global $conf;
447 447
 
448 448
 		if ($incbefore) $text = $incbefore.$text;
449
-		if (! $htmltext) return $text;
449
+		if (!$htmltext) return $text;
450 450
 
451
-		$tag='td';
452
-		if ($notabs == 2) $tag='div';
453
-		if ($notabs == 3) $tag='span';
451
+		$tag = 'td';
452
+		if ($notabs == 2) $tag = 'div';
453
+		if ($notabs == 3) $tag = 'span';
454 454
 		// Sanitize tooltip
455
-		$htmltext=str_replace("\\","\\\\",$htmltext);
456
-		$htmltext=str_replace("\r","",$htmltext);
457
-		$htmltext=str_replace("\n","",$htmltext);
455
+		$htmltext = str_replace("\\", "\\\\", $htmltext);
456
+		$htmltext = str_replace("\r", "", $htmltext);
457
+		$htmltext = str_replace("\n", "", $htmltext);
458 458
 
459
-		$extrastyle='';
460
-		if ($direction < 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-left: 3px !important;'; }
461
-		if ($direction > 0) { $extracss=($extracss?$extracss.' ':'').'inline-block'; $extrastyle='padding: 0px; padding-right: 3px !important;'; }
459
+		$extrastyle = '';
460
+		if ($direction < 0) { $extracss = ($extracss ? $extracss.' ' : '').'inline-block'; $extrastyle = 'padding: 0px; padding-left: 3px !important;'; }
461
+		if ($direction > 0) { $extracss = ($extracss ? $extracss.' ' : '').'inline-block'; $extrastyle = 'padding: 0px; padding-right: 3px !important;'; }
462 462
 
463
-		$classfortooltip='classfortooltip';
463
+		$classfortooltip = 'classfortooltip';
464 464
 
465
-		$s='';$textfordialog='';
465
+		$s = ''; $textfordialog = '';
466 466
 
467 467
 		if ($tooltiptrigger == '')
468 468
 		{
469
-			$htmltext=str_replace('"',"&quot;",$htmltext);
469
+			$htmltext = str_replace('"', "&quot;", $htmltext);
470 470
 		}
471 471
 		else
472 472
 		{
473
-			$classfortooltip='classfortooltiponclick';
474
-			$textfordialog.='<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
473
+			$classfortooltip = 'classfortooltiponclick';
474
+			$textfordialog .= '<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
475 475
 		}
476 476
 		if ($tooltipon == 2 || $tooltipon == 3)
477 477
 		{
478
-			$paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"';
479
-			if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip
480
-			else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"';
478
+			$paramfortooltipimg = ' class="'.$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'"';
479
+			if ($tooltiptrigger == '') $paramfortooltipimg .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on img tag to store tooltip
480
+			else $paramfortooltipimg .= ' dolid="'.$tooltiptrigger.'"';
481 481
 		}
482
-		else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
482
+		else $paramfortooltipimg = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
483 483
 		if ($tooltipon == 1 || $tooltipon == 3)
484 484
 		{
485
-			$paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" ';
486
-			if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip
487
-			else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"';
485
+			$paramfortooltiptd = ' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss ? ' '.$extracss : '').'" style="padding: 0px;'.($extrastyle ? ' '.$extrastyle : '').'" ';
486
+			if ($tooltiptrigger == '') $paramfortooltiptd .= ' title="'.($noencodehtmltext ? $htmltext : dol_escape_htmltag($htmltext, 1)).'"'; // Attribut to put on td tag to store tooltip
487
+			else $paramfortooltiptd .= ' dolid="'.$tooltiptrigger.'"';
488 488
 		}
489
-		else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
490
-		if (empty($notabs)) $s.='<table class="nobordernopadding" summary=""><tr style="height: auto;">';
491
-		elseif ($notabs == 2) $s.='<div class="inline-block'.($forcenowrap?' nowrap':'').'">';
489
+		else $paramfortooltiptd = ($extracss ? ' class="'.$extracss.'"' : '').($extrastyle ? ' style="'.$extrastyle.'"' : ''); // Attribut to put on td text tag
490
+		if (empty($notabs)) $s .= '<table class="nobordernopadding" summary=""><tr style="height: auto;">';
491
+		elseif ($notabs == 2) $s .= '<div class="inline-block'.($forcenowrap ? ' nowrap' : '').'">';
492 492
 		// Define value if value is before
493 493
 		if ($direction < 0) {
494
-			$s.='<'.$tag.$paramfortooltipimg;
494
+			$s .= '<'.$tag.$paramfortooltipimg;
495 495
 			if ($tag == 'td') {
496 496
 				$s .= ' valign="top" width="14"';
497 497
 			}
498
-			$s.= '>'.$textfordialog.$img.'</'.$tag.'>';
498
+			$s .= '>'.$textfordialog.$img.'</'.$tag.'>';
499 499
 		}
500 500
 		// Use another method to help avoid having a space in value in order to use this value with jquery
501 501
 		// Define label
502
-		if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
502
+		if ((string) $text != '') $s .= '<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
503 503
 		// Define value if value is after
504 504
 		if ($direction > 0) {
505
-			$s.='<'.$tag.$paramfortooltipimg;
505
+			$s .= '<'.$tag.$paramfortooltipimg;
506 506
 			if ($tag == 'td') $s .= ' valign="middle" width="14"';
507
-			$s.= '>'.$textfordialog.$img.'</'.$tag.'>';
507
+			$s .= '>'.$textfordialog.$img.'</'.$tag.'>';
508 508
 		}
509
-		if (empty($notabs)) $s.='</tr></table>';
510
-		elseif ($notabs == 2) $s.='</div>';
509
+		if (empty($notabs)) $s .= '</tr></table>';
510
+		elseif ($notabs == 2) $s .= '</div>';
511 511
 
512 512
 		return $s;
513 513
 	}
@@ -526,12 +526,12 @@  discard block
 block discarded – undo
526 526
 	 *  @param	int		$forcenowrap		Force no wrap between text and picto (works with notabs=2 only)
527 527
 	 * 	@return	string						HTML code of text, picto, tooltip
528 528
 	 */
529
-	function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger='', $forcenowrap=0)
529
+	function textwithpicto($text, $htmltext, $direction = 1, $type = 'help', $extracss = '', $noencodehtmltext = 0, $notabs = 2, $tooltiptrigger = '', $forcenowrap = 0)
530 530
 	{
531 531
 		global $conf, $langs;
532 532
 
533 533
 		$alt = '';
534
-		if ($tooltiptrigger) $alt=$langs->transnoentitiesnoconv("ClickToShowHelp");
534
+		if ($tooltiptrigger) $alt = $langs->transnoentitiesnoconv("ClickToShowHelp");
535 535
 
536 536
 		//For backwards compatibility
537 537
 		if ($type == '0') $type = 'info';
@@ -549,12 +549,12 @@  discard block
 block discarded – undo
549 549
 		}
550 550
 
551 551
 		// If info or help with smartphone, show only text (tooltip hover can't works)
552
-		if (! empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))
552
+		if (!empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))
553 553
 		{
554 554
 			if ($type == 'info' || $type == 'help') return $text;
555 555
 		}
556 556
 		// If info or help with smartphone, show only text (tooltip on lick does not works with dialog on smaprtphone)
557
-		if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
557
+		if (!empty($conf->dol_no_mouse_hover) && !empty($tooltiptrigger))
558 558
 		{
559 559
 			if ($type == 'info' || $type == 'help') return $text;
560 560
 		}
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
 		elseif ($type == 'warning') $img = img_warning($alt);
567 567
 		else $img = img_picto($alt, $type);
568 568
 
569
-		return $this->textwithtooltip($text, $htmltext, (($tooltiptrigger && ! $img)?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
569
+		return $this->textwithtooltip($text, $htmltext, (($tooltiptrigger && !$img) ? 3 : 2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
570 570
 	}
571 571
 
572 572
 	/**
@@ -577,38 +577,38 @@  discard block
 block discarded – undo
577 577
 	 * @param   int     $alwaysvisible  1=select button always visible
578 578
 	 * @return	string					Select list
579 579
 	 */
580
-	function selectMassAction($selected, $arrayofaction, $alwaysvisible=0)
580
+	function selectMassAction($selected, $arrayofaction, $alwaysvisible = 0)
581 581
 	{
582
-		global $conf,$langs,$hookmanager;
582
+		global $conf, $langs, $hookmanager;
583 583
 
584 584
 		if (count($arrayofaction) == 0) return;
585 585
 
586
-		$disabled=0;
587
-		$ret='<div class="centpercent center">';
588
-		$ret.='<select class="flat'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionselect" name="massaction"'.($disabled?' disabled="disabled"':'').'>';
586
+		$disabled = 0;
587
+		$ret = '<div class="centpercent center">';
588
+		$ret .= '<select class="flat'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' massaction massactionselect" name="massaction"'.($disabled ? ' disabled="disabled"' : '').'>';
589 589
 
590 590
 		// Complete list with data from external modules. THe module can use $_SERVER['PHP_SELF'] to know on which page we are, or use the $parameters['currentcontext'] completed by executeHooks.
591
-		$parameters=array();
592
-		$reshook=$hookmanager->executeHooks('addMoreMassActions',$parameters);    // Note that $action and $object may have been modified by hook
591
+		$parameters = array();
592
+		$reshook = $hookmanager->executeHooks('addMoreMassActions', $parameters); // Note that $action and $object may have been modified by hook
593 593
 		if (empty($reshook))
594 594
 		{
595
-			$ret.='<option value="0"'.($disabled?' disabled="disabled"':'').'>-- '.$langs->trans("SelectAction").' --</option>';
596
-			foreach($arrayofaction as $code => $label)
595
+			$ret .= '<option value="0"'.($disabled ? ' disabled="disabled"' : '').'>-- '.$langs->trans("SelectAction").' --</option>';
596
+			foreach ($arrayofaction as $code => $label)
597 597
 			{
598
-				$ret.='<option value="'.$code.'"'.($disabled?' disabled="disabled"':'').'>'.$label.'</option>';
598
+				$ret .= '<option value="'.$code.'"'.($disabled ? ' disabled="disabled"' : '').'>'.$label.'</option>';
599 599
 			}
600 600
 		}
601
-		$ret.=$hookmanager->resPrint;
601
+		$ret .= $hookmanager->resPrint;
602 602
 
603
-		$ret.='</select>';
603
+		$ret .= '</select>';
604 604
 		// Warning: if you set submit button to disabled, post using 'Enter' will no more work if there is no another input submit. So we add a hidden button
605
-		$ret.='<input type="submit" name="confirmmassactioninvisible" style="display: none" tabindex="-1">';	// Hidden button BEFORE so it is the one used when we submit with ENTER.
606
-		$ret.='<input type="submit" disabled name="confirmmassaction" class="button'.(empty($conf->use_javascript_ajax)?'':' hideobject').' massaction massactionconfirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
607
-		$ret.='</div>';
605
+		$ret .= '<input type="submit" name="confirmmassactioninvisible" style="display: none" tabindex="-1">'; // Hidden button BEFORE so it is the one used when we submit with ENTER.
606
+		$ret .= '<input type="submit" disabled name="confirmmassaction" class="button'.(empty($conf->use_javascript_ajax) ? '' : ' hideobject').' massaction massactionconfirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
607
+		$ret .= '</div>';
608 608
 
609
-		if (! empty($conf->use_javascript_ajax))
609
+		if (!empty($conf->use_javascript_ajax))
610 610
 		{
611
-			$ret.='<!-- JS CODE TO ENABLE mass action select -->
611
+			$ret .= '<!-- JS CODE TO ENABLE mass action select -->
612 612
     		<script type="text/javascript">
613 613
         		function initCheckForSelect(mode)	/* mode is 0 during init of page or click all, 1 when we click on 1 checkbox */
614 614
         		{
@@ -677,44 +677,44 @@  discard block
 block discarded – undo
677 677
 	 *  @param	int		$addspecialentries	1=Add dedicated entries for group of countries (like 'European Economic Community', ...)
678 678
 	 *  @return string           			HTML string with select
679 679
 	 */
680
-	function select_country($selected='', $htmlname='country_id', $htmloption='', $maxlength=0, $morecss='minwidth300', $usecodeaskey='', $showempty=1, $disablefavorites=0, $addspecialentries=0)
680
+	function select_country($selected = '', $htmlname = 'country_id', $htmloption = '', $maxlength = 0, $morecss = 'minwidth300', $usecodeaskey = '', $showempty = 1, $disablefavorites = 0, $addspecialentries = 0)
681 681
 	{
682 682
         // phpcs:enable
683
-		global $conf,$langs,$mysoc;
683
+		global $conf, $langs, $mysoc;
684 684
 
685 685
 		$langs->load("dict");
686 686
 
687
-		$out='';
688
-		$countryArray=array();
689
-		$favorite=array();
690
-		$label=array();
691
-		$atleastonefavorite=0;
687
+		$out = '';
688
+		$countryArray = array();
689
+		$favorite = array();
690
+		$label = array();
691
+		$atleastonefavorite = 0;
692 692
 
693 693
 		$sql = "SELECT rowid, code as code_iso, code_iso as code_iso3, label, favorite";
694
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_country";
695
-		$sql.= " WHERE active > 0";
694
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_country";
695
+		$sql .= " WHERE active > 0";
696 696
 		//$sql.= " ORDER BY code ASC";
697 697
 
698 698
 		dol_syslog(get_class($this)."::select_country", LOG_DEBUG);
699
-		$resql=$this->db->query($sql);
699
+		$resql = $this->db->query($sql);
700 700
 		if ($resql)
701 701
 		{
702
-			$out.= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" '.$htmloption.'>';
702
+			$out .= '<select id="select'.$htmlname.'" class="flat maxwidth200onsmartphone selectcountry'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" '.$htmloption.'>';
703 703
 			$num = $this->db->num_rows($resql);
704 704
 			$i = 0;
705 705
 			if ($num)
706 706
 			{
707
-				$foundselected=false;
707
+				$foundselected = false;
708 708
 
709 709
 				while ($i < $num)
710 710
 				{
711 711
 					$obj = $this->db->fetch_object($resql);
712
-					$countryArray[$i]['rowid'] 		= $obj->rowid;
713
-					$countryArray[$i]['code_iso'] 	= $obj->code_iso;
712
+					$countryArray[$i]['rowid'] = $obj->rowid;
713
+					$countryArray[$i]['code_iso'] = $obj->code_iso;
714 714
 					$countryArray[$i]['code_iso3'] 	= $obj->code_iso3;
715
-					$countryArray[$i]['label']		= ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso)!="Country".$obj->code_iso?$langs->transnoentitiesnoconv("Country".$obj->code_iso):($obj->label!='-'?$obj->label:''));
715
+					$countryArray[$i]['label'] = ($obj->code_iso && $langs->transnoentitiesnoconv("Country".$obj->code_iso) != "Country".$obj->code_iso ? $langs->transnoentitiesnoconv("Country".$obj->code_iso) : ($obj->label != '-' ? $obj->label : ''));
716 716
 					$countryArray[$i]['favorite']   = $obj->favorite;
717
-					$favorite[$i]					= $obj->favorite;
717
+					$favorite[$i] = $obj->favorite;
718 718
 					$label[$i] = dol_string_unaccent($countryArray[$i]['label']);
719 719
 					$i++;
720 720
 				}
@@ -724,17 +724,17 @@  discard block
 block discarded – undo
724 724
 
725 725
 				if ($showempty)
726 726
 				{
727
-					$out.='<option value="">&nbsp;</option>'."\n";
727
+					$out .= '<option value="">&nbsp;</option>'."\n";
728 728
 				}
729 729
 
730 730
 				if ($addspecialentries)	// Add dedicated entries for groups of countries
731 731
 				{
732 732
 					//if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
733
-					$out.= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
734
-					$out.= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
735
-					if ($mysoc->isInEEC()) $out.= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
736
-					$out.= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
737
-					$out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
733
+					$out .= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
734
+					$out .= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
735
+					if ($mysoc->isInEEC()) $out .= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
736
+					$out .= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
737
+					$out .= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
738 738
 				}
739 739
 
740 740
 				foreach ($countryArray as $row)
@@ -745,25 +745,25 @@  discard block
 block discarded – undo
745 745
 					if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) $atleastonefavorite++;
746 746
 					if (empty($row['favorite']) && $atleastonefavorite)
747 747
 					{
748
-						$atleastonefavorite=0;
749
-						$out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
748
+						$atleastonefavorite = 0;
749
+						$out .= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
750 750
 					}
751
-					if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']) )
751
+					if ($selected && $selected != '-1' && ($selected == $row['rowid'] || $selected == $row['code_iso'] || $selected == $row['code_iso3'] || $selected == $row['label']))
752 752
 					{
753
-						$foundselected=true;
754
-						$out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'" selected>';
753
+						$foundselected = true;
754
+						$out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'" selected>';
755 755
 					}
756 756
 					else
757 757
 					{
758
-						$out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'">';
758
+						$out .= '<option value="'.($usecodeaskey ? ($usecodeaskey == 'code2' ? $row['code_iso'] : $row['code_iso3']) : $row['rowid']).'">';
759 759
 					}
760
-					if ($row['label']) $out.= dol_trunc($row['label'],$maxlength,'middle');
761
-					else $out.= '&nbsp;';
762
-					if ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';
763
-					$out.= '</option>';
760
+					if ($row['label']) $out .= dol_trunc($row['label'], $maxlength, 'middle');
761
+					else $out .= '&nbsp;';
762
+					if ($row['code_iso']) $out .= ' ('.$row['code_iso'].')';
763
+					$out .= '</option>';
764 764
 				}
765 765
 			}
766
-			$out.= '</select>';
766
+			$out .= '</select>';
767 767
 		}
768 768
 		else
769 769
 		{
@@ -771,7 +771,7 @@  discard block
 block discarded – undo
771 771
 		}
772 772
 
773 773
 		// Make select dynamic
774
-		include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
774
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
775 775
 		$out .= ajax_combobox('select'.$htmlname);
776 776
 
777 777
 		return $out;
@@ -790,28 +790,28 @@  discard block
 block discarded – undo
790 790
 	 *  @param	array	$events					Event options to run on change. Example: array(array('method'=>'getContacts', 'url'=>dol_buildpath('/core/ajax/contacts.php',1), 'htmlname'=>'contactid', 'params'=>array('add-customer-contact'=>'disabled')))
791 791
 	 *  @return string           				HTML string with select and input
792 792
 	 */
793
-	function select_incoterms($selected='', $location_incoterms='', $page='', $htmlname='incoterm_id', $htmloption='', $forcecombo=1, $events=array())
793
+	function select_incoterms($selected = '', $location_incoterms = '', $page = '', $htmlname = 'incoterm_id', $htmloption = '', $forcecombo = 1, $events = array())
794 794
 	{
795 795
         // phpcs:enable
796
-		global $conf,$langs;
796
+		global $conf, $langs;
797 797
 
798 798
 		$langs->load("dict");
799 799
 
800
-		$out='';
801
-		$incotermArray=array();
800
+		$out = '';
801
+		$incotermArray = array();
802 802
 
803 803
 		$sql = "SELECT rowid, code";
804
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_incoterms";
805
-		$sql.= " WHERE active > 0";
806
-		$sql.= " ORDER BY code ASC";
804
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_incoterms";
805
+		$sql .= " WHERE active > 0";
806
+		$sql .= " ORDER BY code ASC";
807 807
 
808 808
 		dol_syslog(get_class($this)."::select_incoterm", LOG_DEBUG);
809
-		$resql=$this->db->query($sql);
809
+		$resql = $this->db->query($sql);
810 810
 		if ($resql)
811 811
 		{
812
-			if ($conf->use_javascript_ajax && ! $forcecombo)
812
+			if ($conf->use_javascript_ajax && !$forcecombo)
813 813
 			{
814
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
814
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
815 815
 				$out .= ajax_combobox($htmlname, $events);
816 816
 			}
817 817
 
@@ -822,13 +822,13 @@  discard block
 block discarded – undo
822 822
 				$out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
823 823
 			}
824 824
 
825
-			$out.= '<select id="'.$htmlname.'" class="flat selectincoterm minwidth100imp noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
826
-			$out.= '<option value="0">&nbsp;</option>';
825
+			$out .= '<select id="'.$htmlname.'" class="flat selectincoterm minwidth100imp noenlargeonsmartphone" name="'.$htmlname.'" '.$htmloption.'>';
826
+			$out .= '<option value="0">&nbsp;</option>';
827 827
 			$num = $this->db->num_rows($resql);
828 828
 			$i = 0;
829 829
 			if ($num)
830 830
 			{
831
-				$foundselected=false;
831
+				$foundselected = false;
832 832
 
833 833
 				while ($i < $num)
834 834
 				{
@@ -842,19 +842,19 @@  discard block
 block discarded – undo
842 842
 				{
843 843
 					if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
844 844
 					{
845
-						$out.= '<option value="'.$row['rowid'].'" selected>';
845
+						$out .= '<option value="'.$row['rowid'].'" selected>';
846 846
 					}
847 847
 					else
848 848
 					{
849
-						$out.= '<option value="'.$row['rowid'].'">';
849
+						$out .= '<option value="'.$row['rowid'].'">';
850 850
 					}
851 851
 
852
-					if ($row['code']) $out.= $row['code'];
852
+					if ($row['code']) $out .= $row['code'];
853 853
 
854
-					$out.= '</option>';
854
+					$out .= '</option>';
855 855
 				}
856 856
 			}
857
-			$out.= '</select>';
857
+			$out .= '</select>';
858 858
 
859 859
 			$out .= '<input id="location_incoterms" class="maxwidth100onsmartphone" name="location_incoterms" value="'.$location_incoterms.'">';
860 860
 
@@ -883,14 +883,14 @@  discard block
 block discarded – undo
883 883
 	 * 	@param	integer	$forceall		1=Force to show products and services in combo list, whatever are activated modules, 0=No force, 2=Force to show only Products, 3=Force to show only services, -1=Force none (and set hidden field to 'service')
884 884
 	 *  @return	void
885 885
 	 */
886
-	function select_type_of_lines($selected='',$htmlname='type',$showempty=0,$hidetext=0,$forceall=0)
886
+	function select_type_of_lines($selected = '', $htmlname = 'type', $showempty = 0, $hidetext = 0, $forceall = 0)
887 887
 	{
888 888
         // phpcs:enable
889
-		global $db,$langs,$user,$conf;
889
+		global $db, $langs, $user, $conf;
890 890
 
891 891
 		// If product & services are enabled or both disabled.
892
-		if ($forceall == 1 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled))
893
-		|| (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) )
892
+		if ($forceall == 1 || (empty($forceall) && !empty($conf->product->enabled) && !empty($conf->service->enabled))
893
+		|| (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)))
894 894
 		{
895 895
 			if (empty($hidetext)) print $langs->trans("Type").': ';
896 896
 			print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
@@ -912,19 +912,19 @@  discard block
 block discarded – undo
912 912
 			print '</select>';
913 913
 			//if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
914 914
 		}
915
-		if ((empty($forceall) && empty($conf->product->enabled) && ! empty($conf->service->enabled)) || $forceall == 3)
915
+		if ((empty($forceall) && empty($conf->product->enabled) && !empty($conf->service->enabled)) || $forceall == 3)
916 916
 		{
917 917
 			print $langs->trans("Service");
918 918
 			print '<input type="hidden" name="'.$htmlname.'" value="1">';
919 919
 		}
920
-		if ((empty($forceall) && ! empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2)
920
+		if ((empty($forceall) && !empty($conf->product->enabled) && empty($conf->service->enabled)) || $forceall == 2)
921 921
 		{
922 922
 			print $langs->trans("Product");
923 923
 			print '<input type="hidden" name="'.$htmlname.'" value="0">';
924 924
 		}
925 925
 		if ($forceall < 0)	// This should happened only for contracts when both predefined product and service are disabled.
926 926
 		{
927
-			print '<input type="hidden" name="'.$htmlname.'" value="1">';	// By default we set on service for contract. If CONTRACT_SUPPORT_PRODUCTS is set, forceall should be 1 not -1
927
+			print '<input type="hidden" name="'.$htmlname.'" value="1">'; // By default we set on service for contract. If CONTRACT_SUPPORT_PRODUCTS is set, forceall should be 1 not -1
928 928
 		}
929 929
 	}
930 930
 
@@ -940,17 +940,17 @@  discard block
 block discarded – undo
940 940
 		global $langs;
941 941
 
942 942
 		$num = count($this->cache_types_fees);
943
-		if ($num > 0) return 0;    // Cache already loaded
943
+		if ($num > 0) return 0; // Cache already loaded
944 944
 
945 945
 		dol_syslog(__METHOD__, LOG_DEBUG);
946 946
 
947 947
 		$langs->load("trips");
948 948
 
949 949
 		$sql = "SELECT c.code, c.label";
950
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
951
-		$sql.= " WHERE active > 0";
950
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c";
951
+		$sql .= " WHERE active > 0";
952 952
 
953
-		$resql=$this->db->query($sql);
953
+		$resql = $this->db->query($sql);
954 954
 		if ($resql)
955 955
 		{
956 956
 			$num = $this->db->num_rows($resql);
@@ -961,7 +961,7 @@  discard block
 block discarded – undo
961 961
 				$obj = $this->db->fetch_object($resql);
962 962
 
963 963
 				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
964
-				$label=($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
964
+				$label = ($obj->code != $langs->trans($obj->code) ? $langs->trans($obj->code) : $langs->trans($obj->label));
965 965
 				$this->cache_types_fees[$obj->code] = $label;
966 966
 				$i++;
967 967
 			}
@@ -986,7 +986,7 @@  discard block
 block discarded – undo
986 986
 	 * 	@param	int			$showempty		Add an empty field
987 987
 	 * 	@return	void
988 988
 	 */
989
-	function select_type_fees($selected='',$htmlname='type',$showempty=0)
989
+	function select_type_fees($selected = '', $htmlname = 'type', $showempty = 0)
990 990
 	{
991 991
         // phpcs:enable
992 992
 		global $user, $langs;
@@ -1003,7 +1003,7 @@  discard block
 block discarded – undo
1003 1003
 			print '>&nbsp;</option>';
1004 1004
 		}
1005 1005
 
1006
-		foreach($this->cache_types_fees as $key => $value)
1006
+		foreach ($this->cache_types_fees as $key => $value)
1007 1007
 		{
1008 1008
 			print '<option value="'.$key.'"';
1009 1009
 			if ($key == $selected) print ' selected';
@@ -1013,7 +1013,7 @@  discard block
 block discarded – undo
1013 1013
 		}
1014 1014
 
1015 1015
 		print '</select>';
1016
-		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
1016
+		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
1017 1017
 	}
1018 1018
 
1019 1019
 
@@ -1030,10 +1030,10 @@  discard block
 block discarded – undo
1030 1030
 	 *  @return		string								Return select box for thirdparty.
1031 1031
 	 *  @deprecated	3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0)
1032 1032
 	 */
1033
-	function select_thirdparty($selected='', $htmlname='socid', $filter='', $limit=20, $ajaxoptions=array(), $forcecombo=0)
1033
+	function select_thirdparty($selected = '', $htmlname = 'socid', $filter = '', $limit = 20, $ajaxoptions = array(), $forcecombo = 0)
1034 1034
 	{
1035 1035
         // phpcs:enable
1036
-   		return $this->select_thirdparty_list($selected,$htmlname,$filter,1,0,$forcecombo,array(),'',0, $limit);
1036
+   		return $this->select_thirdparty_list($selected, $htmlname, $filter, 1, 0, $forcecombo, array(), '', 0, $limit);
1037 1037
 	}
1038 1038
 
1039 1039
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -1056,45 +1056,45 @@  discard block
 block discarded – undo
1056 1056
 	 * 	@param  bool	$multiple				add [] in the name of element and add 'multiple' attribut (not working with ajax_autocompleter)
1057 1057
 	 * 	@return	string							HTML string with select box for thirdparty.
1058 1058
 	 */
1059
-	function select_company($selected='', $htmlname='socid', $filter='', $showempty='', $showtype=0, $forcecombo=0, $events=array(), $limit=0, $morecss='minwidth100', $moreparam='', $selected_input_value='', $hidelabel=1, $ajaxoptions=array(), $multiple=false)
1059
+	function select_company($selected = '', $htmlname = 'socid', $filter = '', $showempty = '', $showtype = 0, $forcecombo = 0, $events = array(), $limit = 0, $morecss = 'minwidth100', $moreparam = '', $selected_input_value = '', $hidelabel = 1, $ajaxoptions = array(), $multiple = false)
1060 1060
 	{
1061 1061
         // phpcs:enable
1062
-		global $conf,$user,$langs;
1062
+		global $conf, $user, $langs;
1063 1063
 
1064
-		$out='';
1064
+		$out = '';
1065 1065
 
1066
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && ! $forcecombo)
1066
+		if (!empty($conf->use_javascript_ajax) && !empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT) && !$forcecombo)
1067 1067
 		{
1068 1068
 			// No immediate load of all database
1069
-			$placeholder='';
1069
+			$placeholder = '';
1070 1070
 			if ($selected && empty($selected_input_value))
1071 1071
 			{
1072 1072
 				require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1073 1073
 				$societetmp = new Societe($this->db);
1074 1074
 				$societetmp->fetch($selected);
1075
-				$selected_input_value=$societetmp->name;
1075
+				$selected_input_value = $societetmp->name;
1076 1076
 				unset($societetmp);
1077 1077
 			}
1078 1078
 			// mode 1
1079
-			$urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:'');
1080
-			$out.=  ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1081
-			$out.='<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
1079
+			$urloption = 'htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype ? '&showtype='.$showtype : '');
1080
+			$out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1081
+			$out .= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
1082 1082
 			if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
1083 1083
 			else if ($hidelabel > 1) {
1084
-				$placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
1084
+				$placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
1085 1085
 				if ($hidelabel == 2) {
1086
-					$out.=  img_picto($langs->trans("Search"), 'search');
1086
+					$out .= img_picto($langs->trans("Search"), 'search');
1087 1087
 				}
1088 1088
 			}
1089
-			$out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
1089
+			$out .= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' '.(!empty($conf->global->THIRDPARTY_SEARCH_AUTOFOCUS) ? 'autofocus' : '').' />';
1090 1090
 			if ($hidelabel == 3) {
1091
-				$out.=  img_picto($langs->trans("Search"), 'search');
1091
+				$out .= img_picto($langs->trans("Search"), 'search');
1092 1092
 			}
1093 1093
 		}
1094 1094
 		else
1095 1095
 		{
1096 1096
 			// Immediate load of all database
1097
-			$out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple);
1097
+			$out .= $this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple);
1098 1098
 		}
1099 1099
 
1100 1100
 		return $out;
@@ -1120,22 +1120,22 @@  discard block
 block discarded – undo
1120 1120
 	 *	@param  bool	$multiple       add [] in the name of element and add 'multiple' attribut
1121 1121
 	 * 	@return	string					HTML string with
1122 1122
 	 */
1123
-	function select_thirdparty_list($selected='',$htmlname='socid',$filter='',$showempty='', $showtype=0, $forcecombo=0, $events=array(), $filterkey='', $outputmode=0, $limit=0, $morecss='minwidth100', $moreparam='', $multiple=false)
1123
+	function select_thirdparty_list($selected = '', $htmlname = 'socid', $filter = '', $showempty = '', $showtype = 0, $forcecombo = 0, $events = array(), $filterkey = '', $outputmode = 0, $limit = 0, $morecss = 'minwidth100', $moreparam = '', $multiple = false)
1124 1124
 	{
1125 1125
         // phpcs:enable
1126
-		global $conf,$user,$langs;
1126
+		global $conf, $user, $langs;
1127 1127
 
1128
-		$out='';
1129
-		$num=0;
1130
-		$outarray=array();
1128
+		$out = '';
1129
+		$num = 0;
1130
+		$outarray = array();
1131 1131
 
1132 1132
 		if ($selected === '') $selected = array();
1133 1133
 		else if (!is_array($selected)) $selected = array($selected);
1134 1134
 
1135 1135
 		// Clean $filter that may contains sql conditions so sql code
1136 1136
 		if (function_exists('testSqlAndScriptInject')) {
1137
-			if (testSqlAndScriptInject($filter, 3)>0) {
1138
-				$filter ='';
1137
+			if (testSqlAndScriptInject($filter, 3) > 0) {
1138
+				$filter = '';
1139 1139
 			}
1140 1140
 		}
1141 1141
 
@@ -1147,65 +1147,65 @@  discard block
 block discarded – undo
1147 1147
 		 	$sql .= " , dictp.code as country_code";
1148 1148
 		}
1149 1149
 
1150
-		$sql.= " FROM (".MAIN_DB_PREFIX ."societe as s";
1150
+		$sql .= " FROM (".MAIN_DB_PREFIX."societe as s";
1151 1151
 		if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1152
-		$sql.= " )";
1152
+		$sql .= " )";
1153 1153
 		if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1154
-			$sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid=s.fk_pays";
1154
+			$sql .= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid=s.fk_pays";
1155 1155
 		}
1156
-		$sql.= " WHERE s.entity IN (".getEntity('societe').")";
1157
-		if (! empty($user->socid)) $sql.= " AND s.rowid = ".$user->socid;
1158
-		if ($filter) $sql.= " AND (".$filter.")";
1159
-		if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
1160
-		if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0";
1156
+		$sql .= " WHERE s.entity IN (".getEntity('societe').")";
1157
+		if (!empty($user->socid)) $sql .= " AND s.rowid = ".$user->socid;
1158
+		if ($filter) $sql .= " AND (".$filter.")";
1159
+		if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
1160
+		if (!empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql .= " AND s.status <> 0";
1161 1161
 		// Add criteria
1162 1162
 		if ($filterkey && $filterkey != '')
1163 1163
 		{
1164
-			$sql.=" AND (";
1165
-			$prefix=empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
1164
+			$sql .= " AND (";
1165
+			$prefix = empty($conf->global->COMPANY_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if COMPANY_DONOTSEARCH_ANYWHERE is on
1166 1166
 			// For natural search
1167 1167
 			$scrit = explode(' ', $filterkey);
1168
-			$i=0;
1169
-			if (count($scrit) > 1) $sql.="(";
1168
+			$i = 0;
1169
+			if (count($scrit) > 1) $sql .= "(";
1170 1170
 			foreach ($scrit as $crit) {
1171
-				if ($i > 0) $sql.=" AND ";
1172
-				$sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
1171
+				if ($i > 0) $sql .= " AND ";
1172
+				$sql .= "(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
1173 1173
 				$i++;
1174 1174
 			}
1175
-			if (count($scrit) > 1) $sql.=")";
1176
-			if (! empty($conf->barcode->enabled))
1175
+			if (count($scrit) > 1) $sql .= ")";
1176
+			if (!empty($conf->barcode->enabled))
1177 1177
 			{
1178 1178
 				$sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1179 1179
 			}
1180
-			$sql.= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1181
-			$sql.=")";
1180
+			$sql .= " OR s.code_client LIKE '".$this->db->escape($prefix.$filterkey)."%' OR s.code_fournisseur LIKE '".$this->db->escape($prefix.$filterkey)."%'";
1181
+			$sql .= ")";
1182 1182
 		}
1183
-		$sql.=$this->db->order("nom","ASC");
1184
-		$sql.=$this->db->plimit($limit, 0);
1183
+		$sql .= $this->db->order("nom", "ASC");
1184
+		$sql .= $this->db->plimit($limit, 0);
1185 1185
 
1186 1186
 		// Build output string
1187 1187
 		dol_syslog(get_class($this)."::select_thirdparty_list", LOG_DEBUG);
1188
-		$resql=$this->db->query($sql);
1188
+		$resql = $this->db->query($sql);
1189 1189
 		if ($resql)
1190 1190
 		{
1191
-		   	if (! $forcecombo)
1191
+		   	if (!$forcecombo)
1192 1192
 			{
1193
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1193
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1194 1194
 				$out .= ajax_combobox($htmlname, $events, $conf->global->COMPANY_USE_SEARCH_TO_SELECT);
1195 1195
 			}
1196 1196
 
1197 1197
 			// Construct $out and $outarray
1198
-			$out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparam?' '.$moreparam:'').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
1198
+			$out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparam ? ' '.$moreparam : '').' name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').'>'."\n";
1199 1199
 
1200
-			$textifempty='';
1200
+			$textifempty = '';
1201 1201
 			// Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
1202 1202
 			//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
1203
-			if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
1203
+			if (!empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
1204 1204
 			{
1205
-				if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
1206
-				else $textifempty.=$langs->trans("All");
1205
+				if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
1206
+				else $textifempty .= $langs->trans("All");
1207 1207
 			}
1208
-			if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
1208
+			if ($showempty) $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
1209 1209
 
1210 1210
 			$num = $this->db->num_rows($resql);
1211 1211
 			$i = 0;
@@ -1214,50 +1214,50 @@  discard block
 block discarded – undo
1214 1214
 				while ($i < $num)
1215 1215
 				{
1216 1216
 					$obj = $this->db->fetch_object($resql);
1217
-					$label='';
1217
+					$label = '';
1218 1218
 					if ($conf->global->SOCIETE_ADD_REF_IN_LIST) {
1219 1219
 						if (($obj->client) && (!empty($obj->code_client))) {
1220
-							$label = $obj->code_client. ' - ';
1220
+							$label = $obj->code_client.' - ';
1221 1221
 						}
1222 1222
 						if (($obj->fournisseur) && (!empty($obj->code_fournisseur))) {
1223
-							$label .= $obj->code_fournisseur. ' - ';
1223
+							$label .= $obj->code_fournisseur.' - ';
1224 1224
 						}
1225
-						$label.=' '.$obj->name;
1225
+						$label .= ' '.$obj->name;
1226 1226
 					}
1227 1227
 					else
1228 1228
 					{
1229
-						$label=$obj->name;
1229
+						$label = $obj->name;
1230 1230
 					}
1231 1231
 
1232
-					if(!empty($obj->name_alias)) {
1233
-						$label.=' ('.$obj->name_alias.')';
1232
+					if (!empty($obj->name_alias)) {
1233
+						$label .= ' ('.$obj->name_alias.')';
1234 1234
 					}
1235 1235
 
1236 1236
 					if ($showtype)
1237 1237
 					{
1238
-						if ($obj->client || $obj->fournisseur) $label.=' (';
1239
-						if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer");
1240
-						if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect");
1241
-						if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier");
1242
-						if ($obj->client || $obj->fournisseur) $label.=')';
1238
+						if ($obj->client || $obj->fournisseur) $label .= ' (';
1239
+						if ($obj->client == 1 || $obj->client == 3) $label .= $langs->trans("Customer");
1240
+						if ($obj->client == 2 || $obj->client == 3) $label .= ($obj->client == 3 ? ', ' : '').$langs->trans("Prospect");
1241
+						if ($obj->fournisseur) $label .= ($obj->client ? ', ' : '').$langs->trans("Supplier");
1242
+						if ($obj->client || $obj->fournisseur) $label .= ')';
1243 1243
 					}
1244 1244
 
1245 1245
 					if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1246
-						$label.='-'.$obj->address.'-'. $obj->zip.' '. $obj->town;
1246
+						$label .= '-'.$obj->address.'-'.$obj->zip.' '.$obj->town;
1247 1247
 						if (!empty($obj->country_code)) {
1248
-							$label.= ' '. $langs->trans('Country'.$obj->country_code);
1248
+							$label .= ' '.$langs->trans('Country'.$obj->country_code);
1249 1249
 						}
1250 1250
 					}
1251 1251
 
1252 1252
 					if (empty($outputmode))
1253 1253
 					{
1254
-						if (in_array($obj->rowid,$selected))
1254
+						if (in_array($obj->rowid, $selected))
1255 1255
 						{
1256
-							$out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
1256
+							$out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
1257 1257
 						}
1258 1258
 						else
1259 1259
 						{
1260
-							$out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
1260
+							$out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
1261 1261
 						}
1262 1262
 					}
1263 1263
 					else
@@ -1266,17 +1266,17 @@  discard block
 block discarded – undo
1266 1266
 					}
1267 1267
 
1268 1268
 					$i++;
1269
-					if (($i % 10) == 0) $out.="\n";
1269
+					if (($i % 10) == 0) $out .= "\n";
1270 1270
 				}
1271 1271
 			}
1272
-			$out.= '</select>'."\n";
1272
+			$out .= '</select>'."\n";
1273 1273
 		}
1274 1274
 		else
1275 1275
 		{
1276 1276
 			dol_print_error($this->db);
1277 1277
 		}
1278 1278
 
1279
-		$this->result=array('nbofthirdparties'=>$num);
1279
+		$this->result = array('nbofthirdparties'=>$num);
1280 1280
 
1281 1281
 		if ($outputmode) return $outarray;
1282 1282
 		return $out;
@@ -1294,28 +1294,28 @@  discard block
 block discarded – undo
1294 1294
 	 * 		@param	int		$maxvalue		Max value for lines that can be selected
1295 1295
 	 * 		@return	int						Return number of qualifed lines in list
1296 1296
 	 */
1297
-	function select_remises($selected, $htmlname, $filter, $socid, $maxvalue=0)
1297
+	function select_remises($selected, $htmlname, $filter, $socid, $maxvalue = 0)
1298 1298
 	{
1299 1299
         // phpcs:enable
1300
-		global $langs,$conf;
1300
+		global $langs, $conf;
1301 1301
 
1302 1302
 		// On recherche les remises
1303 1303
 		$sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
1304
-		$sql.= " re.description, re.fk_facture_source";
1305
-		$sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
1306
-		$sql.= " WHERE re.fk_soc = ".(int) $socid;
1307
-		$sql.= " AND re.entity = " . $conf->entity;
1308
-		if ($filter) $sql.= " AND ".$filter;
1309
-		$sql.= " ORDER BY re.description ASC";
1304
+		$sql .= " re.description, re.fk_facture_source";
1305
+		$sql .= " FROM ".MAIN_DB_PREFIX."societe_remise_except as re";
1306
+		$sql .= " WHERE re.fk_soc = ".(int) $socid;
1307
+		$sql .= " AND re.entity = ".$conf->entity;
1308
+		if ($filter) $sql .= " AND ".$filter;
1309
+		$sql .= " ORDER BY re.description ASC";
1310 1310
 
1311 1311
 		dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
1312
-		$resql=$this->db->query($sql);
1312
+		$resql = $this->db->query($sql);
1313 1313
 		if ($resql)
1314 1314
 		{
1315 1315
 			print '<select id="select_'.$htmlname.'" class="flat maxwidthonsmartphone" name="'.$htmlname.'">';
1316 1316
 			$num = $this->db->num_rows($resql);
1317 1317
 
1318
-			$qualifiedlines=$num;
1318
+			$qualifiedlines = $num;
1319 1319
 
1320 1320
 			$i = 0;
1321 1321
 			if ($num)
@@ -1324,26 +1324,26 @@  discard block
 block discarded – undo
1324 1324
 				while ($i < $num)
1325 1325
 				{
1326 1326
 					$obj = $this->db->fetch_object($resql);
1327
-					$desc=dol_trunc($obj->description,40);
1328
-					if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
1329
-					if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
1330
-					if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
1331
-					if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc=preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
1327
+					$desc = dol_trunc($obj->description, 40);
1328
+					if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc = preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
1329
+					if (preg_match('/\(DEPOSIT\)/', $desc)) $desc = preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
1330
+					if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc = preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
1331
+					if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc = preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
1332 1332
 
1333
-					$selectstring='';
1334
-					if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected';
1333
+					$selectstring = '';
1334
+					if ($selected > 0 && $selected == $obj->rowid) $selectstring = ' selected';
1335 1335
 
1336
-					$disabled='';
1336
+					$disabled = '';
1337 1337
 					if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
1338 1338
 					{
1339 1339
 						$qualifiedlines--;
1340
-						$disabled=' disabled';
1340
+						$disabled = ' disabled';
1341 1341
 					}
1342 1342
 
1343 1343
 					if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source))
1344 1344
 					{
1345 1345
 						$tmpfac = new Facture($this->db);
1346
-						if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc=$desc.' - '.$tmpfac->ref;
1346
+						if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc = $desc.' - '.$tmpfac->ref;
1347 1347
 					}
1348 1348
 
1349 1349
 					print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
@@ -1381,10 +1381,10 @@  discard block
 block discarded – undo
1381 1381
 	 *	@return	int						<0 if KO, Nb of contact in list if OK
1382 1382
 	 *  @deprected						You can use selectcontacts directly (warning order of param was changed)
1383 1383
 	 */
1384
-	function select_contacts($socid,$selected='',$htmlname='contactid',$showempty=0,$exclude='',$limitto='',$showfunction=0, $moreclass='', $showsoc=0, $forcecombo=0, $events=array(), $options_only=false, $moreparam='', $htmlid='')
1384
+	function select_contacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $moreclass = '', $showsoc = 0, $forcecombo = 0, $events = array(), $options_only = false, $moreparam = '', $htmlid = '')
1385 1385
 	{
1386 1386
         // phpcs:enable
1387
-		print $this->selectcontacts($socid,$selected,$htmlname,$showempty,$exclude,$limitto,$showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
1387
+		print $this->selectcontacts($socid, $selected, $htmlname, $showempty, $exclude, $limitto, $showfunction, $moreclass, $options_only, $showsoc, $forcecombo, $events, $moreparam, $htmlid);
1388 1388
 		return $this->num;
1389 1389
 	}
1390 1390
 
@@ -1411,9 +1411,9 @@  discard block
 block discarded – undo
1411 1411
 	 *  @param	bool		$multiple		add [] in the name of element and add 'multiple' attribut
1412 1412
 	 *	@return	 int						<0 if KO, Nb of contact in list if OK
1413 1413
 	 */
1414
-	function selectcontacts($socid, $selected='', $htmlname='contactid', $showempty=0, $exclude='', $limitto='', $showfunction=0, $moreclass='', $options_only=false, $showsoc=0, $forcecombo=0, $events=array(), $moreparam='', $htmlid='', $multiple=false)
1414
+	function selectcontacts($socid, $selected = '', $htmlname = 'contactid', $showempty = 0, $exclude = '', $limitto = '', $showfunction = 0, $moreclass = '', $options_only = false, $showsoc = 0, $forcecombo = 0, $events = array(), $moreparam = '', $htmlid = '', $multiple = false)
1415 1415
 	{
1416
-		global $conf,$langs,$hookmanager,$action;
1416
+		global $conf, $langs, $hookmanager, $action;
1417 1417
 
1418 1418
 		$langs->load('companies');
1419 1419
 
@@ -1421,87 +1421,87 @@  discard block
 block discarded – undo
1421 1421
 
1422 1422
 		if ($selected === '') $selected = array();
1423 1423
 		else if (!is_array($selected)) $selected = array($selected);
1424
-		$out='';
1424
+		$out = '';
1425 1425
 
1426
-		if (! is_object($hookmanager))
1426
+		if (!is_object($hookmanager))
1427 1427
 		{
1428 1428
 			include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
1429
-			$hookmanager=new HookManager($this->db);
1429
+			$hookmanager = new HookManager($this->db);
1430 1430
 		}
1431 1431
 
1432 1432
 		// We search third parties
1433 1433
 		$sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste";
1434
-		if ($showsoc > 0) $sql.= " , s.nom as company";
1435
-		$sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp";
1436
-		if ($showsoc > 0) $sql.= " LEFT OUTER JOIN  ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc";
1437
-		$sql.= " WHERE sp.entity IN (".getEntity('socpeople').")";
1438
-		if ($socid > 0 || $socid == -1) $sql.= " AND sp.fk_soc=".$socid;
1439
-		if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0";
1440
-		$sql.= " ORDER BY sp.lastname ASC";
1434
+		if ($showsoc > 0) $sql .= " , s.nom as company";
1435
+		$sql .= " FROM ".MAIN_DB_PREFIX."socpeople as sp";
1436
+		if ($showsoc > 0) $sql .= " LEFT OUTER JOIN  ".MAIN_DB_PREFIX."societe as s ON s.rowid=sp.fk_soc";
1437
+		$sql .= " WHERE sp.entity IN (".getEntity('socpeople').")";
1438
+		if ($socid > 0 || $socid == -1) $sql .= " AND sp.fk_soc=".$socid;
1439
+		if (!empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql .= " AND sp.statut <> 0";
1440
+		$sql .= " ORDER BY sp.lastname ASC";
1441 1441
 
1442 1442
 		dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
1443
-		$resql=$this->db->query($sql);
1443
+		$resql = $this->db->query($sql);
1444 1444
 		if ($resql)
1445 1445
 		{
1446
-			$num=$this->db->num_rows($resql);
1446
+			$num = $this->db->num_rows($resql);
1447 1447
 
1448
-			if ($conf->use_javascript_ajax && ! $forcecombo && ! $options_only)
1448
+			if ($conf->use_javascript_ajax && !$forcecombo && !$options_only)
1449 1449
 			{
1450
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1450
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1451 1451
 				$out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
1452 1452
 			}
1453 1453
 
1454
-			if ($htmlname != 'none' || $options_only) $out.= '<select class="flat'.($moreclass?' '.$moreclass:'').'" id="'.$htmlid.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
1455
-			if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>&nbsp;</option>';
1456
-			if ($showempty == 2) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>'.$langs->trans("Internal").'</option>';
1454
+			if ($htmlname != 'none' || $options_only) $out .= '<select class="flat'.($moreclass ? ' '.$moreclass : '').'" id="'.$htmlid.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
1455
+			if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>&nbsp;</option>';
1456
+			if ($showempty == 2) $out .= '<option value="0"'.(in_array(0, $selected) ? ' selected' : '').'>'.$langs->trans("Internal").'</option>';
1457 1457
 			$num = $this->db->num_rows($resql);
1458 1458
 			$i = 0;
1459 1459
 			if ($num)
1460 1460
 			{
1461 1461
 				include_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1462
-				$contactstatic=new Contact($this->db);
1462
+				$contactstatic = new Contact($this->db);
1463 1463
 
1464 1464
 				while ($i < $num)
1465 1465
 				{
1466 1466
 					$obj = $this->db->fetch_object($resql);
1467 1467
 
1468
-					$contactstatic->id=$obj->rowid;
1469
-					$contactstatic->lastname=$obj->lastname;
1470
-					$contactstatic->firstname=$obj->firstname;
1471
-					if ($obj->statut == 1){
1468
+					$contactstatic->id = $obj->rowid;
1469
+					$contactstatic->lastname = $obj->lastname;
1470
+					$contactstatic->firstname = $obj->firstname;
1471
+					if ($obj->statut == 1) {
1472 1472
 					if ($htmlname != 'none')
1473 1473
 					{
1474
-						$disabled=0;
1475
-						if (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;
1476
-						if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;
1474
+						$disabled = 0;
1475
+						if (is_array($exclude) && count($exclude) && in_array($obj->rowid, $exclude)) $disabled = 1;
1476
+						if (is_array($limitto) && count($limitto) && !in_array($obj->rowid, $limitto)) $disabled = 1;
1477 1477
 						if (!empty($selected) && in_array($obj->rowid, $selected))
1478 1478
 						{
1479
-							$out.= '<option value="'.$obj->rowid.'"';
1480
-							if ($disabled) $out.= ' disabled';
1481
-							$out.= ' selected>';
1482
-							$out.= $contactstatic->getFullName($langs);
1483
-							if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1484
-							if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1485
-							$out.= '</option>';
1479
+							$out .= '<option value="'.$obj->rowid.'"';
1480
+							if ($disabled) $out .= ' disabled';
1481
+							$out .= ' selected>';
1482
+							$out .= $contactstatic->getFullName($langs);
1483
+							if ($showfunction && $obj->poste) $out .= ' ('.$obj->poste.')';
1484
+							if (($showsoc > 0) && $obj->company) $out .= ' - ('.$obj->company.')';
1485
+							$out .= '</option>';
1486 1486
 						}
1487 1487
 						else
1488 1488
 						{
1489
-							$out.= '<option value="'.$obj->rowid.'"';
1490
-							if ($disabled) $out.= ' disabled';
1491
-							$out.= '>';
1492
-							$out.= $contactstatic->getFullName($langs);
1493
-							if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1494
-							if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1495
-							$out.= '</option>';
1489
+							$out .= '<option value="'.$obj->rowid.'"';
1490
+							if ($disabled) $out .= ' disabled';
1491
+							$out .= '>';
1492
+							$out .= $contactstatic->getFullName($langs);
1493
+							if ($showfunction && $obj->poste) $out .= ' ('.$obj->poste.')';
1494
+							if (($showsoc > 0) && $obj->company) $out .= ' - ('.$obj->company.')';
1495
+							$out .= '</option>';
1496 1496
 						}
1497 1497
 					}
1498 1498
 					else
1499 1499
 					{
1500 1500
 						if (in_array($obj->rowid, $selected))
1501 1501
 						{
1502
-							$out.= $contactstatic->getFullName($langs);
1503
-							if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1504
-							if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1502
+							$out .= $contactstatic->getFullName($langs);
1503
+							if ($showfunction && $obj->poste) $out .= ' ('.$obj->poste.')';
1504
+							if (($showsoc > 0) && $obj->company) $out .= ' - ('.$obj->company.')';
1505 1505
 						}
1506 1506
 					}
1507 1507
 				}
@@ -1510,9 +1510,9 @@  discard block
 block discarded – undo
1510 1510
 			}
1511 1511
 			else
1512 1512
 			{
1513
-				$out.= '<option value="-1"'.(($showempty==2 || $multiple) ? '' : ' selected').' disabled>';
1514
-				$out.= ($socid != -1) ? ($langs->trans($socid?"NoContactDefinedForThirdParty":"NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
1515
-				$out.= '</option>';
1513
+				$out .= '<option value="-1"'.(($showempty == 2 || $multiple) ? '' : ' selected').' disabled>';
1514
+				$out .= ($socid != -1) ? ($langs->trans($socid ? "NoContactDefinedForThirdParty" : "NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
1515
+				$out .= '</option>';
1516 1516
 			}
1517 1517
 
1518 1518
 			$parameters = array(
@@ -1524,11 +1524,11 @@  discard block
 block discarded – undo
1524 1524
 				'showsoc'=>$showsoc,
1525 1525
 			);
1526 1526
 
1527
-			$reshook = $hookmanager->executeHooks( 'afterSelectContactOptions', $parameters, $this, $action );    // Note that $action and $object may have been modified by some hooks
1527
+			$reshook = $hookmanager->executeHooks('afterSelectContactOptions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1528 1528
 
1529 1529
 			if ($htmlname != 'none' || $options_only)
1530 1530
 			{
1531
-				$out.= '</select>';
1531
+				$out .= '</select>';
1532 1532
 			}
1533 1533
 
1534 1534
 			$this->num = $num;
@@ -1557,10 +1557,10 @@  discard block
 block discarded – undo
1557 1557
 	 *  @deprecated		Use select_dolusers instead
1558 1558
 	 *  @see select_dolusers()
1559 1559
 	 */
1560
-	function select_users($selected='',$htmlname='userid',$show_empty=0,$exclude=null,$disabled=0,$include='',$enableonly='',$force_entity='0')
1560
+	function select_users($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0')
1561 1561
 	{
1562 1562
         // phpcs:enable
1563
-		print $this->select_dolusers($selected,$htmlname,$show_empty,$exclude,$disabled,$include,$enableonly,$force_entity);
1563
+		print $this->select_dolusers($selected, $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity);
1564 1564
 	}
1565 1565
 
1566 1566
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -1587,81 +1587,81 @@  discard block
 block discarded – undo
1587 1587
 	 * 	@return	string					HTML select string
1588 1588
 	 *  @see select_dolgroups
1589 1589
 	 */
1590
-	function select_dolusers($selected='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $show_every=0, $enableonlytext='', $morecss='', $noactive=0, $outputmode=0, $multiple=false)
1590
+	function select_dolusers($selected = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $show_every = 0, $enableonlytext = '', $morecss = '', $noactive = 0, $outputmode = 0, $multiple = false)
1591 1591
 	{
1592 1592
         // phpcs:enable
1593
-		global $conf,$user,$langs;
1593
+		global $conf, $user, $langs;
1594 1594
 
1595 1595
 		// If no preselected user defined, we take current user
1596
-		if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;
1596
+		if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected = $user->id;
1597 1597
 
1598 1598
 		if ($selected === '') $selected = array();
1599 1599
 		else if (!is_array($selected)) $selected = array($selected);
1600 1600
 
1601
-		$excludeUsers=null;
1602
-		$includeUsers=null;
1601
+		$excludeUsers = null;
1602
+		$includeUsers = null;
1603 1603
 
1604 1604
 		// Permettre l'exclusion d'utilisateurs
1605
-		if (is_array($exclude))	$excludeUsers = implode(",",$exclude);
1605
+		if (is_array($exclude))	$excludeUsers = implode(",", $exclude);
1606 1606
 		// Permettre l'inclusion d'utilisateurs
1607
-		if (is_array($include))	$includeUsers = implode(",",$include);
1607
+		if (is_array($include))	$includeUsers = implode(",", $include);
1608 1608
 		else if ($include == 'hierarchy')
1609 1609
 		{
1610 1610
 			// Build list includeUsers to have only hierarchy
1611
-			$includeUsers = implode(",",$user->getAllChildIds(0));
1611
+			$includeUsers = implode(",", $user->getAllChildIds(0));
1612 1612
 		}
1613 1613
 		else if ($include == 'hierarchyme')
1614 1614
 		{
1615 1615
 			// Build list includeUsers to have only hierarchy and current user
1616
-			$includeUsers = implode(",",$user->getAllChildIds(1));
1616
+			$includeUsers = implode(",", $user->getAllChildIds(1));
1617 1617
 		}
1618 1618
 
1619
-		$out='';
1619
+		$out = '';
1620 1620
 		$outarray = array();
1621 1621
 
1622 1622
 		// Forge request to select users
1623 1623
 		$sql = "SELECT DISTINCT u.rowid, u.lastname as lastname, u.firstname, u.statut, u.login, u.admin, u.entity";
1624
-		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
1624
+		if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
1625 1625
 		{
1626
-			$sql.= ", e.label";
1626
+			$sql .= ", e.label";
1627 1627
 		}
1628
-		$sql.= " FROM ".MAIN_DB_PREFIX ."user as u";
1629
-		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
1628
+		$sql .= " FROM ".MAIN_DB_PREFIX."user as u";
1629
+		if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
1630 1630
 		{
1631
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity";
1632
-			if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")";
1633
-			else $sql.= " WHERE u.entity IS NOT NULL";
1631
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=u.entity";
1632
+			if ($force_entity) $sql .= " WHERE u.entity IN (0,".$force_entity.")";
1633
+			else $sql .= " WHERE u.entity IS NOT NULL";
1634 1634
 		}
1635 1635
 		else
1636 1636
 		{
1637
-			if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1637
+			if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1638 1638
 			{
1639
-				$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
1640
-				$sql.= " ON ug.fk_user = u.rowid";
1641
-				$sql.= " WHERE ug.entity = ".$conf->entity;
1639
+				$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
1640
+				$sql .= " ON ug.fk_user = u.rowid";
1641
+				$sql .= " WHERE ug.entity = ".$conf->entity;
1642 1642
 			}
1643 1643
 			else
1644 1644
 			{
1645
-				$sql.= " WHERE u.entity IN (0,".$conf->entity.")";
1645
+				$sql .= " WHERE u.entity IN (0,".$conf->entity.")";
1646 1646
 			}
1647 1647
 		}
1648
-		if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id;
1649
-		if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")";
1650
-		if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")";
1651
-		if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0";
1652
-		if (! empty($morefilter)) $sql.=" ".$morefilter;
1648
+		if (!empty($user->societe_id)) $sql .= " AND u.fk_soc = ".$user->societe_id;
1649
+		if (is_array($exclude) && $excludeUsers) $sql .= " AND u.rowid NOT IN (".$excludeUsers.")";
1650
+		if ($includeUsers) $sql .= " AND u.rowid IN (".$includeUsers.")";
1651
+		if (!empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql .= " AND u.statut <> 0";
1652
+		if (!empty($morefilter)) $sql .= " ".$morefilter;
1653 1653
 
1654 1654
 		if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))	// MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
1655 1655
 		{
1656
-			$sql.= " ORDER BY u.firstname ASC";
1656
+			$sql .= " ORDER BY u.firstname ASC";
1657 1657
 		}
1658 1658
 		else
1659 1659
 		{
1660
-			$sql.= " ORDER BY u.lastname ASC";
1660
+			$sql .= " ORDER BY u.lastname ASC";
1661 1661
 		}
1662 1662
 
1663 1663
 		dol_syslog(get_class($this)."::select_dolusers", LOG_DEBUG);
1664
-		$resql=$this->db->query($sql);
1664
+		$resql = $this->db->query($sql);
1665 1665
 		if ($resql)
1666 1666
 		{
1667 1667
 			$num = $this->db->num_rows($resql);
@@ -1669,38 +1669,38 @@  discard block
 block discarded – undo
1669 1669
 			if ($num)
1670 1670
 			{
1671 1671
 		   		// Enhance with select2
1672
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1672
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1673 1673
 				$out .= ajax_combobox($htmlname);
1674 1674
 
1675 1675
 				// do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
1676
-				$out.= '<select class="flat'.($morecss?' minwidth100 '.$morecss:' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
1677
-				if ($show_empty && !$multiple) $out.= '<option value="-1"'.((empty($selected) || in_array(-1,$selected))?' selected':'').'>&nbsp;</option>'."\n";
1678
-				if ($show_every) $out.= '<option value="-2"'.((in_array(-2,$selected))?' selected':'').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
1676
+				$out .= '<select class="flat'.($morecss ? ' minwidth100 '.$morecss : ' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
1677
+				if ($show_empty && !$multiple) $out .= '<option value="-1"'.((empty($selected) || in_array(-1, $selected)) ? ' selected' : '').'>&nbsp;</option>'."\n";
1678
+				if ($show_every) $out .= '<option value="-2"'.((in_array(-2, $selected)) ? ' selected' : '').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
1679 1679
 
1680
-				$userstatic=new User($this->db);
1680
+				$userstatic = new User($this->db);
1681 1681
 
1682 1682
 				while ($i < $num)
1683 1683
 				{
1684 1684
 					$obj = $this->db->fetch_object($resql);
1685 1685
 
1686
-					$userstatic->id=$obj->rowid;
1687
-					$userstatic->lastname=$obj->lastname;
1688
-					$userstatic->firstname=$obj->firstname;
1686
+					$userstatic->id = $obj->rowid;
1687
+					$userstatic->lastname = $obj->lastname;
1688
+					$userstatic->firstname = $obj->firstname;
1689 1689
 
1690
-					$disableline='';
1691
-					if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1');
1690
+					$disableline = '';
1691
+					if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) $disableline = ($enableonlytext ? $enableonlytext : '1');
1692 1692
 
1693
-					if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && in_array($obj->rowid,$selected) ))
1693
+					if ((is_object($selected) && $selected->id == $obj->rowid) || (!is_object($selected) && in_array($obj->rowid, $selected)))
1694 1694
 					{
1695
-						$out.= '<option value="'.$obj->rowid.'"';
1696
-						if ($disableline) $out.= ' disabled';
1697
-						$out.= ' selected>';
1695
+						$out .= '<option value="'.$obj->rowid.'"';
1696
+						if ($disableline) $out .= ' disabled';
1697
+						$out .= ' selected>';
1698 1698
 					}
1699 1699
 					else
1700 1700
 					{
1701
-						$out.= '<option value="'.$obj->rowid.'"';
1702
-						if ($disableline) $out.= ' disabled';
1703
-						$out.= '>';
1701
+						$out .= '<option value="'.$obj->rowid.'"';
1702
+						if ($disableline) $out .= ' disabled';
1703
+						$out .= '>';
1704 1704
 					}
1705 1705
 
1706 1706
 					// $fullNameMode is 0=Lastname+Firstname (MAIN_FIRSTNAME_NAME_POSITION=1), 1=Firstname+Lastname (MAIN_FIRSTNAME_NAME_POSITION=0)
@@ -1709,47 +1709,47 @@  discard block
 block discarded – undo
1709 1709
 					{
1710 1710
 						$fullNameMode = 1; //Firstname+lastname
1711 1711
 					}
1712
-					$out.= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
1712
+					$out .= $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
1713 1713
 
1714 1714
 					// Complete name with more info
1715
-					$moreinfo=0;
1716
-					if (! empty($conf->global->MAIN_SHOW_LOGIN))
1715
+					$moreinfo = 0;
1716
+					if (!empty($conf->global->MAIN_SHOW_LOGIN))
1717 1717
 					{
1718
-						$out.= ($moreinfo?' - ':' (').$obj->login;
1718
+						$out .= ($moreinfo ? ' - ' : ' (').$obj->login;
1719 1719
 						$moreinfo++;
1720 1720
 					}
1721 1721
 					if ($showstatus >= 0)
1722 1722
 					{
1723 1723
 						if ($obj->statut == 1 && $showstatus == 1)
1724 1724
 						{
1725
-							$out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
1725
+							$out .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
1726 1726
 							$moreinfo++;
1727 1727
 						}
1728 1728
 						if ($obj->statut == 0)
1729 1729
 						{
1730
-							$out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
1730
+							$out .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
1731 1731
 							$moreinfo++;
1732 1732
 						}
1733 1733
 					}
1734
-					if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && ! $user->entity)
1734
+					if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1 && $user->admin && !$user->entity)
1735 1735
 					{
1736
-						if (! $obj->entity)
1736
+						if (!$obj->entity)
1737 1737
 						{
1738
-							$out.=($moreinfo?' - ':' (').$langs->trans("AllEntities");
1738
+							$out .= ($moreinfo ? ' - ' : ' (').$langs->trans("AllEntities");
1739 1739
 							$moreinfo++;
1740 1740
 						}
1741 1741
 						else
1742 1742
 						{
1743
-							$out.=($moreinfo?' - ':' (').($obj->label?$obj->label:$langs->trans("EntityNameNotDefined"));
1743
+							$out .= ($moreinfo ? ' - ' : ' (').($obj->label ? $obj->label : $langs->trans("EntityNameNotDefined"));
1744 1744
 							$moreinfo++;
1745 1745
 					 	}
1746 1746
 					}
1747
-					$out.=($moreinfo?')':'');
1747
+					$out .= ($moreinfo ? ')' : '');
1748 1748
 					if ($disableline && $disableline != '1')
1749 1749
 					{
1750
-						$out.=' - '.$disableline;	// This is text from $enableonlytext parameter
1750
+						$out .= ' - '.$disableline; // This is text from $enableonlytext parameter
1751 1751
 					}
1752
-					$out.= '</option>';
1752
+					$out .= '</option>';
1753 1753
 					$outarray[$userstatic->id] = $userstatic->getFullName($langs, $fullNameMode, -1, $maxlength);
1754 1754
 
1755 1755
 					$i++;
@@ -1757,10 +1757,10 @@  discard block
 block discarded – undo
1757 1757
 			}
1758 1758
 			else
1759 1759
 			{
1760
-				$out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
1761
-				$out.= '<option value="">'.$langs->trans("None").'</option>';
1760
+				$out .= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
1761
+				$out .= '<option value="">'.$langs->trans("None").'</option>';
1762 1762
 			}
1763
-			$out.= '</select>';
1763
+			$out .= '</select>';
1764 1764
 		}
1765 1765
 		else
1766 1766
 		{
@@ -1795,67 +1795,67 @@  discard block
 block discarded – undo
1795 1795
 	 * 	@return	string					HTML select string
1796 1796
 	 *  @see select_dolgroups
1797 1797
 	 */
1798
-	function select_dolusers_forevent($action='', $htmlname='userid', $show_empty=0, $exclude=null, $disabled=0, $include='', $enableonly='', $force_entity='0', $maxlength=0, $showstatus=0, $morefilter='', $showproperties=0, $listofuserid=array(), $listofcontactid=array(), $listofotherid=array())
1798
+	function select_dolusers_forevent($action = '', $htmlname = 'userid', $show_empty = 0, $exclude = null, $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $maxlength = 0, $showstatus = 0, $morefilter = '', $showproperties = 0, $listofuserid = array(), $listofcontactid = array(), $listofotherid = array())
1799 1799
 	{
1800 1800
         // phpcs:enable
1801 1801
 		global $conf, $user, $langs;
1802 1802
 
1803
-		$userstatic=new User($this->db);
1804
-		$out='';
1803
+		$userstatic = new User($this->db);
1804
+		$out = '';
1805 1805
 
1806 1806
 		// Method with no ajax
1807 1807
 		//$out.='<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
1808 1808
 		if ($action == 'view')
1809 1809
 		{
1810
-			$out.='';
1810
+			$out .= '';
1811 1811
 		}
1812 1812
 		else
1813 1813
 		{
1814
-			$out.='<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
1815
-			$out.='<script type="text/javascript" language="javascript">jQuery(document).ready(function () {    jQuery(".removedassigned").click(function() {        jQuery(".removedassignedhidden").val(jQuery(this).val());    });})</script>';
1816
-			$out.=$this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
1817
-			$out.=' <input type="submit" class="button valignmiddle" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
1818
-			$out.='<br>';
1814
+			$out .= '<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
1815
+			$out .= '<script type="text/javascript" language="javascript">jQuery(document).ready(function () {    jQuery(".removedassigned").click(function() {        jQuery(".removedassignedhidden").val(jQuery(this).val());    });})</script>';
1816
+			$out .= $this->select_dolusers('', $htmlname, $show_empty, $exclude, $disabled, $include, $enableonly, $force_entity, $maxlength, $showstatus, $morefilter);
1817
+			$out .= ' <input type="submit" class="button valignmiddle" name="'.$action.'assignedtouser" value="'.dol_escape_htmltag($langs->trans("Add")).'">';
1818
+			$out .= '<br>';
1819 1819
 		}
1820
-		$assignedtouser=array();
1820
+		$assignedtouser = array();
1821 1821
 		if (!empty($_SESSION['assignedtouser']))
1822 1822
 		{
1823
-			$assignedtouser=json_decode($_SESSION['assignedtouser'], true);
1823
+			$assignedtouser = json_decode($_SESSION['assignedtouser'], true);
1824 1824
 		}
1825
-		$nbassignetouser=count($assignedtouser);
1825
+		$nbassignetouser = count($assignedtouser);
1826 1826
 
1827
-		if ($nbassignetouser && $action != 'view') $out.='<br>';
1828
-		if ($nbassignetouser) $out.='<ul class="attendees">';
1829
-		$i=0; $ownerid=0;
1830
-		foreach($assignedtouser as $key => $value)
1827
+		if ($nbassignetouser && $action != 'view') $out .= '<br>';
1828
+		if ($nbassignetouser) $out .= '<ul class="attendees">';
1829
+		$i = 0; $ownerid = 0;
1830
+		foreach ($assignedtouser as $key => $value)
1831 1831
 		{
1832 1832
 			if ($value['id'] == $ownerid) continue;
1833 1833
 
1834
-			$out.='<li>';
1834
+			$out .= '<li>';
1835 1835
 			$userstatic->fetch($value['id']);
1836
-			$out.= $userstatic->getNomUrl(-1);
1837
-			if ($i == 0) { $ownerid = $value['id']; $out.=' ('.$langs->trans("Owner").')'; }
1836
+			$out .= $userstatic->getNomUrl(-1);
1837
+			if ($i == 0) { $ownerid = $value['id']; $out .= ' ('.$langs->trans("Owner").')'; }
1838 1838
 			if ($nbassignetouser > 1 && $action != 'view')
1839 1839
 			{
1840
-				$out.=' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
1840
+				$out .= ' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Remove"), 'delete', '', 0, 1).'" value="'.$userstatic->id.'" class="removedassigned" id="removedassigned_'.$userstatic->id.'" name="removedassigned_'.$userstatic->id.'">';
1841 1841
 			}
1842 1842
 			// Show my availability
1843 1843
 			if ($showproperties)
1844 1844
 			{
1845 1845
 				if ($ownerid == $value['id'] && is_array($listofuserid) && count($listofuserid) && in_array($ownerid, array_keys($listofuserid)))
1846 1846
 				{
1847
-					$out.='<div class="myavailability inline-block">';
1848
-					$out.='&nbsp;-&nbsp;<span class="opacitymedium">'.$langs->trans("Availability").':</span>  <input id="transparency" class="marginleftonly marginrightonly" '.($action == 'view'?'disabled':'').' type="checkbox" name="transparency"'.($listofuserid[$ownerid]['transparency']?' checked':'').'>'.$langs->trans("Busy");
1849
-					$out.='</div>';
1847
+					$out .= '<div class="myavailability inline-block">';
1848
+					$out .= '&nbsp;-&nbsp;<span class="opacitymedium">'.$langs->trans("Availability").':</span>  <input id="transparency" class="marginleftonly marginrightonly" '.($action == 'view' ? 'disabled' : '').' type="checkbox" name="transparency"'.($listofuserid[$ownerid]['transparency'] ? ' checked' : '').'>'.$langs->trans("Busy");
1849
+					$out .= '</div>';
1850 1850
 				}
1851 1851
 			}
1852 1852
 			//$out.=' '.($value['mandatory']?$langs->trans("Mandatory"):$langs->trans("Optional"));
1853 1853
 			//$out.=' '.($value['transparency']?$langs->trans("Busy"):$langs->trans("NotBusy"));
1854 1854
 
1855
-			$out.='</li>';
1855
+			$out .= '</li>';
1856 1856
 			$i++;
1857 1857
 		}
1858
-		if ($nbassignetouser) $out.='</ul>';
1858
+		if ($nbassignetouser) $out .= '</ul>';
1859 1859
 
1860 1860
 		//$out.='</form>';
1861 1861
 		return $out;
@@ -1888,30 +1888,30 @@  discard block
 block discarded – undo
1888 1888
 	 *  @param 		array 		$selected_combinations 	Selected combinations. Format: array([attrid] => attrval, [...])
1889 1889
 	 *  @return		void
1890 1890
 	 */
1891
-	function select_produits($selected='', $htmlname='productid', $filtertype='', $limit=20, $price_level=0, $status=1, $finished=2, $selected_input_value='', $hidelabel=0, $ajaxoptions=array(), $socid=0, $showempty='1', $forcecombo=0, $morecss='', $hidepriceinlabel=0, $warehouseStatus='', $selected_combinations = array())
1891
+	function select_produits($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $price_level = 0, $status = 1, $finished = 2, $selected_input_value = '', $hidelabel = 0, $ajaxoptions = array(), $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '', $selected_combinations = array())
1892 1892
 	{
1893 1893
         // phpcs:enable
1894
-		global $langs,$conf;
1894
+		global $langs, $conf;
1895 1895
 
1896
-		$price_level = (! empty($price_level) ? $price_level : 0);
1896
+		$price_level = (!empty($price_level) ? $price_level : 0);
1897 1897
 
1898
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
1898
+		if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
1899 1899
 		{
1900
-			$placeholder='';
1900
+			$placeholder = '';
1901 1901
 
1902 1902
 			if ($selected && empty($selected_input_value))
1903 1903
 			{
1904 1904
 				require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1905 1905
 				$producttmpselect = new Product($this->db);
1906 1906
 				$producttmpselect->fetch($selected);
1907
-				$selected_input_value=$producttmpselect->ref;
1907
+				$selected_input_value = $producttmpselect->ref;
1908 1908
 				unset($producttmpselect);
1909 1909
 			}
1910 1910
 			// mode=1 means customers products
1911
-			$urloption='htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
1911
+			$urloption = 'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=1&status='.$status.'&finished='.$finished.'&hidepriceinlabel='.$hidepriceinlabel.'&warehousestatus='.$warehouseStatus;
1912 1912
 			//Price by customer
1913
-			if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
1914
-				$urloption.='&socid='.$socid;
1913
+			if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
1914
+				$urloption .= '&socid='.$socid;
1915 1915
 			}
1916 1916
 			print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1917 1917
 
@@ -1990,7 +1990,7 @@  discard block
 block discarded – undo
1990 1990
 			}
1991 1991
 			if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
1992 1992
 			else if ($hidelabel > 1) {
1993
-				$placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
1993
+				$placeholder = ' placeholder="'.$langs->trans("RefOrLabel").'"';
1994 1994
 				if ($hidelabel == 2) {
1995 1995
 					print img_picto($langs->trans("Search"), 'search');
1996 1996
 				}
@@ -2002,7 +2002,7 @@  discard block
 block discarded – undo
2002 2002
 		}
2003 2003
 		else
2004 2004
 		{
2005
-			print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus);
2005
+			print $this->select_produits_list($selected, $htmlname, $filtertype, $limit, $price_level, '', $status, $finished, 0, $socid, $showempty, $forcecombo, $morecss, $hidepriceinlabel, $warehouseStatus);
2006 2006
 		}
2007 2007
 	}
2008 2008
 
@@ -2030,16 +2030,16 @@  discard block
 block discarded – undo
2030 2030
 	 *										    'warehouseinternal' = select products from warehouses for internal correct/transfer only
2031 2031
 	 *  @return     array    				    Array of keys for json
2032 2032
 	 */
2033
-	function select_produits_list($selected='',$htmlname='productid',$filtertype='',$limit=20,$price_level=0,$filterkey='',$status=1,$finished=2,$outputmode=0,$socid=0,$showempty='1',$forcecombo=0,$morecss='',$hidepriceinlabel=0, $warehouseStatus='')
2033
+	function select_produits_list($selected = '', $htmlname = 'productid', $filtertype = '', $limit = 20, $price_level = 0, $filterkey = '', $status = 1, $finished = 2, $outputmode = 0, $socid = 0, $showempty = '1', $forcecombo = 0, $morecss = '', $hidepriceinlabel = 0, $warehouseStatus = '')
2034 2034
 	{
2035 2035
         // phpcs:enable
2036
-		global $langs,$conf,$user,$db;
2036
+		global $langs, $conf, $user, $db;
2037 2037
 
2038
-		$out='';
2039
-		$outarray=array();
2038
+		$out = '';
2039
+		$outarray = array();
2040 2040
 
2041 2041
 		$warehouseStatusArray = array();
2042
-		if (! empty($warehouseStatus))
2042
+		if (!empty($warehouseStatus))
2043 2043
 		{
2044 2044
 			require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
2045 2045
 			if (preg_match('/warehouseclosed/', $warehouseStatus))
@@ -2060,12 +2060,12 @@  discard block
 block discarded – undo
2060 2060
 		(count($warehouseStatusArray)) ? $selectFieldsGrouped = ", sum(ps.reel) as stock" : $selectFieldsGrouped = ", p.stock";
2061 2061
 
2062 2062
 		$sql = "SELECT ";
2063
-		$sql.= $selectFields . $selectFieldsGrouped;
2063
+		$sql .= $selectFields.$selectFieldsGrouped;
2064 2064
 
2065
-		if (! empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
2065
+		if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
2066 2066
 		{
2067 2067
 			//Product category
2068
-			$sql.= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie
2068
+			$sql .= ", (SELECT ".MAIN_DB_PREFIX."categorie_product.fk_categorie
2069 2069
 						FROM ".MAIN_DB_PREFIX."categorie_product
2070 2070
 						WHERE ".MAIN_DB_PREFIX."categorie_product.fk_product=p.rowid
2071 2071
 						LIMIT 1
@@ -2073,63 +2073,63 @@  discard block
 block discarded – undo
2073 2073
 		}
2074 2074
 
2075 2075
 		//Price by customer
2076
-		if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid))
2076
+		if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid))
2077 2077
 		{
2078
-			$sql.=', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
2079
-			$sql.=' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
2080
-			$selectFields.= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx";
2078
+			$sql .= ', pcp.rowid as idprodcustprice, pcp.price as custprice, pcp.price_ttc as custprice_ttc,';
2079
+			$sql .= ' pcp.price_base_type as custprice_base_type, pcp.tva_tx as custtva_tx';
2080
+			$selectFields .= ", idprodcustprice, custprice, custprice_ttc, custprice_base_type, custtva_tx";
2081 2081
 		}
2082 2082
 
2083 2083
 		// Multilang : we add translation
2084
-		if (! empty($conf->global->MAIN_MULTILANGS))
2084
+		if (!empty($conf->global->MAIN_MULTILANGS))
2085 2085
 		{
2086
-			$sql.= ", pl.label as label_translated";
2087
-			$selectFields.= ", label_translated";
2086
+			$sql .= ", pl.label as label_translated";
2087
+			$selectFields .= ", label_translated";
2088 2088
 		}
2089 2089
 		// Price by quantity
2090
-		if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
2091
-		{
2092
-			$sql.= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
2093
-			if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
2094
-			$sql.= " ORDER BY date_price";
2095
-			$sql.= " DESC LIMIT 1) as price_rowid";
2096
-			$sql.= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";	// price_by_qty is 1 if some prices by qty exists in subtable
2097
-			if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
2098
-			$sql.= " ORDER BY date_price";
2099
-			$sql.= " DESC LIMIT 1) as price_by_qty";
2100
-			$selectFields.= ", price_rowid, price_by_qty";
2101
-		}
2102
-		$sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2090
+		if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
2091
+		{
2092
+			$sql .= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
2093
+			if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql .= " AND price_level=".$price_level;
2094
+			$sql .= " ORDER BY date_price";
2095
+			$sql .= " DESC LIMIT 1) as price_rowid";
2096
+			$sql .= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid"; // price_by_qty is 1 if some prices by qty exists in subtable
2097
+			if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql .= " AND price_level=".$price_level;
2098
+			$sql .= " ORDER BY date_price";
2099
+			$sql .= " DESC LIMIT 1) as price_by_qty";
2100
+			$selectFields .= ", price_rowid, price_by_qty";
2101
+		}
2102
+		$sql .= " FROM ".MAIN_DB_PREFIX."product as p";
2103 2103
 		if (count($warehouseStatusArray))
2104 2104
 		{
2105
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
2106
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid";
2105
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as ps on ps.fk_product = p.rowid";
2106
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e on ps.fk_entrepot = e.rowid";
2107 2107
 		}
2108 2108
 
2109 2109
 		// include search in supplier ref
2110
-		if(!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF))
2110
+		if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF))
2111 2111
 		{
2112
-            $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2112
+            $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2113 2113
 		}
2114 2114
 
2115 2115
 		//Price by customer
2116
-		if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
2117
-			$sql.=" LEFT JOIN  ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
2116
+		if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && !empty($socid)) {
2117
+			$sql .= " LEFT JOIN  ".MAIN_DB_PREFIX."product_customer_price as pcp ON pcp.fk_soc=".$socid." AND pcp.fk_product=p.rowid";
2118 2118
 		}
2119 2119
 		// Multilang : we add translation
2120
-		if (! empty($conf->global->MAIN_MULTILANGS))
2120
+		if (!empty($conf->global->MAIN_MULTILANGS))
2121 2121
 		{
2122
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='". $langs->getDefaultLang() ."'";
2122
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_lang as pl ON pl.fk_product = p.rowid AND pl.lang='".$langs->getDefaultLang()."'";
2123 2123
 		}
2124 2124
 
2125 2125
 		if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
2126 2126
 			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac.fk_product_child = p.rowid";
2127 2127
 		}
2128 2128
 
2129
-		$sql.= ' WHERE p.entity IN ('.getEntity('product').')';
2129
+		$sql .= ' WHERE p.entity IN ('.getEntity('product').')';
2130 2130
 		if (count($warehouseStatusArray))
2131 2131
 		{
2132
-			$sql.= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',',$warehouseStatusArray)).'))';
2132
+			$sql .= ' AND (p.fk_product_type = 1 OR e.statut IN ('.$this->db->escape(implode(',', $warehouseStatusArray)).'))';
2133 2133
 		}
2134 2134
 
2135 2135
 		if (!empty($conf->global->PRODUIT_ATTRIBUTES_HIDECHILD)) {
@@ -2138,92 +2138,92 @@  discard block
 block discarded – undo
2138 2138
 
2139 2139
 		if ($finished == 0)
2140 2140
 		{
2141
-			$sql.= " AND p.finished = ".$finished;
2141
+			$sql .= " AND p.finished = ".$finished;
2142 2142
 		}
2143 2143
 		elseif ($finished == 1)
2144 2144
 		{
2145
-			$sql.= " AND p.finished = ".$finished;
2146
-			if ($status >= 0)  $sql.= " AND p.tosell = ".$status;
2145
+			$sql .= " AND p.finished = ".$finished;
2146
+			if ($status >= 0)  $sql .= " AND p.tosell = ".$status;
2147 2147
 		}
2148 2148
 		elseif ($status >= 0)
2149 2149
 		{
2150
-			$sql.= " AND p.tosell = ".$status;
2150
+			$sql .= " AND p.tosell = ".$status;
2151 2151
 		}
2152
-		if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype;
2152
+		if (strval($filtertype) != '') $sql .= " AND p.fk_product_type=".$filtertype;
2153 2153
 		// Add criteria on ref/label
2154 2154
 		if ($filterkey != '')
2155 2155
 		{
2156
-			$sql.=' AND (';
2157
-			$prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2156
+			$sql .= ' AND (';
2157
+			$prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2158 2158
 			// For natural search
2159 2159
 			$scrit = explode(' ', $filterkey);
2160
-			$i=0;
2161
-			if (count($scrit) > 1) $sql.="(";
2160
+			$i = 0;
2161
+			if (count($scrit) > 1) $sql .= "(";
2162 2162
 			foreach ($scrit as $crit)
2163 2163
 			{
2164
-				if ($i > 0) $sql.=" AND ";
2165
-				$sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'";
2166
-				if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
2164
+				if ($i > 0) $sql .= " AND ";
2165
+				$sql .= "(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'";
2166
+				if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
2167 2167
 				if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION))
2168 2168
 				{
2169
-					$sql.=" OR p.description LIKE '".$db->escape($prefix.$crit)."%'";
2170
-					if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.description LIKE '".$db->escape($prefix.$crit)."%'";
2169
+					$sql .= " OR p.description LIKE '".$db->escape($prefix.$crit)."%'";
2170
+					if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " OR pl.description LIKE '".$db->escape($prefix.$crit)."%'";
2171 2171
 				}
2172
-				if (! empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql.=" OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'";
2173
-				$sql.=")";
2172
+				if (!empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql .= " OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'";
2173
+				$sql .= ")";
2174 2174
 				$i++;
2175 2175
 			}
2176
-			if (count($scrit) > 1) $sql.=")";
2177
-		  	if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
2178
-			$sql.=')';
2176
+			if (count($scrit) > 1) $sql .= ")";
2177
+		  	if (!empty($conf->barcode->enabled)) $sql .= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
2178
+			$sql .= ')';
2179 2179
 		}
2180 2180
 		if (count($warehouseStatusArray))
2181 2181
 		{
2182
-			$sql.= ' GROUP BY'.$selectFields;
2182
+			$sql .= ' GROUP BY'.$selectFields;
2183 2183
 		}
2184 2184
 
2185 2185
 		//Sort by category
2186
-		if(! empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
2186
+		if (!empty($conf->global->PRODUCT_SORT_BY_CATEGORY))
2187 2187
 		{
2188 2188
 			$sql .= " ORDER BY categorie_product_id ";
2189 2189
 			//ASC OR DESC order
2190
-			($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .="ASC" : $sql .="DESC";
2190
+			($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .= "ASC" : $sql .= "DESC";
2191 2191
 		}
2192 2192
 		else
2193 2193
 		{
2194
-			$sql.= $db->order("p.ref");
2194
+			$sql .= $db->order("p.ref");
2195 2195
 		}
2196 2196
 
2197
-		$sql.= $db->plimit($limit, 0);
2197
+		$sql .= $db->plimit($limit, 0);
2198 2198
 
2199 2199
 		// Build output string
2200 2200
 		dol_syslog(get_class($this)."::select_produits_list search product", LOG_DEBUG);
2201
-		$result=$this->db->query($sql);
2201
+		$result = $this->db->query($sql);
2202 2202
 		if ($result)
2203 2203
 		{
2204 2204
 			require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2205 2205
 			require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2206 2206
 			$num = $this->db->num_rows($result);
2207 2207
 
2208
-			$events=null;
2208
+			$events = null;
2209 2209
 
2210
-			if (! $forcecombo)
2210
+			if (!$forcecombo)
2211 2211
 			{
2212
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2212
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
2213 2213
 				$out .= ajax_combobox($htmlname, $events, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT);
2214 2214
 			}
2215 2215
 
2216
-			$out.='<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
2216
+			$out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
2217 2217
 
2218
-			$textifempty='';
2218
+			$textifempty = '';
2219 2219
 			// Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
2220 2220
 			//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
2221
-			if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2221
+			if (!empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2222 2222
 			{
2223
-				if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
2224
-				else $textifempty.=$langs->trans("All");
2223
+				if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
2224
+				else $textifempty .= $langs->trans("All");
2225 2225
 			}
2226
-			if ($showempty) $out.='<option value="0" selected>'.$textifempty.'</option>';
2226
+			if ($showempty) $out .= '<option value="0" selected>'.$textifempty.'</option>';
2227 2227
 
2228 2228
 			$i = 0;
2229 2229
 			while ($num && $i < $num)
@@ -2235,9 +2235,9 @@  discard block
 block discarded – undo
2235 2235
 				if ((!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1)
2236 2236
 				{ // Price by quantity will return many prices for the same product
2237 2237
 					$sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise, price_base_type";
2238
-					$sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
2239
-					$sql.= " WHERE fk_product_price=".$objp->price_rowid;
2240
-					$sql.= " ORDER BY quantity ASC";
2238
+					$sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
2239
+					$sql .= " WHERE fk_product_price=".$objp->price_rowid;
2240
+					$sql .= " ORDER BY quantity ASC";
2241 2241
 
2242 2242
 					dol_syslog(get_class($this)."::select_produits_list search price by qty", LOG_DEBUG);
2243 2243
 					$result2 = $this->db->query($sql);
@@ -2267,7 +2267,7 @@  discard block
 block discarded – undo
2267 2267
 							// Add new entry
2268 2268
 							// "key" value of json key array is used by jQuery automatically as selected value
2269 2269
 							// "label" value of json key array is used by jQuery automatically as text for combo box
2270
-							$out.=$opt;
2270
+							$out .= $opt;
2271 2271
 							array_push($outarray, $optJson);
2272 2272
 						}
2273 2273
 					}
@@ -2284,21 +2284,21 @@  discard block
 block discarded – undo
2284 2284
 							$objp->unitprice = $price_result;
2285 2285
 							//Calculate the VAT
2286 2286
 							$objp->price_ttc = price2num($objp->price) * (1 + ($objp->tva_tx / 100));
2287
-							$objp->price_ttc = price2num($objp->price_ttc,'MU');
2287
+							$objp->price_ttc = price2num($objp->price_ttc, 'MU');
2288 2288
 						}
2289 2289
 					}
2290 2290
 					$this->constructProductListOption($objp, $opt, $optJson, $price_level, $selected, $hidepriceinlabel);
2291 2291
 					// Add new entry
2292 2292
 					// "key" value of json key array is used by jQuery automatically as selected value
2293 2293
 					// "label" value of json key array is used by jQuery automatically as text for combo box
2294
-					$out.=$opt;
2294
+					$out .= $opt;
2295 2295
 					array_push($outarray, $optJson);
2296 2296
 				}
2297 2297
 
2298 2298
 				$i++;
2299 2299
 			}
2300 2300
 
2301
-			$out.='</select>';
2301
+			$out .= '</select>';
2302 2302
 
2303 2303
 			$this->db->free($result);
2304 2304
 
@@ -2322,75 +2322,75 @@  discard block
 block discarded – undo
2322 2322
 	 * @param   int         $hidepriceinlabel   Hide price in label
2323 2323
 	 * @return	void
2324 2324
 	 */
2325
-	private function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel=0)
2325
+	private function constructProductListOption(&$objp, &$opt, &$optJson, $price_level, $selected, $hidepriceinlabel = 0)
2326 2326
 	{
2327
-		global $langs,$conf,$user,$db;
2328
-
2329
-		$outkey='';
2330
-		$outval='';
2331
-		$outref='';
2332
-		$outlabel='';
2333
-		$outdesc='';
2334
-		$outbarcode='';
2335
-		$outtype='';
2336
-		$outprice_ht='';
2337
-		$outprice_ttc='';
2338
-		$outpricebasetype='';
2339
-		$outtva_tx='';
2340
-		$outqty=1;
2341
-		$outdiscount=0;
2342
-
2343
-		$maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO);
2344
-
2345
-		$label=$objp->label;
2346
-		if (! empty($objp->label_translated)) $label=$objp->label_translated;
2347
-		if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
2348
-
2349
-		$outkey=$objp->rowid;
2350
-		$outref=$objp->ref;
2351
-		$outlabel=$objp->label;
2352
-		$outdesc=$objp->description;
2353
-		$outbarcode=$objp->barcode;
2354
-
2355
-		$outtype=$objp->fk_product_type;
2356
-		$outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
2357
-		$outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
2327
+		global $langs, $conf, $user, $db;
2328
+
2329
+		$outkey = '';
2330
+		$outval = '';
2331
+		$outref = '';
2332
+		$outlabel = '';
2333
+		$outdesc = '';
2334
+		$outbarcode = '';
2335
+		$outtype = '';
2336
+		$outprice_ht = '';
2337
+		$outprice_ttc = '';
2338
+		$outpricebasetype = '';
2339
+		$outtva_tx = '';
2340
+		$outqty = 1;
2341
+		$outdiscount = 0;
2342
+
2343
+		$maxlengtharticle = (empty($conf->global->PRODUCT_MAX_LENGTH_COMBO) ? 48 : $conf->global->PRODUCT_MAX_LENGTH_COMBO);
2344
+
2345
+		$label = $objp->label;
2346
+		if (!empty($objp->label_translated)) $label = $objp->label_translated;
2347
+		if (!empty($filterkey) && $filterkey != '') $label = preg_replace('/('.preg_quote($filterkey).')/i', '<strong>$1</strong>', $label, 1);
2348
+
2349
+		$outkey = $objp->rowid;
2350
+		$outref = $objp->ref;
2351
+		$outlabel = $objp->label;
2352
+		$outdesc = $objp->description;
2353
+		$outbarcode = $objp->barcode;
2354
+
2355
+		$outtype = $objp->fk_product_type;
2356
+		$outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
2357
+		$outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
2358 2358
 
2359 2359
 		$opt = '<option value="'.$objp->rowid.'"';
2360
-		$opt.= ($objp->rowid == $selected)?' selected':'';
2360
+		$opt .= ($objp->rowid == $selected) ? ' selected' : '';
2361 2361
 		if (!empty($objp->price_by_qty_rowid) && $objp->price_by_qty_rowid > 0)
2362 2362
 		{
2363
-			$opt.= ' pbq="'.$objp->price_by_qty_rowid.'" data-pbq="'.$objp->price_by_qty_rowid.'" data-pbqqty="'.$objp->price_by_qty_quantity.'" data-pbqpercent="'.$objp->price_by_qty_remise_percent.'"';
2363
+			$opt .= ' pbq="'.$objp->price_by_qty_rowid.'" data-pbq="'.$objp->price_by_qty_rowid.'" data-pbqqty="'.$objp->price_by_qty_quantity.'" data-pbqpercent="'.$objp->price_by_qty_remise_percent.'"';
2364 2364
 		}
2365
-		if (! empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))
2365
+		if (!empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))
2366 2366
 		{
2367
-			if ($objp->stock > 0) $opt.= ' class="product_line_stock_ok"';
2368
-			else if ($objp->stock <= 0) $opt.= ' class="product_line_stock_too_low"';
2367
+			if ($objp->stock > 0) $opt .= ' class="product_line_stock_ok"';
2368
+			else if ($objp->stock <= 0) $opt .= ' class="product_line_stock_too_low"';
2369 2369
 		}
2370
-		$opt.= '>';
2371
-		$opt.= $objp->ref;
2372
-		if ($outbarcode) $opt.=' ('.$outbarcode.')';
2373
-		$opt.=' - '.dol_trunc($label,$maxlengtharticle);
2370
+		$opt .= '>';
2371
+		$opt .= $objp->ref;
2372
+		if ($outbarcode) $opt .= ' ('.$outbarcode.')';
2373
+		$opt .= ' - '.dol_trunc($label, $maxlengtharticle);
2374 2374
 
2375 2375
 		$objRef = $objp->ref;
2376
-		if (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2377
-		$outval.=$objRef;
2378
-		if ($outbarcode) $outval.=' ('.$outbarcode.')';
2379
-		$outval.=' - '.dol_trunc($label,$maxlengtharticle);
2376
+		if (!empty($filterkey) && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey).')/i', '<strong>$1</strong>', $objRef, 1);
2377
+		$outval .= $objRef;
2378
+		if ($outbarcode) $outval .= ' ('.$outbarcode.')';
2379
+		$outval .= ' - '.dol_trunc($label, $maxlengtharticle);
2380 2380
 
2381
-		$found=0;
2381
+		$found = 0;
2382 2382
 
2383 2383
 		// Multiprice
2384 2384
 		// If we need a particular price level (from 1 to 6)
2385
-		if (empty($hidepriceinlabel) && $price_level >= 1 && (! empty($conf->global->PRODUIT_MULTIPRICES) || ! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
2385
+		if (empty($hidepriceinlabel) && $price_level >= 1 && (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
2386 2386
 		{
2387 2387
 			$sql = "SELECT price, price_ttc, price_base_type, tva_tx";
2388
-			$sql.= " FROM ".MAIN_DB_PREFIX."product_price";
2389
-			$sql.= " WHERE fk_product='".$objp->rowid."'";
2390
-			$sql.= " AND entity IN (".getEntity('productprice').")";
2391
-			$sql.= " AND price_level=".$price_level;
2392
-			$sql.= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
2393
-			$sql.= " LIMIT 1";
2388
+			$sql .= " FROM ".MAIN_DB_PREFIX."product_price";
2389
+			$sql .= " WHERE fk_product='".$objp->rowid."'";
2390
+			$sql .= " AND entity IN (".getEntity('productprice').")";
2391
+			$sql .= " AND price_level=".$price_level;
2392
+			$sql .= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
2393
+			$sql .= " LIMIT 1";
2394 2394
 
2395 2395
 			dol_syslog(get_class($this).'::constructProductListOption search price for level '.$price_level.'', LOG_DEBUG);
2396 2396
 			$result2 = $this->db->query($sql);
@@ -2399,21 +2399,21 @@  discard block
 block discarded – undo
2399 2399
 				$objp2 = $this->db->fetch_object($result2);
2400 2400
 				if ($objp2)
2401 2401
 				{
2402
-					$found=1;
2402
+					$found = 1;
2403 2403
 					if ($objp2->price_base_type == 'HT')
2404 2404
 					{
2405
-						$opt.= ' - '.price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2406
-						$outval.= ' - '.price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2405
+						$opt .= ' - '.price($objp2->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
2406
+						$outval .= ' - '.price($objp2->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
2407 2407
 					}
2408 2408
 					else
2409 2409
 					{
2410
-						$opt.= ' - '.price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2411
-						$outval.= ' - '.price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2410
+						$opt .= ' - '.price($objp2->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
2411
+						$outval .= ' - '.price($objp2->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
2412 2412
 					}
2413
-					$outprice_ht=price($objp2->price);
2414
-					$outprice_ttc=price($objp2->price_ttc);
2415
-					$outpricebasetype=$objp2->price_base_type;
2416
-					$outtva_tx=$objp2->tva_tx;
2413
+					$outprice_ht = price($objp2->price);
2414
+					$outprice_ttc = price($objp2->price_ttc);
2415
+					$outpricebasetype = $objp2->price_base_type;
2416
+					$outtva_tx = $objp2->tva_tx;
2417 2417
 				}
2418 2418
 			}
2419 2419
 			else
@@ -2423,40 +2423,40 @@  discard block
 block discarded – undo
2423 2423
 		}
2424 2424
 
2425 2425
 		// Price by quantity
2426
-		if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
2426
+		if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1 && (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)))
2427 2427
 		{
2428 2428
 			$found = 1;
2429
-			$outqty=$objp->quantity;
2430
-			$outdiscount=$objp->remise_percent;
2429
+			$outqty = $objp->quantity;
2430
+			$outdiscount = $objp->remise_percent;
2431 2431
 			if ($objp->quantity == 1)
2432 2432
 			{
2433
-				$opt.= ' - '.price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/";
2434
-				$outval.= ' - '.price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/";
2435
-				$opt.= $langs->trans("Unit");	// Do not use strtolower because it breaks utf8 encoding
2436
-				$outval.=$langs->transnoentities("Unit");
2433
+				$opt .= ' - '.price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
2434
+				$outval .= ' - '.price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
2435
+				$opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
2436
+				$outval .= $langs->transnoentities("Unit");
2437 2437
 			}
2438 2438
 			else
2439 2439
 			{
2440
-				$opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2441
-				$outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2442
-				$opt.= $langs->trans("Units");	// Do not use strtolower because it breaks utf8 encoding
2443
-				$outval.=$langs->transnoentities("Units");
2440
+				$opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
2441
+				$outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
2442
+				$opt .= $langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
2443
+				$outval .= $langs->transnoentities("Units");
2444 2444
 			}
2445 2445
 
2446
-			$outprice_ht=price($objp->unitprice);
2447
-			$outprice_ttc=price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
2448
-			$outpricebasetype=$objp->price_base_type;
2449
-			$outtva_tx=$objp->tva_tx;
2446
+			$outprice_ht = price($objp->unitprice);
2447
+			$outprice_ttc = price($objp->unitprice * (1 + ($objp->tva_tx / 100)));
2448
+			$outpricebasetype = $objp->price_base_type;
2449
+			$outtva_tx = $objp->tva_tx;
2450 2450
 		}
2451 2451
 		if (empty($hidepriceinlabel) && !empty($objp->quantity) && $objp->quantity >= 1)
2452 2452
 		{
2453
-			$opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2454
-			$outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2453
+			$opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
2454
+			$outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
2455 2455
 		}
2456 2456
 		if (empty($hidepriceinlabel) && !empty($objp->remise_percent) && $objp->remise_percent >= 1)
2457 2457
 		{
2458
-			$opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
2459
-			$outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
2458
+			$opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
2459
+			$outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
2460 2460
 		}
2461 2461
 
2462 2462
 		// Price by customer
@@ -2468,64 +2468,64 @@  discard block
 block discarded – undo
2468 2468
 
2469 2469
 				if ($objp->custprice_base_type == 'HT')
2470 2470
 				{
2471
-					$opt.= ' - '.price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2472
-					$outval.= ' - '.price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2471
+					$opt .= ' - '.price($objp->custprice, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
2472
+					$outval .= ' - '.price($objp->custprice, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
2473 2473
 				}
2474 2474
 				else
2475 2475
 				{
2476
-					$opt.= ' - '.price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2477
-					$outval.= ' - '.price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2476
+					$opt .= ' - '.price($objp->custprice_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
2477
+					$outval .= ' - '.price($objp->custprice_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
2478 2478
 				}
2479 2479
 
2480
-				$outprice_ht=price($objp->custprice);
2481
-				$outprice_ttc=price($objp->custprice_ttc);
2482
-				$outpricebasetype=$objp->custprice_base_type;
2483
-				$outtva_tx=$objp->custtva_tx;
2480
+				$outprice_ht = price($objp->custprice);
2481
+				$outprice_ttc = price($objp->custprice_ttc);
2482
+				$outpricebasetype = $objp->custprice_base_type;
2483
+				$outtva_tx = $objp->custtva_tx;
2484 2484
 			}
2485 2485
 		}
2486 2486
 
2487 2487
 		// If level no defined or multiprice not found, we used the default price
2488
-		if (empty($hidepriceinlabel) && ! $found)
2488
+		if (empty($hidepriceinlabel) && !$found)
2489 2489
 		{
2490 2490
 			if ($objp->price_base_type == 'HT')
2491 2491
 			{
2492
-				$opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2493
-				$outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2492
+				$opt .= ' - '.price($objp->price, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("HT");
2493
+				$outval .= ' - '.price($objp->price, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("HT");
2494 2494
 			}
2495 2495
 			else
2496 2496
 			{
2497
-				$opt.= ' - '.price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2498
-				$outval.= ' - '.price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
2497
+				$opt .= ' - '.price($objp->price_ttc, 1, $langs, 0, 0, -1, $conf->currency).' '.$langs->trans("TTC");
2498
+				$outval .= ' - '.price($objp->price_ttc, 0, $langs, 0, 0, -1, $conf->currency).' '.$langs->transnoentities("TTC");
2499 2499
 			}
2500
-			$outprice_ht=price($objp->price);
2501
-			$outprice_ttc=price($objp->price_ttc);
2502
-			$outpricebasetype=$objp->price_base_type;
2503
-			$outtva_tx=$objp->tva_tx;
2500
+			$outprice_ht = price($objp->price);
2501
+			$outprice_ttc = price($objp->price_ttc);
2502
+			$outpricebasetype = $objp->price_base_type;
2503
+			$outtva_tx = $objp->tva_tx;
2504 2504
 		}
2505 2505
 
2506
-		if (! empty($conf->stock->enabled) && isset($objp->stock) && $objp->fk_product_type == 0)
2506
+		if (!empty($conf->stock->enabled) && isset($objp->stock) && $objp->fk_product_type == 0)
2507 2507
 		{
2508
-			$opt.= ' - '.$langs->trans("Stock").':'.$objp->stock;
2508
+			$opt .= ' - '.$langs->trans("Stock").':'.$objp->stock;
2509 2509
 
2510 2510
 			if ($objp->stock > 0) {
2511
-				$outval.= ' - <span class="product_line_stock_ok">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2511
+				$outval .= ' - <span class="product_line_stock_ok">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2512 2512
 			}elseif ($objp->stock <= 0) {
2513
-				$outval.= ' - <span class="product_line_stock_too_low">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2513
+				$outval .= ' - <span class="product_line_stock_too_low">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2514 2514
 			}
2515 2515
 		}
2516 2516
 
2517 2517
 		if ($outdurationvalue && $outdurationunit)
2518 2518
 		{
2519
-			$da=array("h"=>$langs->trans("Hour"),"d"=>$langs->trans("Day"),"w"=>$langs->trans("Week"),"m"=>$langs->trans("Month"),"y"=>$langs->trans("Year"));
2519
+			$da = array("h"=>$langs->trans("Hour"), "d"=>$langs->trans("Day"), "w"=>$langs->trans("Week"), "m"=>$langs->trans("Month"), "y"=>$langs->trans("Year"));
2520 2520
 			if (isset($da[$outdurationunit]))
2521 2521
 			{
2522
-				$key = $da[$outdurationunit].($outdurationvalue > 1?'s':'');
2523
-				$opt.= ' - '.$outdurationvalue.' '.$langs->trans($key);
2524
-				$outval.=' - '.$outdurationvalue.' '.$langs->transnoentities($key);
2522
+				$key = $da[$outdurationunit].($outdurationvalue > 1 ? 's' : '');
2523
+				$opt .= ' - '.$outdurationvalue.' '.$langs->trans($key);
2524
+				$outval .= ' - '.$outdurationvalue.' '.$langs->transnoentities($key);
2525 2525
 			}
2526 2526
 		}
2527 2527
 
2528
-		$opt.= "</option>\n";
2528
+		$opt .= "</option>\n";
2529 2529
 		$optJson = array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'label2'=>$outlabel, 'desc'=>$outdesc, 'type'=>$outtype, 'price_ht'=>$outprice_ht, 'price_ttc'=>$outprice_ttc, 'pricebasetype'=>$outpricebasetype, 'tva_tx'=>$outtva_tx, 'qty'=>$outqty, 'discount'=>$outdiscount, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit);
2530 2530
 	}
2531 2531
 
@@ -2543,32 +2543,32 @@  discard block
 block discarded – undo
2543 2543
 	 *  @param  int     $alsoproductwithnosupplierprice    1=Add also product without supplier prices
2544 2544
 	 *	@return	void
2545 2545
 	 */
2546
-	function select_produits_fournisseurs($socid, $selected='', $htmlname='productid', $filtertype='', $filtre='', $ajaxoptions=array(), $hidelabel=0, $alsoproductwithnosupplierprice=0)
2546
+	function select_produits_fournisseurs($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $ajaxoptions = array(), $hidelabel = 0, $alsoproductwithnosupplierprice = 0)
2547 2547
 	{
2548 2548
         // phpcs:enable
2549
-		global $langs,$conf;
2549
+		global $langs, $conf;
2550 2550
 		global $price_level, $status, $finished;
2551 2551
 
2552
-		$selected_input_value='';
2553
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2552
+		$selected_input_value = '';
2553
+		if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2554 2554
 		{
2555 2555
 			if ($selected > 0)
2556 2556
 			{
2557 2557
 				require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
2558 2558
 				$producttmpselect = new Product($this->db);
2559 2559
 				$producttmpselect->fetch($selected);
2560
-				$selected_input_value=$producttmpselect->ref;
2560
+				$selected_input_value = $producttmpselect->ref;
2561 2561
 				unset($producttmpselect);
2562 2562
 			}
2563 2563
 
2564 2564
 			// mode=2 means suppliers products
2565
-			$urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
2565
+			$urloption = ($socid > 0 ? 'socid='.$socid.'&' : '').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
2566 2566
 			print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
2567
-			print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
2567
+			print ($hidelabel ? '' : $langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
2568 2568
 		}
2569 2569
 		else
2570 2570
 		{
2571
-			print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice);
2571
+			print $this->select_produits_fournisseurs_list($socid, $selected, $htmlname, $filtertype, $filtre, '', -1, 0, 0, $alsoproductwithnosupplierprice);
2572 2572
 		}
2573 2573
 	}
2574 2574
 
@@ -2588,54 +2588,54 @@  discard block
 block discarded – undo
2588 2588
 	 *  @param  int     $alsoproductwithnosupplierprice    1=Add also product without supplier prices
2589 2589
 	 *  @return array           		Array of keys for json
2590 2590
 	 */
2591
-	function select_produits_fournisseurs_list($socid,$selected='',$htmlname='productid',$filtertype='',$filtre='',$filterkey='',$statut=-1,$outputmode=0,$limit=100,$alsoproductwithnosupplierprice=0)
2591
+	function select_produits_fournisseurs_list($socid, $selected = '', $htmlname = 'productid', $filtertype = '', $filtre = '', $filterkey = '', $statut = -1, $outputmode = 0, $limit = 100, $alsoproductwithnosupplierprice = 0)
2592 2592
 	{
2593 2593
         // phpcs:enable
2594
-		global $langs,$conf,$db;
2594
+		global $langs, $conf, $db;
2595 2595
 
2596
-		$out='';
2597
-		$outarray=array();
2596
+		$out = '';
2597
+		$outarray = array();
2598 2598
 
2599 2599
 		$langs->load('stocks');
2600 2600
 
2601 2601
 		$sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, p.fk_product_type,";
2602
-		$sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
2603
-		$sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
2604
-		$sql.= " pfp.supplier_reputation";
2605
-		$sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2606
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2607
-		if ($socid) $sql.= " AND pfp.fk_soc = ".$socid;
2608
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2609
-		$sql.= " WHERE p.entity IN (".getEntity('product').")";
2610
-		$sql.= " AND p.tobuy = 1";
2611
-		if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype);
2612
-		if (! empty($filtre)) $sql.=" ".$filtre;
2602
+		$sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.remise_percent, pfp.remise, pfp.unitprice,";
2603
+		$sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, pfp.fk_soc, s.nom as name,";
2604
+		$sql .= " pfp.supplier_reputation";
2605
+		$sql .= " FROM ".MAIN_DB_PREFIX."product as p";
2606
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2607
+		if ($socid) $sql .= " AND pfp.fk_soc = ".$socid;
2608
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2609
+		$sql .= " WHERE p.entity IN (".getEntity('product').")";
2610
+		$sql .= " AND p.tobuy = 1";
2611
+		if (strval($filtertype) != '') $sql .= " AND p.fk_product_type=".$this->db->escape($filtertype);
2612
+		if (!empty($filtre)) $sql .= " ".$filtre;
2613 2613
 		// Add criteria on ref/label
2614 2614
 		if ($filterkey != '')
2615 2615
 		{
2616
-			$sql.=' AND (';
2617
-			$prefix=empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE)?'%':'';	// Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2616
+			$sql .= ' AND (';
2617
+			$prefix = empty($conf->global->PRODUCT_DONOTSEARCH_ANYWHERE) ? '%' : ''; // Can use index if PRODUCT_DONOTSEARCH_ANYWHERE is on
2618 2618
 			// For natural search
2619 2619
 			$scrit = explode(' ', $filterkey);
2620
-			$i=0;
2621
-			if (count($scrit) > 1) $sql.="(";
2620
+			$i = 0;
2621
+			if (count($scrit) > 1) $sql .= "(";
2622 2622
 			foreach ($scrit as $crit)
2623 2623
 			{
2624
-				if ($i > 0) $sql.=" AND ";
2625
-				$sql.="(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')";
2624
+				if ($i > 0) $sql .= " AND ";
2625
+				$sql .= "(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')";
2626 2626
 				$i++;
2627 2627
 			}
2628
-			if (count($scrit) > 1) $sql.=")";
2629
-			if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
2630
-			$sql.=')';
2628
+			if (count($scrit) > 1) $sql .= ")";
2629
+			if (!empty($conf->barcode->enabled)) $sql .= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
2630
+			$sql .= ')';
2631 2631
 		}
2632
-		$sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
2633
-		$sql.= $db->plimit($limit, 0);
2632
+		$sql .= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
2633
+		$sql .= $db->plimit($limit, 0);
2634 2634
 
2635 2635
 		// Build output string
2636 2636
 
2637 2637
 		dol_syslog(get_class($this)."::select_produits_fournisseurs_list", LOG_DEBUG);
2638
-		$result=$this->db->query($sql);
2638
+		$result = $this->db->query($sql);
2639 2639
 		if ($result)
2640 2640
 		{
2641 2641
 			require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
@@ -2643,57 +2643,57 @@  discard block
 block discarded – undo
2643 2643
 			$num = $this->db->num_rows($result);
2644 2644
 
2645 2645
 			//$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">';	// remove select to have id same with combo and ajax
2646
-			$out.='<select class="flat maxwidthonsmartphone" id="'.$htmlname.'" name="'.$htmlname.'">';
2647
-			if (! $selected) $out.='<option value="0" selected>&nbsp;</option>';
2648
-			else $out.='<option value="0">&nbsp;</option>';
2646
+			$out .= '<select class="flat maxwidthonsmartphone" id="'.$htmlname.'" name="'.$htmlname.'">';
2647
+			if (!$selected) $out .= '<option value="0" selected>&nbsp;</option>';
2648
+			else $out .= '<option value="0">&nbsp;</option>';
2649 2649
 
2650 2650
 			$i = 0;
2651 2651
 			while ($i < $num)
2652 2652
 			{
2653 2653
 				$objp = $this->db->fetch_object($result);
2654 2654
 
2655
-				$outkey=$objp->idprodfournprice;                                                    // id in table of price
2656
-				if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid;   // id of product
2655
+				$outkey = $objp->idprodfournprice; // id in table of price
2656
+				if (!$outkey && $alsoproductwithnosupplierprice) $outkey = 'idprod_'.$objp->rowid; // id of product
2657 2657
 
2658
-				$outref=$objp->ref;
2659
-				$outval='';
2660
-				$outqty=1;
2661
-				$outdiscount=0;
2662
-				$outtype=$objp->fk_product_type;
2663
-				$outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
2664
-				$outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
2658
+				$outref = $objp->ref;
2659
+				$outval = '';
2660
+				$outqty = 1;
2661
+				$outdiscount = 0;
2662
+				$outtype = $objp->fk_product_type;
2663
+				$outdurationvalue = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, 0, dol_strlen($objp->duration) - 1) : '';
2664
+				$outdurationunit = $outtype == Product::TYPE_SERVICE ?substr($objp->duration, -1) : '';
2665 2665
 
2666 2666
 				$opt = '<option value="'.$outkey.'"';
2667
-				if ($selected && $selected == $objp->idprodfournprice) $opt.= ' selected';
2668
-				if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt.=' disabled';
2667
+				if ($selected && $selected == $objp->idprodfournprice) $opt .= ' selected';
2668
+				if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt .= ' disabled';
2669 2669
 				if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0)
2670 2670
 				{
2671
-					$opt.= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqpercent="'.$objp->remise_percent.'"';
2671
+					$opt .= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqpercent="'.$objp->remise_percent.'"';
2672 2672
 				}
2673
-				$opt.= '>';
2673
+				$opt .= '>';
2674 2674
 
2675 2675
 				$objRef = $objp->ref;
2676
-				if ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2676
+				if ($filterkey && $filterkey != '') $objRef = preg_replace('/('.preg_quote($filterkey).')/i', '<strong>$1</strong>', $objRef, 1);
2677 2677
 				$objRefFourn = $objp->ref_fourn;
2678
-				if ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);
2678
+				if ($filterkey && $filterkey != '') $objRefFourn = preg_replace('/('.preg_quote($filterkey).')/i', '<strong>$1</strong>', $objRefFourn, 1);
2679 2679
 				$label = $objp->label;
2680
-				if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
2681
-
2682
-				$opt.=$objp->ref;
2683
-				if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2684
-					$opt.=' ('.$objp->ref_fourn.')';
2685
-				$opt.=' - ';
2686
-				$outval.=$objRef;
2687
-				if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2688
-					$outval.=' ('.$objRefFourn.')';
2689
-				$outval.=' - ';
2690
-				$opt.=dol_trunc($label, 72).' - ';
2691
-				$outval.=dol_trunc($label, 72).' - ';
2692
-
2693
-				if (! empty($objp->idprodfournprice))
2680
+				if ($filterkey && $filterkey != '') $label = preg_replace('/('.preg_quote($filterkey).')/i', '<strong>$1</strong>', $label, 1);
2681
+
2682
+				$opt .= $objp->ref;
2683
+				if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2684
+					$opt .= ' ('.$objp->ref_fourn.')';
2685
+				$opt .= ' - ';
2686
+				$outval .= $objRef;
2687
+				if (!empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2688
+					$outval .= ' ('.$objRefFourn.')';
2689
+				$outval .= ' - ';
2690
+				$opt .= dol_trunc($label, 72).' - ';
2691
+				$outval .= dol_trunc($label, 72).' - ';
2692
+
2693
+				if (!empty($objp->idprodfournprice))
2694 2694
 				{
2695
-					$outqty=$objp->quantity;
2696
-					$outdiscount=$objp->remise_percent;
2695
+					$outqty = $objp->quantity;
2696
+					$outdiscount = $objp->remise_percent;
2697 2697
 					if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
2698 2698
 						$prod_supplier = new ProductFournisseur($this->db);
2699 2699
 						$prod_supplier->product_fourn_price_id = $objp->idprodfournprice;
@@ -2713,59 +2713,59 @@  discard block
 block discarded – undo
2713 2713
 					}
2714 2714
 					if ($objp->quantity == 1)
2715 2715
 					{
2716
-						$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
2717
-						$outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/";
2718
-						$opt.= $langs->trans("Unit");	// Do not use strtolower because it breaks utf8 encoding
2719
-						$outval.=$langs->transnoentities("Unit");
2716
+						$opt .= price($objp->fprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
2717
+						$outval .= price($objp->fprice, 0, $langs, 0, 0, -1, $conf->currency)."/";
2718
+						$opt .= $langs->trans("Unit"); // Do not use strtolower because it breaks utf8 encoding
2719
+						$outval .= $langs->transnoentities("Unit");
2720 2720
 					}
2721 2721
 					else
2722 2722
 					{
2723
-						$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2724
-						$outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2725
-						$opt.= ' '.$langs->trans("Units");	// Do not use strtolower because it breaks utf8 encoding
2726
-						$outval.= ' '.$langs->transnoentities("Units");
2723
+						$opt .= price($objp->fprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
2724
+						$outval .= price($objp->fprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$objp->quantity;
2725
+						$opt .= ' '.$langs->trans("Units"); // Do not use strtolower because it breaks utf8 encoding
2726
+						$outval .= ' '.$langs->transnoentities("Units");
2727 2727
 					}
2728 2728
 
2729 2729
 					if ($objp->quantity >= 1)
2730 2730
 					{
2731
-						$opt.=" (".price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2732
-						$outval.=" (".price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/".$langs->transnoentities("Unit").")";	// Do not use strtolower because it breaks utf8 encoding
2731
+						$opt .= " (".price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
2732
+						$outval .= " (".price($objp->unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->transnoentities("Unit").")"; // Do not use strtolower because it breaks utf8 encoding
2733 2733
 					}
2734 2734
 					if ($objp->remise_percent >= 1)
2735 2735
 					{
2736
-						$opt.=" - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
2737
-						$outval.=" - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
2736
+						$opt .= " - ".$langs->trans("Discount")." : ".vatrate($objp->remise_percent).' %';
2737
+						$outval .= " - ".$langs->transnoentities("Discount")." : ".vatrate($objp->remise_percent).' %';
2738 2738
 					}
2739 2739
 					if ($objp->duration)
2740 2740
 					{
2741 2741
 						$opt .= " - ".$objp->duration;
2742
-						$outval.=" - ".$objp->duration;
2742
+						$outval .= " - ".$objp->duration;
2743 2743
 					}
2744
-					if (! $socid)
2744
+					if (!$socid)
2745 2745
 					{
2746
-						$opt .= " - ".dol_trunc($objp->name,8);
2747
-						$outval.=" - ".dol_trunc($objp->name,8);
2746
+						$opt .= " - ".dol_trunc($objp->name, 8);
2747
+						$outval .= " - ".dol_trunc($objp->name, 8);
2748 2748
 					}
2749 2749
 					if ($objp->supplier_reputation)
2750 2750
 					{
2751 2751
 						//TODO dictionary
2752
-						$reputations=array(''=>$langs->trans('Standard'),'FAVORITE'=>$langs->trans('Favorite'),'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
2752
+						$reputations = array(''=>$langs->trans('Standard'), 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
2753 2753
 
2754 2754
 						$opt .= " - ".$reputations[$objp->supplier_reputation];
2755
-						$outval.=" - ".$reputations[$objp->supplier_reputation];
2755
+						$outval .= " - ".$reputations[$objp->supplier_reputation];
2756 2756
 					}
2757 2757
 				}
2758 2758
 				else
2759 2759
 				{
2760 2760
 					if (empty($alsoproductwithnosupplierprice))     // No supplier price defined for couple product/supplier
2761 2761
 					{
2762
-						$opt.= $langs->trans("NoPriceDefinedForThisSupplier");
2763
-						$outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
2762
+						$opt .= $langs->trans("NoPriceDefinedForThisSupplier");
2763
+						$outval .= $langs->transnoentities("NoPriceDefinedForThisSupplier");
2764 2764
 					}
2765 2765
 					else                                            // No supplier price defined for product, even on other suppliers
2766 2766
 					{
2767
-						$opt.= $langs->trans("NoPriceDefinedForThisSupplier");
2768
-						$outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
2767
+						$opt .= $langs->trans("NoPriceDefinedForThisSupplier");
2768
+						$outval .= $langs->transnoentities("NoPriceDefinedForThisSupplier");
2769 2769
 					}
2770 2770
 				}
2771 2771
 				$opt .= "</option>\n";
@@ -2774,8 +2774,8 @@  discard block
 block discarded – undo
2774 2774
 				// Add new entry
2775 2775
 				// "key" value of json key array is used by jQuery automatically as selected value
2776 2776
 				// "label" value of json key array is used by jQuery automatically as text for combo box
2777
-				$out.=$opt;
2778
-				array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice)?true:false)));
2777
+				$out .= $opt;
2778
+				array_push($outarray, array('key'=>$outkey, 'value'=>$outref, 'label'=>$outval, 'qty'=>$outqty, 'discount'=>$outdiscount, 'type'=>$outtype, 'duration_value'=>$outdurationvalue, 'duration_unit'=>$outdurationunit, 'disabled'=>(empty($objp->idprodfournprice) ?true:false)));
2779 2779
 				// Exemple of var_dump $outarray
2780 2780
 				// array(1) {[0]=>array(6) {[key"]=>string(1) "2" ["value"]=>string(3) "ppp"
2781 2781
 				//           ["label"]=>string(76) "ppp (<strong>f</strong>ff2) - ppp - 20,00 Euros/1unité (20,00 Euros/unité)"
@@ -2787,12 +2787,12 @@  discard block
 block discarded – undo
2787 2787
 
2788 2788
 				$i++;
2789 2789
 			}
2790
-			$out.='</select>';
2790
+			$out .= '</select>';
2791 2791
 
2792 2792
 			$this->db->free($result);
2793 2793
 
2794
-			include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2795
-			$out.=ajax_combobox($htmlname);
2794
+			include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
2795
+			$out .= ajax_combobox($htmlname);
2796 2796
 
2797 2797
 			if (empty($outputmode)) return $out;
2798 2798
 			return $outarray;
@@ -2812,27 +2812,27 @@  discard block
 block discarded – undo
2812 2812
 	 *  @param      int		$selected_supplier  Pre-selected supplier if more than 1 result
2813 2813
 	 *  @return	    void
2814 2814
 	 */
2815
-	function select_product_fourn_price($productid, $htmlname='productfournpriceid', $selected_supplier='')
2815
+	function select_product_fourn_price($productid, $htmlname = 'productfournpriceid', $selected_supplier = '')
2816 2816
 	{
2817 2817
         // phpcs:enable
2818
-		global $langs,$conf;
2818
+		global $langs, $conf;
2819 2819
 
2820 2820
 		$langs->load('stocks');
2821 2821
 
2822 2822
 		$sql = "SELECT p.rowid, p.label, p.ref, p.price, p.duration, pfp.fk_soc,";
2823
-		$sql.= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,";
2824
-		$sql.= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
2825
-		$sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2826
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2827
-		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2828
-		$sql.= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
2829
-		$sql.= " AND p.tobuy = 1";
2830
-		$sql.= " AND s.fournisseur = 1";
2831
-		$sql.= " AND p.rowid = ".$productid;
2832
-		$sql.= " ORDER BY s.nom, pfp.ref_fourn DESC";
2823
+		$sql .= " pfp.ref_fourn, pfp.rowid as idprodfournprice, pfp.price as fprice, pfp.quantity, pfp.unitprice,";
2824
+		$sql .= " pfp.fk_supplier_price_expression, pfp.fk_product, pfp.tva_tx, s.nom as name";
2825
+		$sql .= " FROM ".MAIN_DB_PREFIX."product as p";
2826
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2827
+		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2828
+		$sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
2829
+		$sql .= " AND p.tobuy = 1";
2830
+		$sql .= " AND s.fournisseur = 1";
2831
+		$sql .= " AND p.rowid = ".$productid;
2832
+		$sql .= " ORDER BY s.nom, pfp.ref_fourn DESC";
2833 2833
 
2834 2834
 		dol_syslog(get_class($this)."::select_product_fourn_price", LOG_DEBUG);
2835
-		$result=$this->db->query($sql);
2835
+		$result = $this->db->query($sql);
2836 2836
 
2837 2837
 		if ($result)
2838 2838
 		{
@@ -2840,14 +2840,14 @@  discard block
 block discarded – undo
2840 2840
 
2841 2841
 			$form = '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
2842 2842
 
2843
-			if (! $num)
2843
+			if (!$num)
2844 2844
 			{
2845
-				$form.= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
2845
+				$form .= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
2846 2846
 			}
2847 2847
 			else
2848 2848
 			{
2849 2849
 				require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2850
-				$form.= '<option value="0">&nbsp;</option>';
2850
+				$form .= '<option value="0">&nbsp;</option>';
2851 2851
 
2852 2852
 				$i = 0;
2853 2853
 				while ($i < $num)
@@ -2856,10 +2856,10 @@  discard block
 block discarded – undo
2856 2856
 
2857 2857
 					$opt = '<option value="'.$objp->idprodfournprice.'"';
2858 2858
 					//if there is only one supplier, preselect it
2859
-					if($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
2859
+					if ($num == 1 || ($selected_supplier > 0 && $objp->fk_soc == $selected_supplier)) {
2860 2860
 						$opt .= ' selected';
2861 2861
 					}
2862
-					$opt.= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
2862
+					$opt .= '>'.$objp->name.' - '.$objp->ref_fourn.' - ';
2863 2863
 
2864 2864
 					if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_supplier_price_expression)) {
2865 2865
 						$prod_supplier = new ProductFournisseur($this->db);
@@ -2880,33 +2880,33 @@  discard block
 block discarded – undo
2880 2880
 					}
2881 2881
 					if ($objp->quantity == 1)
2882 2882
 					{
2883
-						$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/";
2883
+						$opt .= price($objp->fprice, 1, $langs, 0, 0, -1, $conf->currency)."/";
2884 2884
 					}
2885 2885
 
2886
-					$opt.= $objp->quantity.' ';
2886
+					$opt .= $objp->quantity.' ';
2887 2887
 
2888 2888
 					if ($objp->quantity == 1)
2889 2889
 					{
2890
-						$opt.= $langs->trans("Unit");
2890
+						$opt .= $langs->trans("Unit");
2891 2891
 					}
2892 2892
 					else
2893 2893
 					{
2894
-						$opt.= $langs->trans("Units");
2894
+						$opt .= $langs->trans("Units");
2895 2895
 					}
2896 2896
 					if ($objp->quantity > 1)
2897 2897
 					{
2898
-						$opt.=" - ";
2899
-						$opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit");
2898
+						$opt .= " - ";
2899
+						$opt .= price($objp->unitprice, 1, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit");
2900 2900
 					}
2901 2901
 					if ($objp->duration) $opt .= " - ".$objp->duration;
2902 2902
 					$opt .= "</option>\n";
2903 2903
 
2904
-					$form.= $opt;
2904
+					$form .= $opt;
2905 2905
 					$i++;
2906 2906
 				}
2907 2907
 			}
2908 2908
 
2909
-			$form.= '</select>';
2909
+			$form .= '</select>';
2910 2910
 			$this->db->free($result);
2911 2911
 			return $form;
2912 2912
 		}
@@ -2926,17 +2926,17 @@  discard block
 block discarded – undo
2926 2926
 	 *    @param    int		$showempty         	Add an empty field
2927 2927
 	 *    @return	integer|null
2928 2928
 	 */
2929
-	function select_address($selected, $socid, $htmlname='address_id',$showempty=0)
2929
+	function select_address($selected, $socid, $htmlname = 'address_id', $showempty = 0)
2930 2930
 	{
2931 2931
         // phpcs:enable
2932 2932
 		// looking for users
2933 2933
 		$sql = "SELECT a.rowid, a.label";
2934
-		$sql .= " FROM ".MAIN_DB_PREFIX ."societe_address as a";
2934
+		$sql .= " FROM ".MAIN_DB_PREFIX."societe_address as a";
2935 2935
 		$sql .= " WHERE a.fk_soc = ".$socid;
2936 2936
 		$sql .= " ORDER BY a.label ASC";
2937 2937
 
2938 2938
 		dol_syslog(get_class($this)."::select_address", LOG_DEBUG);
2939
-		$resql=$this->db->query($sql);
2939
+		$resql = $this->db->query($sql);
2940 2940
 		if ($resql)
2941 2941
 		{
2942 2942
 			print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
@@ -2982,15 +2982,15 @@  discard block
 block discarded – undo
2982 2982
 		global $langs;
2983 2983
 
2984 2984
 		$num = count($this->cache_conditions_paiements);
2985
-		if ($num > 0) return 0;    // Cache already loaded
2985
+		if ($num > 0) return 0; // Cache already loaded
2986 2986
 
2987 2987
 		dol_syslog(__METHOD__, LOG_DEBUG);
2988 2988
 
2989 2989
 		$sql = "SELECT rowid, code, libelle as label";
2990
-		$sql.= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
2991
-		$sql.= " WHERE entity IN (".getEntity('c_payment_term').")";
2992
-		$sql.= " AND active > 0";
2993
-		$sql.= " ORDER BY sortorder";
2990
+		$sql .= " FROM ".MAIN_DB_PREFIX.'c_payment_term';
2991
+		$sql .= " WHERE entity IN (".getEntity('c_payment_term').")";
2992
+		$sql .= " AND active > 0";
2993
+		$sql .= " ORDER BY sortorder";
2994 2994
 
2995 2995
 		$resql = $this->db->query($sql);
2996 2996
 		if ($resql)
@@ -3002,9 +3002,9 @@  discard block
 block discarded – undo
3002 3002
 				$obj = $this->db->fetch_object($resql);
3003 3003
 
3004 3004
 				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3005
-				$label=($langs->trans("PaymentConditionShort".$obj->code)!=("PaymentConditionShort".$obj->code)?$langs->trans("PaymentConditionShort".$obj->code):($obj->label!='-'?$obj->label:''));
3006
-				$this->cache_conditions_paiements[$obj->rowid]['code'] =$obj->code;
3007
-				$this->cache_conditions_paiements[$obj->rowid]['label']=$label;
3005
+				$label = ($langs->trans("PaymentConditionShort".$obj->code) != ("PaymentConditionShort".$obj->code) ? $langs->trans("PaymentConditionShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
3006
+				$this->cache_conditions_paiements[$obj->rowid]['code'] = $obj->code;
3007
+				$this->cache_conditions_paiements[$obj->rowid]['label'] = $label;
3008 3008
 				$i++;
3009 3009
 			}
3010 3010
 
@@ -3031,15 +3031,15 @@  discard block
 block discarded – undo
3031 3031
 		global $langs;
3032 3032
 
3033 3033
 		$num = count($this->cache_availability);
3034
-		if ($num > 0) return 0;    // Cache already loaded
3034
+		if ($num > 0) return 0; // Cache already loaded
3035 3035
 
3036 3036
 		dol_syslog(__METHOD__, LOG_DEBUG);
3037 3037
 
3038 3038
 		$langs->load('propal');
3039 3039
 
3040 3040
 		$sql = "SELECT rowid, code, label";
3041
-		$sql.= " FROM ".MAIN_DB_PREFIX.'c_availability';
3042
-		$sql.= " WHERE active > 0";
3041
+		$sql .= " FROM ".MAIN_DB_PREFIX.'c_availability';
3042
+		$sql .= " WHERE active > 0";
3043 3043
 
3044 3044
 		$resql = $this->db->query($sql);
3045 3045
 		if ($resql)
@@ -3051,9 +3051,9 @@  discard block
 block discarded – undo
3051 3051
 				$obj = $this->db->fetch_object($resql);
3052 3052
 
3053 3053
 				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3054
-				$label=($langs->trans("AvailabilityType".$obj->code)!=("AvailabilityType".$obj->code)?$langs->trans("AvailabilityType".$obj->code):($obj->label!='-'?$obj->label:''));
3055
-				$this->cache_availability[$obj->rowid]['code'] =$obj->code;
3056
-				$this->cache_availability[$obj->rowid]['label']=$label;
3054
+				$label = ($langs->trans("AvailabilityType".$obj->code) != ("AvailabilityType".$obj->code) ? $langs->trans("AvailabilityType".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
3055
+				$this->cache_availability[$obj->rowid]['code'] = $obj->code;
3056
+				$this->cache_availability[$obj->rowid]['label'] = $label;
3057 3057
 				$i++;
3058 3058
 			}
3059 3059
 
@@ -3077,9 +3077,9 @@  discard block
 block discarded – undo
3077 3077
 	 *		@param	int		$addempty		Add empty entry
3078 3078
 	 *		@return	void
3079 3079
 	 */
3080
-	function selectAvailabilityDelay($selected='',$htmlname='availid',$filtertype='',$addempty=0)
3080
+	function selectAvailabilityDelay($selected = '', $htmlname = 'availid', $filtertype = '', $addempty = 0)
3081 3081
 	{
3082
-		global $langs,$user;
3082
+		global $langs, $user;
3083 3083
 
3084 3084
 		$this->load_cache_availability();
3085 3085
 
@@ -3087,7 +3087,7 @@  discard block
 block discarded – undo
3087 3087
 
3088 3088
 		print '<select id="'.$htmlname.'" class="flat" name="'.$htmlname.'">';
3089 3089
 		if ($addempty) print '<option value="0">&nbsp;</option>';
3090
-		foreach($this->cache_availability as $id => $arrayavailability)
3090
+		foreach ($this->cache_availability as $id => $arrayavailability)
3091 3091
 		{
3092 3092
 			if ($selected == $id)
3093 3093
 			{
@@ -3101,7 +3101,7 @@  discard block
 block discarded – undo
3101 3101
 			print '</option>';
3102 3102
 		}
3103 3103
 		print '</select>';
3104
-		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3104
+		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
3105 3105
 	}
3106 3106
 
3107 3107
 	/**
@@ -3114,34 +3114,34 @@  discard block
 block discarded – undo
3114 3114
 		global $langs;
3115 3115
 
3116 3116
 		$num = count($this->cache_demand_reason);
3117
-		if ($num > 0) return 0;    // Cache already loaded
3117
+		if ($num > 0) return 0; // Cache already loaded
3118 3118
 
3119 3119
 		$sql = "SELECT rowid, code, label";
3120
-		$sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
3121
-		$sql.= " WHERE active > 0";
3120
+		$sql .= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
3121
+		$sql .= " WHERE active > 0";
3122 3122
 
3123 3123
 		$resql = $this->db->query($sql);
3124 3124
 		if ($resql)
3125 3125
 		{
3126 3126
 			$num = $this->db->num_rows($resql);
3127 3127
 			$i = 0;
3128
-			$tmparray=array();
3128
+			$tmparray = array();
3129 3129
 			while ($i < $num)
3130 3130
 			{
3131 3131
 				$obj = $this->db->fetch_object($resql);
3132 3132
 
3133 3133
 				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3134
-				$label=($obj->label!='-'?$obj->label:'');
3134
+				$label = ($obj->label != '-' ? $obj->label : '');
3135 3135
 				if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
3136
-				if ($langs->trans($obj->code) != $obj->code) $label=$langs->trans($obj->code);																// So translation key SRC_XXX will work
3136
+				if ($langs->trans($obj->code) != $obj->code) $label = $langs->trans($obj->code); // So translation key SRC_XXX will work
3137 3137
 
3138
-				$tmparray[$obj->rowid]['id']   =$obj->rowid;
3139
-				$tmparray[$obj->rowid]['code'] =$obj->code;
3140
-				$tmparray[$obj->rowid]['label']=$label;
3138
+				$tmparray[$obj->rowid]['id']   = $obj->rowid;
3139
+				$tmparray[$obj->rowid]['code'] = $obj->code;
3140
+				$tmparray[$obj->rowid]['label'] = $label;
3141 3141
 				$i++;
3142 3142
 			}
3143 3143
 
3144
-			$this->cache_demand_reason=dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
3144
+			$this->cache_demand_reason = dol_sort_array($tmparray, 'label', 'asc', 0, 0, 1);
3145 3145
 
3146 3146
 			unset($tmparray);
3147 3147
 			return $num;
@@ -3163,17 +3163,17 @@  discard block
 block discarded – undo
3163 3163
 	 *	@param	int		$addempty		 Add an empty entry
3164 3164
 	 *	@return	void
3165 3165
 	 */
3166
-	function selectInputReason($selected='',$htmlname='demandreasonid',$exclude='',$addempty=0)
3166
+	function selectInputReason($selected = '', $htmlname = 'demandreasonid', $exclude = '', $addempty = 0)
3167 3167
 	{
3168
-		global $langs,$user;
3168
+		global $langs, $user;
3169 3169
 
3170 3170
 		$this->loadCacheInputReason();
3171 3171
 
3172 3172
 		print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3173
-		if ($addempty) print '<option value="0"'.(empty($selected)?' selected':'').'>&nbsp;</option>';
3174
-		foreach($this->cache_demand_reason as $id => $arraydemandreason)
3173
+		if ($addempty) print '<option value="0"'.(empty($selected) ? ' selected' : '').'>&nbsp;</option>';
3174
+		foreach ($this->cache_demand_reason as $id => $arraydemandreason)
3175 3175
 		{
3176
-			if ($arraydemandreason['code']==$exclude) continue;
3176
+			if ($arraydemandreason['code'] == $exclude) continue;
3177 3177
 
3178 3178
 			if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
3179 3179
 			{
@@ -3183,12 +3183,12 @@  discard block
 block discarded – undo
3183 3183
 			{
3184 3184
 				print '<option value="'.$arraydemandreason['id'].'">';
3185 3185
 			}
3186
-			$label=$arraydemandreason['label'];	// Translation of label was already done into the ->loadCacheInputReason
3186
+			$label = $arraydemandreason['label']; // Translation of label was already done into the ->loadCacheInputReason
3187 3187
 			print $langs->trans($label);
3188 3188
 			print '</option>';
3189 3189
 		}
3190 3190
 		print '</select>';
3191
-		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3191
+		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
3192 3192
 	}
3193 3193
 
3194 3194
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -3202,16 +3202,16 @@  discard block
 block discarded – undo
3202 3202
         // phpcs:enable
3203 3203
 		global $langs;
3204 3204
 
3205
-		$num=count($this->cache_types_paiements);
3206
-		if ($num > 0) return $num;    // Cache already loaded
3205
+		$num = count($this->cache_types_paiements);
3206
+		if ($num > 0) return $num; // Cache already loaded
3207 3207
 
3208 3208
 		dol_syslog(__METHOD__, LOG_DEBUG);
3209 3209
 
3210 3210
 		$this->cache_types_paiements = array();
3211 3211
 
3212 3212
 		$sql = "SELECT id, code, libelle as label, type, active";
3213
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_paiement";
3214
-		$sql.= " WHERE entity IN (".getEntity('c_paiement').")";
3213
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_paiement";
3214
+		$sql .= " WHERE entity IN (".getEntity('c_paiement').")";
3215 3215
 		//if ($active >= 0) $sql.= " AND active = ".$active;
3216 3216
 
3217 3217
 		$resql = $this->db->query($sql);
@@ -3224,12 +3224,12 @@  discard block
 block discarded – undo
3224 3224
 				$obj = $this->db->fetch_object($resql);
3225 3225
 
3226 3226
 				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3227
-				$label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:''));
3228
-				$this->cache_types_paiements[$obj->id]['id'] =$obj->id;
3229
-				$this->cache_types_paiements[$obj->id]['code'] =$obj->code;
3230
-				$this->cache_types_paiements[$obj->id]['label']=$label;
3231
-				$this->cache_types_paiements[$obj->id]['type'] =$obj->type;
3232
-				$this->cache_types_paiements[$obj->id]['active'] =$obj->active;
3227
+				$label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : ''));
3228
+				$this->cache_types_paiements[$obj->id]['id'] = $obj->id;
3229
+				$this->cache_types_paiements[$obj->id]['code'] = $obj->code;
3230
+				$this->cache_types_paiements[$obj->id]['label'] = $label;
3231
+				$this->cache_types_paiements[$obj->id]['type'] = $obj->type;
3232
+				$this->cache_types_paiements[$obj->id]['active'] = $obj->active;
3233 3233
 				$i++;
3234 3234
 			}
3235 3235
 
@@ -3259,7 +3259,7 @@  discard block
 block discarded – undo
3259 3259
 	 * 		@param	string	$morecss			Add more CSS on select tag
3260 3260
 	 *		@return	void
3261 3261
 	 */
3262
-	function select_conditions_paiements($selected=0, $htmlname='condid', $filtertype=-1, $addempty=0, $noinfoadmin=0, $morecss='')
3262
+	function select_conditions_paiements($selected = 0, $htmlname = 'condid', $filtertype = -1, $addempty = 0, $noinfoadmin = 0, $morecss = '')
3263 3263
 	{
3264 3264
         // phpcs:enable
3265 3265
 		global $langs, $user, $conf;
@@ -3269,11 +3269,11 @@  discard block
 block discarded – undo
3269 3269
 		$this->load_cache_conditions_paiements();
3270 3270
 
3271 3271
 		// Set default value if not already set by caller
3272
-		if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
3272
+		if (empty($selected) && !empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
3273 3273
 
3274
-		print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
3274
+		print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
3275 3275
 		if ($addempty) print '<option value="0">&nbsp;</option>';
3276
-		foreach($this->cache_conditions_paiements as $id => $arrayconditions)
3276
+		foreach ($this->cache_conditions_paiements as $id => $arrayconditions)
3277 3277
 		{
3278 3278
 			if ($selected == $id)
3279 3279
 			{
@@ -3287,7 +3287,7 @@  discard block
 block discarded – undo
3287 3287
 			print '</option>';
3288 3288
 		}
3289 3289
 		print '</select>';
3290
-		if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3290
+		if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
3291 3291
 	}
3292 3292
 
3293 3293
 
@@ -3306,29 +3306,29 @@  discard block
 block discarded – undo
3306 3306
 	 *      @param  string  $morecss        Add more CSS on select tag
3307 3307
 	 * 		@return	void
3308 3308
 	 */
3309
-	function select_types_paiements($selected='', $htmlname='paiementtype', $filtertype='', $format=0, $empty=1, $noadmininfo=0, $maxlength=0, $active=1, $morecss='')
3309
+	function select_types_paiements($selected = '', $htmlname = 'paiementtype', $filtertype = '', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '')
3310 3310
 	{
3311 3311
         // phpcs:enable
3312
-		global $langs,$user;
3312
+		global $langs, $user;
3313 3313
 
3314 3314
 		dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
3315 3315
 
3316
-		$filterarray=array();
3317
-		if ($filtertype == 'CRDT')  	$filterarray=array(0,2,3);
3318
-		elseif ($filtertype == 'DBIT') 	$filterarray=array(1,2,3);
3319
-		elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);
3316
+		$filterarray = array();
3317
+		if ($filtertype == 'CRDT')  	$filterarray = array(0, 2, 3);
3318
+		elseif ($filtertype == 'DBIT') 	$filterarray = array(1, 2, 3);
3319
+		elseif ($filtertype != '' && $filtertype != '-1') $filterarray = explode(',', $filtertype);
3320 3320
 
3321 3321
 		$this->load_cache_types_paiements();
3322 3322
 
3323
-		print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
3323
+		print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'">';
3324 3324
 		if ($empty) print '<option value="">&nbsp;</option>';
3325
-		foreach($this->cache_types_paiements as $id => $arraytypes)
3325
+		foreach ($this->cache_types_paiements as $id => $arraytypes)
3326 3326
 		{
3327 3327
 			// If not good status
3328 3328
 			if ($active >= 0 && $arraytypes['active'] != $active) continue;
3329 3329
 
3330 3330
 			// On passe si on a demande de filtrer sur des modes de paiments particuliers
3331
-			if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;
3331
+			if (count($filterarray) && !in_array($arraytypes['type'], $filterarray)) continue;
3332 3332
 
3333 3333
 			// We discard empty line if showempty is on because an empty line has already been output.
3334 3334
 			if ($empty && empty($arraytypes['code'])) continue;
@@ -3341,15 +3341,15 @@  discard block
 block discarded – undo
3341 3341
 			if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';
3342 3342
 			elseif ($selected == $id) print ' selected';
3343 3343
 			print '>';
3344
-			if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3345
-			elseif ($format == 1) $value=$arraytypes['code'];
3346
-			elseif ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3347
-			elseif ($format == 3) $value=$arraytypes['code'];
3348
-			print $value?$value:'&nbsp;';
3344
+			if ($format == 0) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
3345
+			elseif ($format == 1) $value = $arraytypes['code'];
3346
+			elseif ($format == 2) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']);
3347
+			elseif ($format == 3) $value = $arraytypes['code'];
3348
+			print $value ? $value : '&nbsp;';
3349 3349
 			print '</option>';
3350 3350
 		}
3351 3351
 		print '</select>';
3352
-		if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3352
+		if ($user->admin && !$noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
3353 3353
 	}
3354 3354
 
3355 3355
 
@@ -3360,30 +3360,30 @@  discard block
 block discarded – undo
3360 3360
 	 *  @param  string	$htmlname       Nom de la zone select
3361 3361
 	 * 	@return	string					Code of HTML select to chose tax or not
3362 3362
 	 */
3363
-	function selectPriceBaseType($selected='',$htmlname='price_base_type')
3363
+	function selectPriceBaseType($selected = '', $htmlname = 'price_base_type')
3364 3364
 	{
3365 3365
 		global $langs;
3366 3366
 
3367
-		$return='';
3367
+		$return = '';
3368 3368
 
3369
-		$return.= '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3369
+		$return .= '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3370 3370
 		$options = array(
3371 3371
 			'HT'=>$langs->trans("HT"),
3372 3372
 			'TTC'=>$langs->trans("TTC")
3373 3373
 		);
3374
-		foreach($options as $id => $value)
3374
+		foreach ($options as $id => $value)
3375 3375
 		{
3376 3376
 			if ($selected == $id)
3377 3377
 			{
3378
-				$return.= '<option value="'.$id.'" selected>'.$value;
3378
+				$return .= '<option value="'.$id.'" selected>'.$value;
3379 3379
 			}
3380 3380
 			else
3381 3381
 			{
3382
-				$return.= '<option value="'.$id.'">'.$value;
3382
+				$return .= '<option value="'.$id.'">'.$value;
3383 3383
 			}
3384
-			$return.= '</option>';
3384
+			$return .= '</option>';
3385 3385
 		}
3386
-		$return.= '</select>';
3386
+		$return .= '</select>';
3387 3387
 
3388 3388
 		return $return;
3389 3389
 	}
@@ -3398,7 +3398,7 @@  discard block
 block discarded – undo
3398 3398
 	 *  @param  string	$moreattrib        To add more attribute on select
3399 3399
 	 * 	@return	void
3400 3400
 	 */
3401
-	function selectShippingMethod($selected='',$htmlname='shipping_method_id',$filtre='',$useempty=0,$moreattrib='')
3401
+	function selectShippingMethod($selected = '', $htmlname = 'shipping_method_id', $filtre = '', $useempty = 0, $moreattrib = '')
3402 3402
 	{
3403 3403
 		global $langs, $conf, $user;
3404 3404
 
@@ -3406,10 +3406,10 @@  discard block
 block discarded – undo
3406 3406
 		$langs->load("deliveries");
3407 3407
 
3408 3408
 		$sql = "SELECT rowid, code, libelle as label";
3409
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
3410
-		$sql.= " WHERE active > 0";
3411
-		if ($filtre) $sql.=" AND ".$filtre;
3412
-		$sql.= " ORDER BY libelle ASC";
3409
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
3410
+		$sql .= " WHERE active > 0";
3411
+		if ($filtre) $sql .= " AND ".$filtre;
3412
+		$sql .= " ORDER BY libelle ASC";
3413 3413
 
3414 3414
 		dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
3415 3415
 		$result = $this->db->query($sql);
@@ -3417,7 +3417,7 @@  discard block
 block discarded – undo
3417 3417
 			$num = $this->db->num_rows($result);
3418 3418
 			$i = 0;
3419 3419
 			if ($num) {
3420
-				print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
3420
+				print '<select id="select'.$htmlname.'" class="flat selectshippingmethod" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
3421 3421
 				if ($useempty == 1 || ($useempty == 2 && $num > 1)) {
3422 3422
 					print '<option value="-1">&nbsp;</option>';
3423 3423
 				}
@@ -3433,7 +3433,7 @@  discard block
 block discarded – undo
3433 3433
 					$i++;
3434 3434
 				}
3435 3435
 				print "</select>";
3436
-				if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3436
+				if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
3437 3437
 			} else {
3438 3438
 				print $langs->trans("NoShippingMethodDefined");
3439 3439
 			}
@@ -3451,7 +3451,7 @@  discard block
 block discarded – undo
3451 3451
 	 *    @param    int		$addempty    1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3452 3452
 	 *    @return	void
3453 3453
 	 */
3454
-	function formSelectShippingMethod($page, $selected='', $htmlname='shipping_method_id', $addempty=0)
3454
+	function formSelectShippingMethod($page, $selected = '', $htmlname = 'shipping_method_id', $addempty = 0)
3455 3455
 	{
3456 3456
 		global $langs, $db;
3457 3457
 
@@ -3466,7 +3466,7 @@  discard block
 block discarded – undo
3466 3466
 			print '</form>';
3467 3467
 		} else {
3468 3468
 			if ($selected) {
3469
-				$code=$langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
3469
+				$code = $langs->getLabelFromKey($db, $selected, 'c_shipment_mode', 'rowid', 'code');
3470 3470
 				print $langs->trans("SendingMethod".strtoupper($code));
3471 3471
 			} else {
3472 3472
 				print "&nbsp;";
@@ -3489,13 +3489,13 @@  discard block
 block discarded – undo
3489 3489
 		$langs->load('bills');
3490 3490
 
3491 3491
 		$opt = '<option value ="" selected></option>';
3492
-		$sql = 'SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_counter>=1';
3493
-		$sql.= ' ORDER by situation_cycle_ref, situation_counter desc';
3492
+		$sql = 'SELECT rowid, ref, situation_cycle_ref, situation_counter, situation_final, fk_soc FROM '.MAIN_DB_PREFIX.'facture WHERE situation_counter>=1';
3493
+		$sql .= ' ORDER by situation_cycle_ref, situation_counter desc';
3494 3494
 		$resql = $this->db->query($sql);
3495 3495
 		if ($resql && $this->db->num_rows($resql) > 0) {
3496 3496
 			// Last seen cycle
3497 3497
 			$ref = 0;
3498
-			while ($obj = $this->db->fetch_object($resql)){
3498
+			while ($obj = $this->db->fetch_object($resql)) {
3499 3499
 				//Same company ?
3500 3500
 			    if ($socid == $obj->fk_soc) {
3501 3501
 					//Same cycle ?
@@ -3507,9 +3507,9 @@  discard block
 block discarded – undo
3507 3507
 							//Not prov?
3508 3508
 			                if (substr($obj->ref, 1, 4) != 'PROV') {
3509 3509
 			                    if ($selected == $obj->rowid) {
3510
-			                        $opt .= '<option value="' . $obj->rowid . '" selected>' . $obj->ref . '</option>';
3510
+			                        $opt .= '<option value="'.$obj->rowid.'" selected>'.$obj->ref.'</option>';
3511 3511
 								} else {
3512
-								    $opt .= '<option value="' . $obj->rowid . '">' . $obj->ref . '</option>';
3512
+								    $opt .= '<option value="'.$obj->rowid.'">'.$obj->ref.'</option>';
3513 3513
 								}
3514 3514
 							}
3515 3515
 						}
@@ -3519,11 +3519,11 @@  discard block
 block discarded – undo
3519 3519
 		}
3520 3520
 		else
3521 3521
 		{
3522
-				dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
3522
+				dol_syslog("Error sql=".$sql.", error=".$this->error, LOG_ERR);
3523 3523
 		}
3524 3524
 		if ($opt == '<option value ="" selected></option>')
3525 3525
 		{
3526
-			$opt = '<option value ="0" selected>' . $langs->trans('NoSituations') . '</option>';
3526
+			$opt = '<option value ="0" selected>'.$langs->trans('NoSituations').'</option>';
3527 3527
 		}
3528 3528
 		return $opt;
3529 3529
 	}
@@ -3536,40 +3536,40 @@  discard block
 block discarded – undo
3536 3536
 	 *      @param	int		$showempty		Add a nempty line
3537 3537
 	 * 		@return	string                  HTML select
3538 3538
 	 */
3539
-	function selectUnits($selected = '', $htmlname = 'units', $showempty=0)
3539
+	function selectUnits($selected = '', $htmlname = 'units', $showempty = 0)
3540 3540
 	{
3541 3541
 		global $langs;
3542 3542
 
3543 3543
 		$langs->load('products');
3544 3544
 
3545
-		$return= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
3545
+		$return = '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'">';
3546 3546
 
3547 3547
 		$sql = 'SELECT rowid, label, code from '.MAIN_DB_PREFIX.'c_units';
3548
-		$sql.= ' WHERE active > 0';
3548
+		$sql .= ' WHERE active > 0';
3549 3549
 
3550 3550
 		$resql = $this->db->query($sql);
3551
-		if($resql && $this->db->num_rows($resql) > 0)
3551
+		if ($resql && $this->db->num_rows($resql) > 0)
3552 3552
 		{
3553 3553
 			if ($showempty) $return .= '<option value="none"></option>';
3554 3554
 
3555
-			while($res = $this->db->fetch_object($resql))
3555
+			while ($res = $this->db->fetch_object($resql))
3556 3556
 			{
3557 3557
 			    $unitLabel = $res->label;
3558
-			    if (! empty($langs->tab_translate['unit'.$res->code]))	// check if Translation is available before
3558
+			    if (!empty($langs->tab_translate['unit'.$res->code]))	// check if Translation is available before
3559 3559
 			    {
3560
-			        $unitLabel = $langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label;
3560
+			        $unitLabel = $langs->trans('unit'.$res->code) != $res->label ? $langs->trans('unit'.$res->code) : $res->label;
3561 3561
 			    }
3562 3562
 
3563 3563
 				if ($selected == $res->rowid)
3564 3564
 				{
3565
-				    $return.='<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
3565
+				    $return .= '<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
3566 3566
 				}
3567 3567
 				else
3568 3568
 				{
3569
-				    $return.='<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
3569
+				    $return .= '<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
3570 3570
 				}
3571 3571
 			}
3572
-			$return.='</select>';
3572
+			$return .= '</select>';
3573 3573
 		}
3574 3574
 		return $return;
3575 3575
 	}
@@ -3587,7 +3587,7 @@  discard block
 block discarded – undo
3587 3587
 	 *  @param	int		$showcurrency		Show currency in label
3588 3588
 	 * 	@return	int							<0 if error, Num of bank account found if OK (0, 1, 2, ...)
3589 3589
 	 */
3590
-	function select_comptes($selected='',$htmlname='accountid',$statut=0,$filtre='',$useempty=0,$moreattrib='',$showcurrency=0)
3590
+	function select_comptes($selected = '', $htmlname = 'accountid', $statut = 0, $filtre = '', $useempty = 0, $moreattrib = '', $showcurrency = 0)
3591 3591
 	{
3592 3592
         // phpcs:enable
3593 3593
 		global $langs, $conf;
@@ -3596,11 +3596,11 @@  discard block
 block discarded – undo
3596 3596
 		$num = 0;
3597 3597
 
3598 3598
 		$sql = "SELECT rowid, label, bank, clos as status, currency_code";
3599
-		$sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
3600
-		$sql.= " WHERE entity IN (".getEntity('bank_account').")";
3601
-		if ($statut != 2) $sql.= " AND clos = '".$statut."'";
3602
-		if ($filtre) $sql.=" AND ".$filtre;
3603
-		$sql.= " ORDER BY label";
3599
+		$sql .= " FROM ".MAIN_DB_PREFIX."bank_account";
3600
+		$sql .= " WHERE entity IN (".getEntity('bank_account').")";
3601
+		if ($statut != 2) $sql .= " AND clos = '".$statut."'";
3602
+		if ($filtre) $sql .= " AND ".$filtre;
3603
+		$sql .= " ORDER BY label";
3604 3604
 
3605 3605
 		dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
3606 3606
 		$result = $this->db->query($sql);
@@ -3610,7 +3610,7 @@  discard block
 block discarded – undo
3610 3610
 			$i = 0;
3611 3611
 			if ($num)
3612 3612
 			{
3613
-				print '<select id="select'.$htmlname.'" class="flat selectbankaccount" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
3613
+				print '<select id="select'.$htmlname.'" class="flat selectbankaccount" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
3614 3614
 				if ($useempty == 1 || ($useempty == 2 && $num > 1))
3615 3615
 				{
3616 3616
 					print '<option value="-1">&nbsp;</option>';
@@ -3657,7 +3657,7 @@  discard block
 block discarded – undo
3657 3657
 	 *    @param    int		$addempty    1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries.
3658 3658
 	 *    @return	void
3659 3659
 	 */
3660
-	function formSelectAccount($page, $selected='', $htmlname='fk_account', $addempty=0)
3660
+	function formSelectAccount($page, $selected = '', $htmlname = 'fk_account', $addempty = 0)
3661 3661
 	{
3662 3662
 		global $langs;
3663 3663
 		if ($htmlname != "none") {
@@ -3672,8 +3672,8 @@  discard block
 block discarded – undo
3672 3672
 			$langs->load('banks');
3673 3673
 
3674 3674
 			if ($selected) {
3675
-				require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php';
3676
-				$bankstatic=new Account($this->db);
3675
+				require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
3676
+				$bankstatic = new Account($this->db);
3677 3677
 				$result = $bankstatic->fetch($selected);
3678 3678
 				if ($result) print $bankstatic->getNomUrl(1);
3679 3679
 			} else {
@@ -3695,7 +3695,7 @@  discard block
 block discarded – undo
3695 3695
 	 *    @return	string
3696 3696
 	 *    @see select_categories
3697 3697
 	 */
3698
-	function select_all_categories($type, $selected='', $htmlname="parent", $maxlength=64, $excludeafterid=0, $outputmode=0)
3698
+	function select_all_categories($type, $selected = '', $htmlname = "parent", $maxlength = 64, $excludeafterid = 0, $outputmode = 0)
3699 3699
 	{
3700 3700
         // phpcs:enable
3701 3701
 		global $conf, $langs;
@@ -3706,17 +3706,17 @@  discard block
 block discarded – undo
3706 3706
 		// For backward compatibility
3707 3707
 		if (is_numeric($type))
3708 3708
 		{
3709
-			dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
3709
+			dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
3710 3710
 		}
3711 3711
 
3712 3712
 		if ($type === Categorie::TYPE_BANK_LINE)
3713 3713
 		{
3714 3714
 			// TODO Move this into common category feature
3715
-			$categids=array();
3715
+			$categids = array();
3716 3716
 			$sql = "SELECT c.label, c.rowid";
3717
-			$sql.= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
3718
-			$sql.= " WHERE entity = ".$conf->entity;
3719
-			$sql.= " ORDER BY c.label";
3717
+			$sql .= " FROM ".MAIN_DB_PREFIX."bank_categ as c";
3718
+			$sql .= " WHERE entity = ".$conf->entity;
3719
+			$sql .= " ORDER BY c.label";
3720 3720
 			$result = $this->db->query($sql);
3721 3721
 			if ($result)
3722 3722
 			{
@@ -3725,7 +3725,7 @@  discard block
 block discarded – undo
3725 3725
 				while ($i < $num)
3726 3726
 				{
3727 3727
 					$objp = $this->db->fetch_object($result);
3728
-					if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
3728
+					if ($objp) $cate_arbo[$objp->rowid] = array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
3729 3729
 					$i++;
3730 3730
 				}
3731 3731
 				$this->db->free($result);
@@ -3739,14 +3739,14 @@  discard block
 block discarded – undo
3739 3739
 		}
3740 3740
 
3741 3741
 		$output = '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
3742
-		$outarray=array();
3742
+		$outarray = array();
3743 3743
 		if (is_array($cate_arbo))
3744 3744
 		{
3745
-			if (! count($cate_arbo)) $output.= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
3745
+			if (!count($cate_arbo)) $output .= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
3746 3746
 			else
3747 3747
 			{
3748
-				$output.= '<option value="-1">&nbsp;</option>';
3749
-				foreach($cate_arbo as $key => $value)
3748
+				$output .= '<option value="-1">&nbsp;</option>';
3749
+				foreach ($cate_arbo as $key => $value)
3750 3750
 				{
3751 3751
 					if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
3752 3752
 					{
@@ -3756,14 +3756,14 @@  discard block
 block discarded – undo
3756 3756
 					{
3757 3757
 						$add = '';
3758 3758
 					}
3759
-					$output.= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'],$maxlength,'middle').'</option>';
3759
+					$output .= '<option '.$add.'value="'.$cate_arbo[$key]['id'].'">'.dol_trunc($cate_arbo[$key]['fulllabel'], $maxlength, 'middle').'</option>';
3760 3760
 
3761 3761
 					$outarray[$cate_arbo[$key]['id']] = $cate_arbo[$key]['fulllabel'];
3762 3762
 				}
3763 3763
 			}
3764 3764
 		}
3765
-		$output.= '</select>';
3766
-		$output.= "\n";
3765
+		$output .= '</select>';
3766
+		$output .= "\n";
3767 3767
 
3768 3768
 		if ($outputmode) return $outarray;
3769 3769
 		return $output;
@@ -3786,10 +3786,10 @@  discard block
 block discarded – undo
3786 3786
 	 *     @deprecated
3787 3787
 	 *     @see formconfirm()
3788 3788
 	 */
3789
-	function form_confirm($page, $title, $question, $action, $formquestion='', $selectedchoice="", $useajax=0, $height=170, $width=500)
3789
+	function form_confirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = "", $useajax = 0, $height = 170, $width = 500)
3790 3790
 	{
3791 3791
         // phpcs:enable
3792
-        dol_syslog(__METHOD__ . ': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
3792
+        dol_syslog(__METHOD__.': using form_confirm is deprecated. Use formconfim instead.', LOG_WARNING);
3793 3793
 		print $this->formconfirm($page, $title, $question, $action, $formquestion, $selectedchoice, $useajax, $height, $width);
3794 3794
 	}
3795 3795
 
@@ -3817,93 +3817,93 @@  discard block
 block discarded – undo
3817 3817
 	 *     @param	int			$disableformtag		1=Disable form tag. Can be used if we are already inside a <form> section.
3818 3818
 	 *     @return 	string      	    			HTML ajax code if a confirm ajax popup is required, Pure HTML code if it's an html form
3819 3819
 	 */
3820
-	function formconfirm($page, $title, $question, $action, $formquestion='', $selectedchoice='', $useajax=0, $height=210, $width=500, $disableformtag=0)
3820
+	function formconfirm($page, $title, $question, $action, $formquestion = '', $selectedchoice = '', $useajax = 0, $height = 210, $width = 500, $disableformtag = 0)
3821 3821
 	{
3822
-		global $langs,$conf;
3822
+		global $langs, $conf;
3823 3823
 		global $useglobalvars;
3824 3824
 
3825
-		$more='';
3826
-		$formconfirm='';
3827
-		$inputok=array();
3828
-		$inputko=array();
3825
+		$more = '';
3826
+		$formconfirm = '';
3827
+		$inputok = array();
3828
+		$inputko = array();
3829 3829
 
3830 3830
 		// Clean parameters
3831
-		$newselectedchoice=empty($selectedchoice)?"no":$selectedchoice;
3832
-		if ($conf->browser->layout == 'phone') $width='95%';
3831
+		$newselectedchoice = empty($selectedchoice) ? "no" : $selectedchoice;
3832
+		if ($conf->browser->layout == 'phone') $width = '95%';
3833 3833
 
3834
-		if (is_array($formquestion) && ! empty($formquestion))
3834
+		if (is_array($formquestion) && !empty($formquestion))
3835 3835
 		{
3836 3836
 			// First add hidden fields and value
3837 3837
 			foreach ($formquestion as $key => $input)
3838 3838
 			{
3839
-				if (is_array($input) && ! empty($input))
3839
+				if (is_array($input) && !empty($input))
3840 3840
 				{
3841 3841
 					if ($input['type'] == 'hidden')
3842 3842
 					{
3843
-						$more.='<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
3843
+						$more .= '<input type="hidden" id="'.$input['name'].'" name="'.$input['name'].'" value="'.dol_escape_htmltag($input['value']).'">'."\n";
3844 3844
 					}
3845 3845
 				}
3846 3846
 			}
3847 3847
 
3848 3848
 			// Now add questions
3849
-			$more.='<table class="paddingtopbottomonly" width="100%">'."\n";
3850
-			if (! empty($formquestion['text'])) $more.='<tr><td colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
3849
+			$more .= '<table class="paddingtopbottomonly" width="100%">'."\n";
3850
+			if (!empty($formquestion['text'])) $more .= '<tr><td colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
3851 3851
 			foreach ($formquestion as $key => $input)
3852 3852
 			{
3853
-				if (is_array($input) && ! empty($input))
3853
+				if (is_array($input) && !empty($input))
3854 3854
 				{
3855
-					$size=(! empty($input['size'])?' size="'.$input['size'].'"':'');
3856
-					$moreattr=(! empty($input['moreattr'])?' '.$input['moreattr']:'');
3857
-					$morecss=(! empty($input['morecss'])?' '.$input['morecss']:'');
3855
+					$size = (!empty($input['size']) ? ' size="'.$input['size'].'"' : '');
3856
+					$moreattr = (!empty($input['moreattr']) ? ' '.$input['moreattr'] : '');
3857
+					$morecss = (!empty($input['morecss']) ? ' '.$input['morecss'] : '');
3858 3858
 
3859 3859
 					if ($input['type'] == 'text')
3860 3860
 					{
3861
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="text" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3861
+						$more .= '<tr><td'.(empty($input['tdclass']) ? '' : (' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="text" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3862 3862
 					}
3863 3863
 					elseif ($input['type'] == 'password')
3864 3864
 					{
3865
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="password" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3865
+						$more .= '<tr><td'.(empty($input['tdclass']) ? '' : (' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="password" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3866 3866
 					}
3867 3867
 					elseif ($input['type'] == 'select')
3868 3868
 					{
3869
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
3870
-						if (! empty($input['label'])) $more.=$input['label'].'</td><td class="tdtop" align="left">';
3871
-						$more.=$this->selectarray($input['name'],$input['values'],$input['default'],1,0,0,$moreattr,0,0,0,'',$morecss);
3872
-						$more.='</td></tr>'."\n";
3869
+						$more .= '<tr><td'.(empty($input['tdclass']) ? '' : (' class="'.$input['tdclass'].'"')).'>';
3870
+						if (!empty($input['label'])) $more .= $input['label'].'</td><td class="tdtop" align="left">';
3871
+						$more .= $this->selectarray($input['name'], $input['values'], $input['default'], 1, 0, 0, $moreattr, 0, 0, 0, '', $morecss);
3872
+						$more .= '</td></tr>'."\n";
3873 3873
 					}
3874 3874
 					elseif ($input['type'] == 'checkbox')
3875 3875
 					{
3876
-						$more.='<tr>';
3877
-						$more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].' </td><td align="left">';
3878
-						$more.='<input type="checkbox" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$moreattr;
3879
-						if (! is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') $more.=' checked';
3880
-						if (is_bool($input['value']) && $input['value']) $more.=' checked';
3881
-						if (isset($input['disabled'])) $more.=' disabled';
3882
-						$more.=' /></td>';
3883
-						$more.='</tr>'."\n";
3876
+						$more .= '<tr>';
3877
+						$more .= '<td'.(empty($input['tdclass']) ? '' : (' class="'.$input['tdclass'].'"')).'>'.$input['label'].' </td><td align="left">';
3878
+						$more .= '<input type="checkbox" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$moreattr;
3879
+						if (!is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') $more .= ' checked';
3880
+						if (is_bool($input['value']) && $input['value']) $more .= ' checked';
3881
+						if (isset($input['disabled'])) $more .= ' disabled';
3882
+						$more .= ' /></td>';
3883
+						$more .= '</tr>'."\n";
3884 3884
 					}
3885 3885
 					elseif ($input['type'] == 'radio')
3886 3886
 					{
3887
-						$i=0;
3888
-						foreach($input['values'] as $selkey => $selval)
3887
+						$i = 0;
3888
+						foreach ($input['values'] as $selkey => $selval)
3889 3889
 						{
3890
-							$more.='<tr>';
3891
-							if ($i==0) $more.='<td'.(empty($input['tdclass'])?' class="tdtop"':(' class="tdtop '.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3892
-							else $more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>&nbsp;</td>';
3893
-							$more.='<td><input type="radio" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"'.$moreattr;
3894
-							if ($input['disabled']) $more.=' disabled';
3895
-							$more.=' /> ';
3896
-							$more.=$selval;
3897
-							$more.='</td></tr>'."\n";
3890
+							$more .= '<tr>';
3891
+							if ($i == 0) $more .= '<td'.(empty($input['tdclass']) ? ' class="tdtop"' : (' class="tdtop '.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3892
+							else $more .= '<td'.(empty($input['tdclass']) ? '' : (' class="'.$input['tdclass'].'"')).'>&nbsp;</td>';
3893
+							$more .= '<td><input type="radio" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"'.$moreattr;
3894
+							if ($input['disabled']) $more .= ' disabled';
3895
+							$more .= ' /> ';
3896
+							$more .= $selval;
3897
+							$more .= '</td></tr>'."\n";
3898 3898
 							$i++;
3899 3899
 						}
3900 3900
 					}
3901 3901
 					elseif ($input['type'] == 'date')
3902 3902
 					{
3903
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3904
-						$more.='<td align="left">';
3905
-						$more.=$this->selectDate($input['value'],$input['name'],0,0,0,'',1,0);
3906
-						$more.='</td></tr>'."\n";
3903
+						$more .= '<tr><td'.(empty($input['tdclass']) ? '' : (' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3904
+						$more .= '<td align="left">';
3905
+						$more .= $this->selectDate($input['value'], $input['name'], 0, 0, 0, '', 1, 0);
3906
+						$more .= '</td></tr>'."\n";
3907 3907
 						$formquestion[] = array('name'=>$input['name'].'day');
3908 3908
 						$formquestion[] = array('name'=>$input['name'].'month');
3909 3909
 						$formquestion[] = array('name'=>$input['name'].'year');
@@ -3912,76 +3912,76 @@  discard block
 block discarded – undo
3912 3912
 					}
3913 3913
 					elseif ($input['type'] == 'other')
3914 3914
 					{
3915
-						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
3916
-						if (! empty($input['label'])) $more.=$input['label'].'</td><td align="left">';
3917
-						$more.=$input['value'];
3918
-						$more.='</td></tr>'."\n";
3915
+						$more .= '<tr><td'.(empty($input['tdclass']) ? '' : (' class="'.$input['tdclass'].'"')).'>';
3916
+						if (!empty($input['label'])) $more .= $input['label'].'</td><td align="left">';
3917
+						$more .= $input['value'];
3918
+						$more .= '</td></tr>'."\n";
3919 3919
 					}
3920 3920
 
3921 3921
 					elseif ($input['type'] == 'onecolumn')
3922 3922
 					{
3923
-						$more.='<tr><td colspan="2" align="left">';
3924
-						$more.=$input['value'];
3925
-						$more.='</td></tr>'."\n";
3923
+						$more .= '<tr><td colspan="2" align="left">';
3924
+						$more .= $input['value'];
3925
+						$more .= '</td></tr>'."\n";
3926 3926
 					}
3927 3927
 				}
3928 3928
 			}
3929
-			$more.='</table>'."\n";
3929
+			$more .= '</table>'."\n";
3930 3930
 		}
3931 3931
 
3932 3932
 		// JQUI method dialog is broken with jmobile, we use standard HTML.
3933 3933
 		// Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx
3934 3934
 		// See page product/card.php for example
3935
-		if (! empty($conf->dol_use_jmobile)) $useajax=0;
3936
-		if (empty($conf->use_javascript_ajax)) $useajax=0;
3935
+		if (!empty($conf->dol_use_jmobile)) $useajax = 0;
3936
+		if (empty($conf->use_javascript_ajax)) $useajax = 0;
3937 3937
 
3938 3938
 		if ($useajax)
3939 3939
 		{
3940
-			$autoOpen=true;
3941
-			$dialogconfirm='dialog-confirm';
3942
-			$button='';
3943
-			if (! is_numeric($useajax))
3940
+			$autoOpen = true;
3941
+			$dialogconfirm = 'dialog-confirm';
3942
+			$button = '';
3943
+			if (!is_numeric($useajax))
3944 3944
 			{
3945
-				$button=$useajax;
3946
-				$useajax=1;
3947
-				$autoOpen=false;
3948
-				$dialogconfirm.='-'.$button;
3945
+				$button = $useajax;
3946
+				$useajax = 1;
3947
+				$autoOpen = false;
3948
+				$dialogconfirm .= '-'.$button;
3949 3949
 			}
3950
-			$pageyes=$page.(preg_match('/\?/',$page)?'&':'?').'action='.$action.'&confirm=yes';
3951
-			$pageno=($useajax == 2 ? $page.(preg_match('/\?/',$page)?'&':'?').'confirm=no':'');
3950
+			$pageyes = $page.(preg_match('/\?/', $page) ? '&' : '?').'action='.$action.'&confirm=yes';
3951
+			$pageno = ($useajax == 2 ? $page.(preg_match('/\?/', $page) ? '&' : '?').'confirm=no' : '');
3952 3952
 			// Add input fields into list of fields to read during submit (inputok and inputko)
3953 3953
 			if (is_array($formquestion))
3954 3954
 			{
3955 3955
 				foreach ($formquestion as $key => $input)
3956 3956
 				{
3957 3957
 					//print "xx ".$key." rr ".is_array($input)."<br>\n";
3958
-					if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']);
3959
-					if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']);
3958
+					if (is_array($input) && isset($input['name'])) array_push($inputok, $input['name']);
3959
+					if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko, $input['name']);
3960 3960
 				}
3961 3961
 			}
3962 3962
 			// Show JQuery confirm box. Note that global var $useglobalvars is used inside this template
3963
-			$formconfirm.= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
3964
-			if (! empty($more)) {
3965
-				$formconfirm.= '<div class="confirmquestions">'.$more.'</div>';
3963
+			$formconfirm .= '<div id="'.$dialogconfirm.'" title="'.dol_escape_htmltag($title).'" style="display: none;">';
3964
+			if (!empty($more)) {
3965
+				$formconfirm .= '<div class="confirmquestions">'.$more.'</div>';
3966 3966
 			}
3967
-			$formconfirm.= ($question ? '<div class="confirmmessage">'.img_help('','').' '.$question . '</div>': '');
3968
-			$formconfirm.= '</div>'."\n";
3967
+			$formconfirm .= ($question ? '<div class="confirmmessage">'.img_help('', '').' '.$question.'</div>' : '');
3968
+			$formconfirm .= '</div>'."\n";
3969 3969
 
3970
-			$formconfirm.= "\n<!-- begin ajax formconfirm page=".$page." -->\n";
3971
-			$formconfirm.= '<script type="text/javascript">'."\n";
3972
-			$formconfirm.= 'jQuery(document).ready(function() {
3970
+			$formconfirm .= "\n<!-- begin ajax formconfirm page=".$page." -->\n";
3971
+			$formconfirm .= '<script type="text/javascript">'."\n";
3972
+			$formconfirm .= 'jQuery(document).ready(function() {
3973 3973
             $(function() {
3974 3974
             	$( "#'.$dialogconfirm.'" ).dialog(
3975 3975
             	{
3976 3976
                     autoOpen: '.($autoOpen ? "true" : "false").',';
3977 3977
 			if ($newselectedchoice == 'no')
3978 3978
 			{
3979
-				$formconfirm.='
3979
+				$formconfirm .= '
3980 3980
 						open: function() {
3981 3981
             				$(this).parent().find("button.ui-button:eq(2)").focus();
3982 3982
 						},';
3983 3983
 			}
3984
-			$formconfirm.='
3984
+			$formconfirm .= '
3985 3985
                     resizable: false,
3986 3986
                     height: "'.$height.'",
3987 3987
                     width: "'.$width.'",
@@ -3991,7 +3991,7 @@  discard block
 block discarded – undo
3991 3991
                         "'.dol_escape_js($langs->transnoentities("Yes")).'": function() {
3992 3992
                         	var options="";
3993 3993
                         	var inputok = '.json_encode($inputok).';
3994
-                         	var pageyes = "'.dol_escape_js(! empty($pageyes)?$pageyes:'').'";
3994
+                         	var pageyes = "'.dol_escape_js(!empty($pageyes) ? $pageyes : '').'";
3995 3995
                          	if (inputok.length>0) {
3996 3996
                          		$.each(inputok, function(i, inputname) {
3997 3997
                          			var more = "";
@@ -4010,7 +4010,7 @@  discard block
 block discarded – undo
4010 4010
                         "'.dol_escape_js($langs->transnoentities("No")).'": function() {
4011 4011
                         	var options = "";
4012 4012
                          	var inputko = '.json_encode($inputko).';
4013
-                         	var pageno="'.dol_escape_js(! empty($pageno)?$pageno:'').'";
4013
+                         	var pageno="'.dol_escape_js(!empty($pageno) ? $pageno : '').'";
4014 4014
                          	if (inputko.length>0) {
4015 4015
                          		$.each(inputko, function(i, inputname) {
4016 4016
                          			var more = "";
@@ -4038,45 +4038,45 @@  discard block
 block discarded – undo
4038 4038
             });
4039 4039
             });
4040 4040
             </script>';
4041
-			$formconfirm.= "<!-- end ajax formconfirm -->\n";
4041
+			$formconfirm .= "<!-- end ajax formconfirm -->\n";
4042 4042
 		}
4043 4043
 		else
4044 4044
 		{
4045
-			$formconfirm.= "\n<!-- begin formconfirm page=".$page." -->\n";
4045
+			$formconfirm .= "\n<!-- begin formconfirm page=".$page." -->\n";
4046 4046
 
4047
-			if (empty($disableformtag)) $formconfirm.= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
4047
+			if (empty($disableformtag)) $formconfirm .= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
4048 4048
 
4049
-			$formconfirm.= '<input type="hidden" name="action" value="'.$action.'">'."\n";
4050
-			if (empty($disableformtag)) $formconfirm.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
4049
+			$formconfirm .= '<input type="hidden" name="action" value="'.$action.'">'."\n";
4050
+			if (empty($disableformtag)) $formconfirm .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
4051 4051
 
4052
-			$formconfirm.= '<table width="100%" class="valid">'."\n";
4052
+			$formconfirm .= '<table width="100%" class="valid">'."\n";
4053 4053
 
4054 4054
 			// Line title
4055
-			$formconfirm.= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('','recent').' '.$title.'</td></tr>'."\n";
4055
+			$formconfirm .= '<tr class="validtitre"><td class="validtitre" colspan="3">'.img_picto('', 'recent').' '.$title.'</td></tr>'."\n";
4056 4056
 
4057 4057
 			// Line form fields
4058 4058
 			if ($more)
4059 4059
 			{
4060
-				$formconfirm.='<tr class="valid"><td class="valid" colspan="3">'."\n";
4061
-				$formconfirm.=$more;
4062
-				$formconfirm.='</td></tr>'."\n";
4060
+				$formconfirm .= '<tr class="valid"><td class="valid" colspan="3">'."\n";
4061
+				$formconfirm .= $more;
4062
+				$formconfirm .= '</td></tr>'."\n";
4063 4063
 			}
4064 4064
 
4065 4065
 			// Line with question
4066
-			$formconfirm.= '<tr class="valid">';
4067
-			$formconfirm.= '<td class="valid">'.$question.'</td>';
4068
-			$formconfirm.= '<td class="valid">';
4069
-			$formconfirm.= $this->selectyesno("confirm",$newselectedchoice);
4070
-			$formconfirm.= '</td>';
4071
-			$formconfirm.= '<td class="valid" align="center"><input class="button valignmiddle" type="submit" value="'.$langs->trans("Validate").'"></td>';
4072
-			$formconfirm.= '</tr>'."\n";
4066
+			$formconfirm .= '<tr class="valid">';
4067
+			$formconfirm .= '<td class="valid">'.$question.'</td>';
4068
+			$formconfirm .= '<td class="valid">';
4069
+			$formconfirm .= $this->selectyesno("confirm", $newselectedchoice);
4070
+			$formconfirm .= '</td>';
4071
+			$formconfirm .= '<td class="valid" align="center"><input class="button valignmiddle" type="submit" value="'.$langs->trans("Validate").'"></td>';
4072
+			$formconfirm .= '</tr>'."\n";
4073 4073
 
4074
-			$formconfirm.= '</table>'."\n";
4074
+			$formconfirm .= '</table>'."\n";
4075 4075
 
4076
-			if (empty($disableformtag)) $formconfirm.= "</form>\n";
4077
-			$formconfirm.= '<br>';
4076
+			if (empty($disableformtag)) $formconfirm .= "</form>\n";
4077
+			$formconfirm .= '<br>';
4078 4078
 
4079
-			$formconfirm.= "<!-- end formconfirm -->\n";
4079
+			$formconfirm .= "<!-- end formconfirm -->\n";
4080 4080
 		}
4081 4081
 
4082 4082
 		return $formconfirm;
@@ -4097,7 +4097,7 @@  discard block
 block discarded – undo
4097 4097
 	 *    @param    int     $nooutput           No print is done. String is returned.
4098 4098
 	 *    @return	string                      Return html content
4099 4099
 	 */
4100
-	function form_project($page, $socid, $selected='', $htmlname='projectid', $discard_closed=0, $maxlength=20, $forcefocus=0, $nooutput=0)
4100
+	function form_project($page, $socid, $selected = '', $htmlname = 'projectid', $discard_closed = 0, $maxlength = 20, $forcefocus = 0, $nooutput = 0)
4101 4101
 	{
4102 4102
         // phpcs:enable
4103 4103
 		global $langs;
@@ -4105,20 +4105,20 @@  discard block
 block discarded – undo
4105 4105
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/project.lib.php';
4106 4106
 		require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php';
4107 4107
 
4108
-		$out='';
4108
+		$out = '';
4109 4109
 
4110
-		$formproject=new FormProjets($this->db);
4110
+		$formproject = new FormProjets($this->db);
4111 4111
 
4112 4112
 		$langs->load("project");
4113 4113
 		if ($htmlname != "none")
4114 4114
 		{
4115
-			$out.="\n";
4116
-			$out.='<form method="post" action="'.$page.'">';
4117
-			$out.='<input type="hidden" name="action" value="classin">';
4118
-			$out.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4119
-			$out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
4120
-			$out.='<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4121
-			$out.='</form>';
4115
+			$out .= "\n";
4116
+			$out .= '<form method="post" action="'.$page.'">';
4117
+			$out .= '<input type="hidden" name="action" value="classin">';
4118
+			$out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4119
+			$out .= $formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
4120
+			$out .= '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4121
+			$out .= '</form>';
4122 4122
 		}
4123 4123
 		else
4124 4124
 		{
@@ -4127,11 +4127,11 @@  discard block
 block discarded – undo
4127 4127
 				$projet = new Project($this->db);
4128 4128
 				$projet->fetch($selected);
4129 4129
 				//print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
4130
-				$out.=$projet->getNomUrl(0,'',1);
4130
+				$out .= $projet->getNomUrl(0, '', 1);
4131 4131
 			}
4132 4132
 			else
4133 4133
 			{
4134
-				$out.="&nbsp;";
4134
+				$out .= "&nbsp;";
4135 4135
 			}
4136 4136
 		}
4137 4137
 
@@ -4153,7 +4153,7 @@  discard block
 block discarded – undo
4153 4153
 	 *	@param	int		$addempty		Add empty entry
4154 4154
 	 *  @return	void
4155 4155
 	 */
4156
-	function form_conditions_reglement($page, $selected='', $htmlname='cond_reglement_id', $addempty=0)
4156
+	function form_conditions_reglement($page, $selected = '', $htmlname = 'cond_reglement_id', $addempty = 0)
4157 4157
 	{
4158 4158
         // phpcs:enable
4159 4159
 		global $langs;
@@ -4162,7 +4162,7 @@  discard block
 block discarded – undo
4162 4162
 			print '<form method="post" action="'.$page.'">';
4163 4163
 			print '<input type="hidden" name="action" value="setconditions">';
4164 4164
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4165
-			$this->select_conditions_paiements($selected,$htmlname,-1,$addempty);
4165
+			$this->select_conditions_paiements($selected, $htmlname, -1, $addempty);
4166 4166
 			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4167 4167
 			print '</form>';
4168 4168
 		}
@@ -4188,7 +4188,7 @@  discard block
 block discarded – undo
4188 4188
 	 *	@param	int		$addempty		Ajoute entree vide
4189 4189
 	 *  @return	void
4190 4190
 	 */
4191
-	function form_availability($page, $selected='', $htmlname='availability', $addempty=0)
4191
+	function form_availability($page, $selected = '', $htmlname = 'availability', $addempty = 0)
4192 4192
 	{
4193 4193
         // phpcs:enable
4194 4194
 		global $langs;
@@ -4197,7 +4197,7 @@  discard block
 block discarded – undo
4197 4197
 			print '<form method="post" action="'.$page.'">';
4198 4198
 			print '<input type="hidden" name="action" value="setavailability">';
4199 4199
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4200
-			$this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty);
4200
+			$this->selectAvailabilityDelay($selected, $htmlname, -1, $addempty);
4201 4201
 			print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4202 4202
 			print '</form>';
4203 4203
 		}
@@ -4223,7 +4223,7 @@  discard block
 block discarded – undo
4223 4223
 	 *	@param	int		$addempty		Add empty entry
4224 4224
 	 *  @return	void
4225 4225
 	 */
4226
-	function formInputReason($page, $selected='', $htmlname='demandreason', $addempty=0)
4226
+	function formInputReason($page, $selected = '', $htmlname = 'demandreason', $addempty = 0)
4227 4227
 	{
4228 4228
 		global $langs;
4229 4229
 		if ($htmlname != "none")
@@ -4231,7 +4231,7 @@  discard block
 block discarded – undo
4231 4231
 			print '<form method="post" action="'.$page.'">';
4232 4232
 			print '<input type="hidden" name="action" value="setdemandreason">';
4233 4233
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4234
-			$this->selectInputReason($selected,$htmlname,-1,$addempty);
4234
+			$this->selectInputReason($selected, $htmlname, -1, $addempty);
4235 4235
 			print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4236 4236
 			print '</form>';
4237 4237
 		}
@@ -4267,29 +4267,29 @@  discard block
 block discarded – undo
4267 4267
 	 *    @return	string
4268 4268
 	 *    @see		selectDate
4269 4269
 	 */
4270
-	function form_date($page, $selected, $htmlname, $displayhour=0, $displaymin=0, $nooutput=0)
4270
+	function form_date($page, $selected, $htmlname, $displayhour = 0, $displaymin = 0, $nooutput = 0)
4271 4271
 	{
4272 4272
         // phpcs:enable
4273 4273
 		global $langs;
4274 4274
 
4275
-		$ret='';
4275
+		$ret = '';
4276 4276
 
4277 4277
 		if ($htmlname != "none")
4278 4278
 		{
4279
-			$ret.='<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
4280
-			$ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
4281
-			$ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4282
-			$ret.='<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
4283
-			$ret.='<tr><td>';
4284
-			$ret.=$this->selectDate($selected,$htmlname,$displayhour,$displaymin,1,'form'.$htmlname,1,0);
4285
-			$ret.='</td>';
4286
-			$ret.='<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
4287
-			$ret.='</tr></table></form>';
4279
+			$ret .= '<form method="post" action="'.$page.'" name="form'.$htmlname.'">';
4280
+			$ret .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
4281
+			$ret .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4282
+			$ret .= '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
4283
+			$ret .= '<tr><td>';
4284
+			$ret .= $this->selectDate($selected, $htmlname, $displayhour, $displaymin, 1, 'form'.$htmlname, 1, 0);
4285
+			$ret .= '</td>';
4286
+			$ret .= '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
4287
+			$ret .= '</tr></table></form>';
4288 4288
 		}
4289 4289
 		else
4290 4290
 		{
4291
-			if ($displayhour) $ret.=dol_print_date($selected,'dayhour');
4292
-			else $ret.=dol_print_date($selected,'day');
4291
+			if ($displayhour) $ret .= dol_print_date($selected, 'dayhour');
4292
+			else $ret .= dol_print_date($selected, 'day');
4293 4293
 		}
4294 4294
 
4295 4295
 		if (empty($nooutput)) print $ret;
@@ -4308,7 +4308,7 @@  discard block
 block discarded – undo
4308 4308
 	 *  @param  array	$include        List of users id to include
4309 4309
 	 *  @return	void
4310 4310
 	 */
4311
-	function form_users($page, $selected='', $htmlname='userid', $exclude='', $include='')
4311
+	function form_users($page, $selected = '', $htmlname = 'userid', $exclude = '', $include = '')
4312 4312
 	{
4313 4313
         // phpcs:enable
4314 4314
 		global $langs;
@@ -4318,7 +4318,7 @@  discard block
 block discarded – undo
4318 4318
 			print '<form method="POST" action="'.$page.'" name="form'.$htmlname.'">';
4319 4319
 			print '<input type="hidden" name="action" value="set'.$htmlname.'">';
4320 4320
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4321
-			print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include);
4321
+			print $this->select_dolusers($selected, $htmlname, 1, $exclude, 0, $include);
4322 4322
 			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4323 4323
 			print '</form>';
4324 4324
 		}
@@ -4326,8 +4326,8 @@  discard block
 block discarded – undo
4326 4326
 		{
4327 4327
 			if ($selected)
4328 4328
 			{
4329
-				require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';
4330
-				$theuser=new User($this->db);
4329
+				require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
4330
+				$theuser = new User($this->db);
4331 4331
 				$theuser->fetch($selected);
4332 4332
 				print $theuser->getNomUrl(1);
4333 4333
 			} else {
@@ -4348,7 +4348,7 @@  discard block
 block discarded – undo
4348 4348
 	 *    @param    int     $active         Active or not, -1 = all
4349 4349
 	 *    @return	void
4350 4350
 	 */
4351
-	function form_modes_reglement($page, $selected='', $htmlname='mode_reglement_id', $filtertype='', $active=1)
4351
+	function form_modes_reglement($page, $selected = '', $htmlname = 'mode_reglement_id', $filtertype = '', $active = 1)
4352 4352
 	{
4353 4353
         // phpcs:enable
4354 4354
 		global $langs;
@@ -4357,7 +4357,7 @@  discard block
 block discarded – undo
4357 4357
 			print '<form method="POST" action="'.$page.'">';
4358 4358
 			print '<input type="hidden" name="action" value="setmode">';
4359 4359
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4360
-			$this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active);
4360
+			$this->select_types_paiements($selected, $htmlname, $filtertype, 0, 0, 0, 0, $active);
4361 4361
 			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4362 4362
 			print '</form>';
4363 4363
 		}
@@ -4382,7 +4382,7 @@  discard block
 block discarded – undo
4382 4382
 	 *    @param    string	$htmlname    	Name of select html field
4383 4383
 	 *    @return	void
4384 4384
 	 */
4385
-	function form_multicurrency_code($page, $selected='', $htmlname='multicurrency_code')
4385
+	function form_multicurrency_code($page, $selected = '', $htmlname = 'multicurrency_code')
4386 4386
 	{
4387 4387
         // phpcs:enable
4388 4388
 		global $langs;
@@ -4398,7 +4398,7 @@  discard block
 block discarded – undo
4398 4398
 		else
4399 4399
 		{
4400 4400
 			dol_include_once('/core/lib/company.lib.php');
4401
-			print !empty($selected) ? currency_name($selected,1) : '&nbsp;';
4401
+			print !empty($selected) ? currency_name($selected, 1) : '&nbsp;';
4402 4402
 		}
4403 4403
 	}
4404 4404
 
@@ -4412,7 +4412,7 @@  discard block
 block discarded – undo
4412 4412
 	 *    @param    string  $currency       Currency code to explain the rate
4413 4413
 	 *    @return	void
4414 4414
 	 */
4415
-	function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='')
4415
+	function form_multicurrency_rate($page, $rate = '', $htmlname = 'multicurrency_tx', $currency = '')
4416 4416
 	{
4417 4417
         // phpcs:enable
4418 4418
 		global $langs, $mysoc, $conf;
@@ -4432,7 +4432,7 @@  discard block
 block discarded – undo
4432 4432
 		}
4433 4433
 		else
4434 4434
 		{
4435
-			if (! empty($rate))
4435
+			if (!empty($rate))
4436 4436
 			{
4437 4437
 				print price($rate, 1, $langs, 1, 0);
4438 4438
 				if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
@@ -4461,59 +4461,59 @@  discard block
 block discarded – undo
4461 4461
 	 *  @param	int		$discount_type	0 => customer discount, 1 => supplier discount
4462 4462
 	 *  @return	void
4463 4463
 	 */
4464
-	function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter='', $maxvalue=0, $more='', $hidelist=0, $discount_type=0)
4464
+	function form_remise_dispo($page, $selected, $htmlname, $socid, $amount, $filter = '', $maxvalue = 0, $more = '', $hidelist = 0, $discount_type = 0)
4465 4465
 	{
4466 4466
         // phpcs:enable
4467
-		global $conf,$langs;
4467
+		global $conf, $langs;
4468 4468
 		if ($htmlname != "none")
4469 4469
 		{
4470 4470
 			print '<form method="post" action="'.$page.'">';
4471 4471
 			print '<input type="hidden" name="action" value="setabsolutediscount">';
4472 4472
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4473 4473
 			print '<div class="inline-block">';
4474
-			if(! empty($discount_type)) {
4475
-				if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4474
+			if (!empty($discount_type)) {
4475
+				if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4476 4476
 				{
4477
-					if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier';    // If we want deposit to be substracted to payments only and not to total of final invoice
4477
+					if (!$filter || $filter == "fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier'; // If we want deposit to be substracted to payments only and not to total of final invoice
4478 4478
 					else $translationKey = 'HasCreditNoteFromSupplier';
4479 4479
 				}
4480 4480
 				else
4481 4481
 				{
4482
-					if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier';
4482
+					if (!$filter || $filter == "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier';
4483 4483
 					else $translationKey = 'HasCreditNoteFromSupplier';
4484 4484
 				}
4485 4485
 			} else {
4486
-				if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4486
+				if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4487 4487
 				{
4488
-					if (! $filter || $filter=="fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount';    // If we want deposit to be substracted to payments only and not to total of final invoice
4488
+					if (!$filter || $filter == "fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount'; // If we want deposit to be substracted to payments only and not to total of final invoice
4489 4489
 					else $translationKey = 'CompanyHasCreditNote';
4490 4490
 				}
4491 4491
 				else
4492 4492
 				{
4493
-					if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount';
4493
+					if (!$filter || $filter == "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount';
4494 4494
 					else $translationKey = 'CompanyHasCreditNote';
4495 4495
 				}
4496 4496
 			}
4497
-			print $langs->trans($translationKey,price($amount,0,$langs,0,0,-1,$conf->currency));
4497
+			print $langs->trans($translationKey, price($amount, 0, $langs, 0, 0, -1, $conf->currency));
4498 4498
 			if (empty($hidelist)) print ': ';
4499 4499
 			print '</div>';
4500 4500
 			if (empty($hidelist))
4501 4501
 			{
4502 4502
 				print '<div class="inline-block" style="padding-right: 10px">';
4503 4503
 				$newfilter = 'discount_type='.intval($discount_type);
4504
-				if(! empty($discount_type)) {
4505
-					$newfilter.= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
4504
+				if (!empty($discount_type)) {
4505
+					$newfilter .= ' AND fk_invoice_supplier IS NULL AND fk_invoice_supplier_line IS NULL'; // Supplier discounts available
4506 4506
 				} else {
4507
-					$newfilter.= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
4507
+					$newfilter .= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
4508 4508
 				}
4509
-				if ($filter) $newfilter.=' AND ('.$filter.')';
4510
-				$nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);
4509
+				if ($filter) $newfilter .= ' AND ('.$filter.')';
4510
+				$nbqualifiedlines = $this->select_remises($selected, $htmlname, $newfilter, $socid, $maxvalue);
4511 4511
 				if ($nbqualifiedlines > 0)
4512 4512
 				{
4513 4513
 					print ' &nbsp; <input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
4514
-					if(! empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')")
4514
+					if (!empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')")
4515 4515
 						print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4516
-					if(empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')")
4516
+					if (empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')")
4517 4517
 						print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4518 4518
 
4519 4519
 					print '>';
@@ -4552,7 +4552,7 @@  discard block
 block discarded – undo
4552 4552
 	 *    @param    string		$htmlname    	Name of HTML select. If 'none', we just show contact link.
4553 4553
 	 *    @return	void
4554 4554
 	 */
4555
-	function form_contacts($page, $societe, $selected='', $htmlname='contactid')
4555
+	function form_contacts($page, $societe, $selected = '', $htmlname = 'contactid')
4556 4556
 	{
4557 4557
         // phpcs:enable
4558 4558
 		global $langs, $conf;
@@ -4564,10 +4564,10 @@  discard block
 block discarded – undo
4564 4564
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4565 4565
 			print '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
4566 4566
 			print '<tr><td>';
4567
-			$num=$this->select_contacts($societe->id, $selected, $htmlname);
4568
-			if ($num==0)
4567
+			$num = $this->select_contacts($societe->id, $selected, $htmlname);
4568
+			if ($num == 0)
4569 4569
 			{
4570
-				$addcontact = (! empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
4570
+				$addcontact = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("AddContact") : $langs->trans("AddContactAddress"));
4571 4571
 				print '<a href="'.DOL_URL_ROOT.'/contact/card.php?socid='.$societe->id.'&amp;action=create&amp;backtoreferer=1">'.$addcontact.'</a>';
4572 4572
 			}
4573 4573
 			print '</td>';
@@ -4578,8 +4578,8 @@  discard block
 block discarded – undo
4578 4578
 		{
4579 4579
 			if ($selected)
4580 4580
 			{
4581
-				require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php';
4582
-				$contact=new Contact($this->db);
4581
+				require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
4582
+				$contact = new Contact($this->db);
4583 4583
 				$contact->fetch($selected);
4584 4584
 				print $contact->getFullName($langs);
4585 4585
 			} else {
@@ -4603,7 +4603,7 @@  discard block
 block discarded – undo
4603 4603
 	 *  @param  int     $nooutput       No print output. Return it only.
4604 4604
 	 *  @return	void
4605 4605
 	 */
4606
-	function form_thirdparty($page, $selected='', $htmlname='socid', $filter='',$showempty=0, $showtype=0, $forcecombo=0, $events=array(), $nooutput=0)
4606
+	function form_thirdparty($page, $selected = '', $htmlname = 'socid', $filter = '', $showempty = 0, $showtype = 0, $forcecombo = 0, $events = array(), $nooutput = 0)
4607 4607
 	{
4608 4608
         // phpcs:enable
4609 4609
 		global $langs;
@@ -4611,25 +4611,25 @@  discard block
 block discarded – undo
4611 4611
 		$out = '';
4612 4612
 		if ($htmlname != "none")
4613 4613
 		{
4614
-			$out.='<form method="post" action="'.$page.'">';
4615
-			$out.= '<input type="hidden" name="action" value="set_thirdparty">';
4616
-			$out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4617
-			$out.= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
4618
-			$out.= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4619
-			$out.= '</form>';
4614
+			$out .= '<form method="post" action="'.$page.'">';
4615
+			$out .= '<input type="hidden" name="action" value="set_thirdparty">';
4616
+			$out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
4617
+			$out .= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
4618
+			$out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4619
+			$out .= '</form>';
4620 4620
 		}
4621 4621
 		else
4622 4622
 		{
4623 4623
 			if ($selected)
4624 4624
 			{
4625
-				require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
4625
+				require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
4626 4626
 				$soc = new Societe($this->db);
4627 4627
 				$soc->fetch($selected);
4628
-				$out.= $soc->getNomUrl($langs);
4628
+				$out .= $soc->getNomUrl($langs);
4629 4629
 			}
4630 4630
 			else
4631 4631
 			{
4632
-				$out.= "&nbsp;";
4632
+				$out .= "&nbsp;";
4633 4633
 			}
4634 4634
 		}
4635 4635
 
@@ -4646,10 +4646,10 @@  discard block
 block discarded – undo
4646 4646
      *    @deprecated
4647 4647
 	 *    @return	void
4648 4648
 	 */
4649
-	function select_currency($selected='',$htmlname='currency_id')
4649
+	function select_currency($selected = '', $htmlname = 'currency_id')
4650 4650
 	{
4651 4651
         // phpcs:enable
4652
-		print $this->selectCurrency($selected,$htmlname);
4652
+		print $this->selectCurrency($selected, $htmlname);
4653 4653
 	}
4654 4654
 
4655 4655
 	/**
@@ -4659,36 +4659,36 @@  discard block
 block discarded – undo
4659 4659
 	 *  @param  string	$htmlname    name of HTML select list
4660 4660
 	 * 	@return	string
4661 4661
 	 */
4662
-	function selectCurrency($selected='',$htmlname='currency_id')
4662
+	function selectCurrency($selected = '', $htmlname = 'currency_id')
4663 4663
 	{
4664
-		global $conf,$langs,$user;
4664
+		global $conf, $langs, $user;
4665 4665
 
4666 4666
 		$langs->loadCacheCurrencies('');
4667 4667
 
4668
-		$out='';
4668
+		$out = '';
4669 4669
 
4670
-		if ($selected=='euro' || $selected=='euros') $selected='EUR';   // Pour compatibilite
4670
+		if ($selected == 'euro' || $selected == 'euros') $selected = 'EUR'; // Pour compatibilite
4671 4671
 
4672
-		$out.= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
4672
+		$out .= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
4673 4673
 		foreach ($langs->cache_currencies as $code_iso => $currency)
4674 4674
 		{
4675 4675
 			if ($selected && $selected == $code_iso)
4676 4676
 			{
4677
-				$out.= '<option value="'.$code_iso.'" selected>';
4677
+				$out .= '<option value="'.$code_iso.'" selected>';
4678 4678
 			}
4679 4679
 			else
4680 4680
 			{
4681
-				$out.= '<option value="'.$code_iso.'">';
4681
+				$out .= '<option value="'.$code_iso.'">';
4682 4682
 			}
4683
-			$out.= $currency['label'];
4684
-			$out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
4685
-			$out.= '</option>';
4683
+			$out .= $currency['label'];
4684
+			$out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
4685
+			$out .= '</option>';
4686 4686
 		}
4687
-		$out.= '</select>';
4688
-		if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
4687
+		$out .= '</select>';
4688
+		if ($user->admin) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
4689 4689
 
4690 4690
 		// Make select dynamic
4691
-		include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4691
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
4692 4692
 		$out .= ajax_combobox($htmlname);
4693 4693
 
4694 4694
 		return $out;
@@ -4702,27 +4702,27 @@  discard block
 block discarded – undo
4702 4702
 	 *  @param  integer	$useempty    1=Add empty line
4703 4703
 	 * 	@return	string
4704 4704
 	 */
4705
-	function selectMultiCurrency($selected='', $htmlname='multicurrency_code', $useempty=0)
4705
+	function selectMultiCurrency($selected = '', $htmlname = 'multicurrency_code', $useempty = 0)
4706 4706
 	{
4707
-		global $db,$conf,$langs,$user;
4707
+		global $db, $conf, $langs, $user;
4708 4708
 
4709
-		$langs->loadCacheCurrencies('');        // Load ->cache_currencies
4709
+		$langs->loadCacheCurrencies(''); // Load ->cache_currencies
4710 4710
 
4711 4711
 		$TCurrency = array();
4712 4712
 
4713 4713
 		$sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
4714
-		$sql.= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
4714
+		$sql .= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
4715 4715
 		$resql = $db->query($sql);
4716 4716
 		if ($resql)
4717 4717
 		{
4718 4718
 			while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
4719 4719
 		}
4720 4720
 
4721
-		$out='';
4722
-		$out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
4721
+		$out = '';
4722
+		$out .= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
4723 4723
 		if ($useempty) $out .= '<option value=""></option>';
4724 4724
 		// If company current currency not in table, we add it into list. Should always be available.
4725
-		if (! in_array($conf->currency, $TCurrency))
4725
+		if (!in_array($conf->currency, $TCurrency))
4726 4726
 		{
4727 4727
 			$TCurrency[$conf->currency] = $conf->currency;
4728 4728
 		}
@@ -4732,20 +4732,20 @@  discard block
 block discarded – undo
4732 4732
 			{
4733 4733
 				if (isset($TCurrency[$code_iso]))
4734 4734
 				{
4735
-					if (!empty($selected) && $selected == $code_iso) $out.= '<option value="'.$code_iso.'" selected="selected">';
4736
-					else $out.= '<option value="'.$code_iso.'">';
4735
+					if (!empty($selected) && $selected == $code_iso) $out .= '<option value="'.$code_iso.'" selected="selected">';
4736
+					else $out .= '<option value="'.$code_iso.'">';
4737 4737
 
4738
-					$out.= $currency['label'];
4739
-					$out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
4740
-					$out.= '</option>';
4738
+					$out .= $currency['label'];
4739
+					$out .= ' ('.$langs->getCurrencySymbol($code_iso).')';
4740
+					$out .= '</option>';
4741 4741
 				}
4742 4742
 			}
4743 4743
 		}
4744 4744
 
4745
-		$out.= '</select>';
4745
+		$out .= '</select>';
4746 4746
 		// Make select dynamic
4747
-		include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
4748
-		$out.= ajax_combobox($htmlname);
4747
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
4748
+		$out .= ajax_combobox($htmlname);
4749 4749
 
4750 4750
 		return $out;
4751 4751
 	}
@@ -4763,18 +4763,18 @@  discard block
 block discarded – undo
4763 4763
 		global $langs;
4764 4764
 
4765 4765
 		$num = count($this->cache_vatrates);
4766
-		if ($num > 0) return $num;    // Cache already loaded
4766
+		if ($num > 0) return $num; // Cache already loaded
4767 4767
 
4768 4768
 		dol_syslog(__METHOD__, LOG_DEBUG);
4769 4769
 
4770
-		$sql  = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
4771
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4772
-		$sql.= " WHERE t.fk_pays = c.rowid";
4773
-		$sql.= " AND t.active > 0";
4774
-		$sql.= " AND c.code IN (".$country_code.")";
4775
-		$sql.= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
4770
+		$sql = "SELECT DISTINCT t.rowid, t.code, t.taux, t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.recuperableonly";
4771
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4772
+		$sql .= " WHERE t.fk_pays = c.rowid";
4773
+		$sql .= " AND t.active > 0";
4774
+		$sql .= " AND c.code IN (".$country_code.")";
4775
+		$sql .= " ORDER BY t.code ASC, t.taux ASC, t.recuperableonly ASC";
4776 4776
 
4777
-		$resql=$this->db->query($sql);
4777
+		$resql = $this->db->query($sql);
4778 4778
 		if ($resql)
4779 4779
 		{
4780 4780
 			$num = $this->db->num_rows($resql);
@@ -4784,29 +4784,29 @@  discard block
 block discarded – undo
4784 4784
 				{
4785 4785
 					$obj = $this->db->fetch_object($resql);
4786 4786
 					$this->cache_vatrates[$i]['rowid']	= $obj->rowid;
4787
-					$this->cache_vatrates[$i]['code']	= $obj->code;
4787
+					$this->cache_vatrates[$i]['code'] = $obj->code;
4788 4788
 					$this->cache_vatrates[$i]['txtva']	= $obj->taux;
4789
-					$this->cache_vatrates[$i]['nprtva']	= $obj->recuperableonly;
4789
+					$this->cache_vatrates[$i]['nprtva'] = $obj->recuperableonly;
4790 4790
 					$this->cache_vatrates[$i]['localtax1']	    = $obj->localtax1;
4791 4791
 					$this->cache_vatrates[$i]['localtax1_type']	= $obj->localtax1_type;
4792 4792
 					$this->cache_vatrates[$i]['localtax2']	    = $obj->localtax2;
4793 4793
 					$this->cache_vatrates[$i]['localtax2_type']	= $obj->localtax1_type;
4794 4794
 
4795
-					$this->cache_vatrates[$i]['label']	= $obj->taux.'%'.($obj->code?' ('.$obj->code.')':'');   // Label must contains only 0-9 , . % or *
4796
-					$this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':'');	// Must never be used as key, only label
4797
-					$positiverates='';
4798
-					if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux;
4799
-					if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1;
4800
-					if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2;
4801
-					if (empty($positiverates)) $positiverates='0';
4802
-					$this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':'');	// Must never be used as key, only label
4795
+					$this->cache_vatrates[$i]['label'] = $obj->taux.'%'.($obj->code ? ' ('.$obj->code.')' : ''); // Label must contains only 0-9 , . % or *
4796
+					$this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1 ? $obj->localtax1 : '0').'/'.($obj->localtax2 ? $obj->localtax2 : '0').($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
4797
+					$positiverates = '';
4798
+					if ($obj->taux) $positiverates .= ($positiverates ? '/' : '').$obj->taux;
4799
+					if ($obj->localtax1) $positiverates .= ($positiverates ? '/' : '').$obj->localtax1;
4800
+					if ($obj->localtax2) $positiverates .= ($positiverates ? '/' : '').$obj->localtax2;
4801
+					if (empty($positiverates)) $positiverates = '0';
4802
+					$this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code ? ' ('.$obj->code.')' : ''); // Must never be used as key, only label
4803 4803
 				}
4804 4804
 
4805 4805
 				return $num;
4806 4806
 			}
4807 4807
 			else
4808 4808
 			{
4809
-				$this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).'</font>';
4809
+				$this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry", $country_code).'</font>';
4810 4810
 				return -1;
4811 4811
 			}
4812 4812
 		}
@@ -4839,37 +4839,37 @@  discard block
 block discarded – undo
4839 4839
 	 *  @param  int          $mode                0=Use vat rate as key in combo list, 1=Add VAT code after vat rate into key, -1=Use id of vat line as key
4840 4840
 	 *  @return	string
4841 4841
 	 */
4842
-	function load_tva($htmlname='tauxtva', $selectedrate='', $societe_vendeuse='', $societe_acheteuse='', $idprod=0, $info_bits=0, $type='', $options_only=false, $mode=0)
4842
+	function load_tva($htmlname = 'tauxtva', $selectedrate = '', $societe_vendeuse = '', $societe_acheteuse = '', $idprod = 0, $info_bits = 0, $type = '', $options_only = false, $mode = 0)
4843 4843
 	{
4844 4844
         // phpcs:enable
4845
-		global $langs,$conf,$mysoc;
4845
+		global $langs, $conf, $mysoc;
4846 4846
 
4847 4847
 		$langs->load('errors');
4848 4848
 
4849
-		$return='';
4849
+		$return = '';
4850 4850
 
4851 4851
 		// Define defaultnpr, defaultttx and defaultcode
4852
-		$defaultnpr=($info_bits & 0x01);
4853
-		$defaultnpr=(preg_match('/\*/',$selectedrate) ? 1 : $defaultnpr);
4854
-		$defaulttx=str_replace('*','',$selectedrate);
4855
-		$defaultcode='';
4852
+		$defaultnpr = ($info_bits & 0x01);
4853
+		$defaultnpr = (preg_match('/\*/', $selectedrate) ? 1 : $defaultnpr);
4854
+		$defaulttx = str_replace('*', '', $selectedrate);
4855
+		$defaultcode = '';
4856 4856
 		if (preg_match('/\((.*)\)/', $defaulttx, $reg))
4857 4857
 		{
4858
-			$defaultcode=$reg[1];
4859
-			$defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
4858
+			$defaultcode = $reg[1];
4859
+			$defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
4860 4860
 		}
4861 4861
 		//var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
4862 4862
 
4863 4863
 		// Check parameters
4864
-		if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)
4864
+		if (is_object($societe_vendeuse) && !$societe_vendeuse->country_code)
4865 4865
 		{
4866 4866
 			if ($societe_vendeuse->id == $mysoc->id)
4867 4867
 			{
4868
-				$return.= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</div>';
4868
+				$return .= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</div>';
4869 4869
 			}
4870 4870
 			else
4871 4871
 			{
4872
-				$return.= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</div>';
4872
+				$return .= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</div>';
4873 4873
 			}
4874 4874
 			return $return;
4875 4875
 		}
@@ -4882,82 +4882,82 @@  discard block
 block discarded – undo
4882 4882
 		// First we defined code_country to use to find list
4883 4883
 		if (is_object($societe_vendeuse))
4884 4884
 		{
4885
-			$code_country="'".$societe_vendeuse->country_code."'";
4885
+			$code_country = "'".$societe_vendeuse->country_code."'";
4886 4886
 		}
4887 4887
 		else
4888 4888
 		{
4889
-			$code_country="'".$mysoc->country_code."'";   // Pour compatibilite ascendente
4889
+			$code_country = "'".$mysoc->country_code."'"; // Pour compatibilite ascendente
4890 4890
 		}
4891
-		if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))    // If option to have vat for end customer for services is on
4891
+		if (!empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))    // If option to have vat for end customer for services is on
4892 4892
 		{
4893 4893
 			require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
4894
-			if (! isInEEC($societe_vendeuse) && (! is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && ! $societe_acheteuse->isACompany())))
4894
+			if (!isInEEC($societe_vendeuse) && (!is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && !$societe_acheteuse->isACompany())))
4895 4895
 			{
4896 4896
 				// We also add the buyer
4897 4897
 				if (is_numeric($type))
4898 4898
 				{
4899 4899
 					if ($type == 1) // We know product is a service
4900 4900
 					{
4901
-						$code_country.=",'".$societe_acheteuse->country_code."'";
4901
+						$code_country .= ",'".$societe_acheteuse->country_code."'";
4902 4902
 					}
4903 4903
 				}
4904
-				else if (! $idprod)  // We don't know type of product
4904
+				else if (!$idprod)  // We don't know type of product
4905 4905
 				{
4906
-					$code_country.=",'".$societe_acheteuse->country_code."'";
4906
+					$code_country .= ",'".$societe_acheteuse->country_code."'";
4907 4907
 				}
4908 4908
 				else
4909 4909
 				{
4910
-					$prodstatic=new Product($this->db);
4910
+					$prodstatic = new Product($this->db);
4911 4911
 					$prodstatic->fetch($idprod);
4912 4912
 					if ($prodstatic->type == Product::TYPE_SERVICE)   // We know product is a service
4913 4913
 					{
4914
-						$code_country.=",'".$societe_acheteuse->country_code."'";
4914
+						$code_country .= ",'".$societe_acheteuse->country_code."'";
4915 4915
 					}
4916 4916
 				}
4917 4917
 			}
4918 4918
 		}
4919 4919
 
4920 4920
 		// Now we get list
4921
-		$num = $this->load_cache_vatrates($code_country);   // If no vat defined, return -1 with message into this->error
4921
+		$num = $this->load_cache_vatrates($code_country); // If no vat defined, return -1 with message into this->error
4922 4922
 
4923 4923
 		if ($num > 0)
4924 4924
 		{
4925 4925
 			// Definition du taux a pre-selectionner (si defaulttx non force et donc vaut -1 ou '')
4926 4926
 			if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
4927 4927
 			{
4928
-				$tmpthirdparty=new Societe($this->db);
4929
-				$defaulttx=get_default_tva($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
4930
-				$defaultnpr=get_default_npr($societe_vendeuse, (is_object($societe_acheteuse)?$societe_acheteuse:$tmpthirdparty), $idprod);
4928
+				$tmpthirdparty = new Societe($this->db);
4929
+				$defaulttx = get_default_tva($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
4930
+				$defaultnpr = get_default_npr($societe_vendeuse, (is_object($societe_acheteuse) ? $societe_acheteuse : $tmpthirdparty), $idprod);
4931 4931
 		        if (preg_match('/\((.*)\)/', $defaulttx, $reg)) {
4932
-			        $defaultcode=$reg[1];
4933
-			        $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
4932
+			        $defaultcode = $reg[1];
4933
+			        $defaulttx = preg_replace('/\s*\(.*\)/', '', $defaulttx);
4934 4934
 		        }
4935
-				if (empty($defaulttx)) $defaultnpr=0;
4935
+				if (empty($defaulttx)) $defaultnpr = 0;
4936 4936
 			}
4937 4937
 
4938 4938
 			// Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
4939 4939
 			// Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
4940 4940
 			if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
4941 4941
 			{
4942
-				if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva'];
4943
-				else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
4942
+				if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num - 1]['txtva'];
4943
+				else $defaulttx = ($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
4944 4944
 			}
4945 4945
 
4946 4946
 			// Disabled if seller is not subject to VAT
4947
-			$disabled=false; $title='';
4947
+			$disabled = false; $title = '';
4948 4948
 			if (is_object($societe_vendeuse) && $societe_vendeuse->id == $mysoc->id && $societe_vendeuse->tva_assuj == "0")
4949 4949
 			{
4950 4950
 				// Override/enable VAT for expense report regardless of global setting - needed if expense report used for business expenses
4951 4951
 				if (empty($conf->global->OVERRIDE_VAT_FOR_EXPENSE_REPORT))
4952 4952
 				{
4953
-					$title=' title="'.$langs->trans('VATIsNotUsed').'"';
4954
-					$disabled=true;
4953
+					$title = ' title="'.$langs->trans('VATIsNotUsed').'"';
4954
+					$disabled = true;
4955 4955
 				}
4956 4956
 			}
4957 4957
 
4958
-			if (! $options_only) $return.= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$title.'>';
4958
+			if (!$options_only) $return .= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled ? ' disabled' : '').$title.'>';
4959 4959
 
4960
-			$selectedfound=false;
4960
+			$selectedfound = false;
4961 4961
 			foreach ($this->cache_vatrates as $rate)
4962 4962
 			{
4963 4963
 				// Keep only 0 if seller is not subject to VAT
@@ -4965,48 +4965,48 @@  discard block
 block discarded – undo
4965 4965
 
4966 4966
 				// Define key to use into select list
4967 4967
 				$key = $rate['txtva'];
4968
-				$key.= $rate['nprtva'] ? '*': '';
4969
-				if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')';
4968
+				$key .= $rate['nprtva'] ? '*' : '';
4969
+				if ($mode > 0 && $rate['code']) $key .= ' ('.$rate['code'].')';
4970 4970
 				if ($mode < 0) $key = $rate['rowid'];
4971 4971
 
4972
-				$return.= '<option value="'.$key.'"';
4973
-				if (! $selectedfound)
4972
+				$return .= '<option value="'.$key.'"';
4973
+				if (!$selectedfound)
4974 4974
 				{
4975 4975
 					if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
4976 4976
 					{
4977 4977
 						if ($defaultcode == $rate['code'])
4978 4978
 						{
4979
-							$return.= ' selected';
4980
-							$selectedfound=true;
4979
+							$return .= ' selected';
4980
+							$selectedfound = true;
4981 4981
 						}
4982 4982
 					}
4983 4983
 					elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
4984 4984
 			   		{
4985
-			   			$return.= ' selected';
4986
-			   			$selectedfound=true;
4985
+			   			$return .= ' selected';
4986
+			   			$selectedfound = true;
4987 4987
 					}
4988 4988
 				}
4989
-				$return.= '>';
4989
+				$return .= '>';
4990 4990
 				//if (! empty($conf->global->MAIN_VAT_SHOW_POSITIVE_RATES))
4991
-				if ($mysoc->country_code == 'IN' || ! empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))
4991
+				if ($mysoc->country_code == 'IN' || !empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))
4992 4992
 				{
4993
-					$return.= $rate['labelpositiverates'];
4993
+					$return .= $rate['labelpositiverates'];
4994 4994
 				}
4995 4995
 				else
4996 4996
 				{
4997
-					$return.= vatrate($rate['label']);
4997
+					$return .= vatrate($rate['label']);
4998 4998
 				}
4999 4999
 				//$return.=($rate['code']?' '.$rate['code']:'');
5000
-				$return.= (empty($rate['code']) && $rate['nprtva']) ? ' *': '';         // We show the *  (old behaviour only if new vat code is not used)
5000
+				$return .= (empty($rate['code']) && $rate['nprtva']) ? ' *' : ''; // We show the *  (old behaviour only if new vat code is not used)
5001 5001
 
5002
-				$return.= '</option>';
5002
+				$return .= '</option>';
5003 5003
 			}
5004 5004
 
5005
-			if (! $options_only) $return.= '</select>';
5005
+			if (!$options_only) $return .= '</select>';
5006 5006
 		}
5007 5007
 		else
5008 5008
 		{
5009
-			$return.= $this->error;
5009
+			$return .= $this->error;
5010 5010
 		}
5011 5011
 
5012 5012
 		$this->num = $num;
@@ -5039,11 +5039,11 @@  discard block
 block discarded – undo
5039 5039
      *  @deprecated
5040 5040
 	 *  @see    form_date, select_month, select_year, select_dayofweek
5041 5041
 	 */
5042
-    function select_date($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $nooutput=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')
5042
+    function select_date($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $nooutput = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '')
5043 5043
     {
5044 5044
         // phpcs:enable
5045 5045
         $retstring = $this->selectDate($set_time, $prefix, $h, $m, $empty, $form_name, $d, $addnowlink, $disabled, $fullday, $addplusone, $adddateof);
5046
-        if (! empty($nooutput)) {
5046
+        if (!empty($nooutput)) {
5047 5047
             return $retstring;
5048 5048
         }
5049 5049
         print $retstring;
@@ -5072,36 +5072,36 @@  discard block
 block discarded – undo
5072 5072
 	 * 	@return string                      Html for selectDate
5073 5073
 	 *  @see    form_date, select_month, select_year, select_dayofweek
5074 5074
 	 */
5075
-	function selectDate($set_time='', $prefix='re', $h=0, $m=0, $empty=0, $form_name="", $d=1, $addnowlink=0, $disabled=0, $fullday='', $addplusone='', $adddateof='')
5075
+	function selectDate($set_time = '', $prefix = 're', $h = 0, $m = 0, $empty = 0, $form_name = "", $d = 1, $addnowlink = 0, $disabled = 0, $fullday = '', $addplusone = '', $adddateof = '')
5076 5076
 	{
5077
-		global $conf,$langs;
5077
+		global $conf, $langs;
5078 5078
 
5079
-		$retstring='';
5079
+		$retstring = '';
5080 5080
 
5081
-		if ($prefix=='') $prefix='re';
5082
-		if ($h == '') $h=0;
5083
-		if ($m == '') $m=0;
5084
-		$emptydate=0;
5085
-		$emptyhours=0;
5086
-		if ($empty == 1) { $emptydate=1; $emptyhours=1; }
5087
-		if ($empty == 2) { $emptydate=0; $emptyhours=1; }
5088
-		$orig_set_time=$set_time;
5081
+		if ($prefix == '') $prefix = 're';
5082
+		if ($h == '') $h = 0;
5083
+		if ($m == '') $m = 0;
5084
+		$emptydate = 0;
5085
+		$emptyhours = 0;
5086
+		if ($empty == 1) { $emptydate = 1; $emptyhours = 1; }
5087
+		if ($empty == 2) { $emptydate = 0; $emptyhours = 1; }
5088
+		$orig_set_time = $set_time;
5089 5089
 
5090 5090
 		if ($set_time === '' && $emptydate == 0)
5091 5091
 		{
5092 5092
 			include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5093
-			$set_time = dol_now('tzuser')-(getServerTimeZoneInt('now')*3600); // set_time must be relative to PHP server timezone
5093
+			$set_time = dol_now('tzuser') - (getServerTimeZoneInt('now') * 3600); // set_time must be relative to PHP server timezone
5094 5094
 		}
5095 5095
 
5096 5096
 		// Analysis of the pre-selection date
5097
-		if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg))	// deprecated usage
5097
+		if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg))	// deprecated usage
5098 5098
 		{
5099 5099
 			// Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
5100
-			$syear	= (! empty($reg[1])?$reg[1]:'');
5101
-			$smonth	= (! empty($reg[2])?$reg[2]:'');
5102
-			$sday	= (! empty($reg[3])?$reg[3]:'');
5103
-			$shour	= (! empty($reg[4])?$reg[4]:'');
5104
-			$smin	= (! empty($reg[5])?$reg[5]:'');
5100
+			$syear	= (!empty($reg[1]) ? $reg[1] : '');
5101
+			$smonth = (!empty($reg[2]) ? $reg[2] : '');
5102
+			$sday	= (!empty($reg[3]) ? $reg[3] : '');
5103
+			$shour	= (!empty($reg[4]) ? $reg[4] : '');
5104
+			$smin	= (!empty($reg[5]) ? $reg[5] : '');
5105 5105
 		}
5106 5106
 		elseif (strval($set_time) != '' && $set_time != -1)
5107 5107
 		{
@@ -5136,9 +5136,9 @@  discard block
 block discarded – undo
5136 5136
 		if ($m == 3) $smin = '';
5137 5137
 
5138 5138
 		// You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
5139
-		$usecalendar='combo';
5140
-		if (! empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
5141
-			$usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy')?'jquery':$conf->global->MAIN_POPUP_CALENDAR);
5139
+		$usecalendar = 'combo';
5140
+		if (!empty($conf->use_javascript_ajax) && (empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR != "none")) {
5141
+			$usecalendar = ((empty($conf->global->MAIN_POPUP_CALENDAR) || $conf->global->MAIN_POPUP_CALENDAR == 'eldy') ? 'jquery' : $conf->global->MAIN_POPUP_CALENDAR);
5142 5142
 		}
5143 5143
 
5144 5144
 		if ($d)
@@ -5146,50 +5146,50 @@  discard block
 block discarded – undo
5146 5146
 			// Show date with popup
5147 5147
 			if ($usecalendar != 'combo')
5148 5148
 			{
5149
-				$formated_date='';
5149
+				$formated_date = '';
5150 5150
 				//print "e".$set_time." t ".$conf->format_date_short;
5151 5151
 				if (strval($set_time) != '' && $set_time != -1)
5152 5152
 				{
5153 5153
 					//$formated_date=dol_print_date($set_time,$conf->format_date_short);
5154
-					$formated_date=dol_print_date($set_time,$langs->trans("FormatDateShortInput"));  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5154
+					$formated_date = dol_print_date($set_time, $langs->trans("FormatDateShortInput")); // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5155 5155
 				}
5156 5156
 
5157 5157
 				// Calendrier popup version eldy
5158 5158
 				if ($usecalendar == "eldy")
5159 5159
 				{
5160 5160
 					// Zone de saisie manuelle de la date
5161
-					$retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
5162
-					$retstring.=($disabled?' disabled':'');
5163
-					$retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "';  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5164
-					$retstring.='>';
5161
+					$retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
5162
+					$retstring .= ($disabled ? ' disabled' : '');
5163
+					$retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5164
+					$retstring .= '>';
5165 5165
 
5166 5166
 					// Icone calendrier
5167
-					if (! $disabled)
5167
+					if (!$disabled)
5168 5168
 					{
5169
-						$retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
5170
-						$base=DOL_URL_ROOT.'/core/';
5171
-						$retstring.=' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
5172
-						$retstring.='>'.img_object($langs->trans("SelectDate"),'calendarday','class="datecallink"').'</button>';
5169
+						$retstring .= '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons"';
5170
+						$base = DOL_URL_ROOT.'/core/';
5171
+						$retstring .= ' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
5172
+						$retstring .= '>'.img_object($langs->trans("SelectDate"), 'calendarday', 'class="datecallink"').'</button>';
5173 5173
 					}
5174
-					else $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5174
+					else $retstring .= '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
5175 5175
 
5176
-					$retstring.='<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5177
-					$retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5178
-					$retstring.='<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5176
+					$retstring .= '<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5177
+					$retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5178
+					$retstring .= '<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5179 5179
 				}
5180 5180
 				elseif ($usecalendar == 'jquery')
5181 5181
 				{
5182
-					if (! $disabled)
5182
+					if (!$disabled)
5183 5183
 					{
5184 5184
 						// Output javascript for datepicker
5185
-						$retstring.="<script type='text/javascript'>";
5186
-						$retstring.="$(function(){ $('#".$prefix."').datepicker({
5185
+						$retstring .= "<script type='text/javascript'>";
5186
+						$retstring .= "$(function(){ $('#".$prefix."').datepicker({
5187 5187
 							dateFormat: '".$langs->trans("FormatDateShortJQueryInput")."',
5188 5188
 							autoclose: true,
5189 5189
 							todayHighlight: true,";
5190
-							if (! empty($conf->dol_use_jmobile))
5190
+							if (!empty($conf->dol_use_jmobile))
5191 5191
 							{
5192
-								$retstring.="
5192
+								$retstring .= "
5193 5193
 								beforeShow: function (input, datePicker) {
5194 5194
 									input.disabled = true;
5195 5195
 								},
@@ -5201,25 +5201,25 @@  discard block
 block discarded – undo
5201 5201
 							// Note: We don't need monthNames, monthNamesShort, dayNames, dayNamesShort, dayNamesMin, they are set globally on datepicker component in lib_head.js.php
5202 5202
 							if (empty($conf->global->MAIN_POPUP_CALENDAR_ON_FOCUS))
5203 5203
 							{
5204
-							$retstring.="
5204
+							$retstring .= "
5205 5205
 								showOn: 'button',
5206 5206
 								buttonImage: '".DOL_URL_ROOT."/theme/".$conf->theme."/img/object_calendarday.png',
5207 5207
 								buttonImageOnly: true";
5208 5208
 							}
5209
-							$retstring.="
5209
+							$retstring .= "
5210 5210
 							}) });";
5211
-						$retstring.="</script>";
5211
+						$retstring .= "</script>";
5212 5212
 					}
5213 5213
 
5214 5214
 					// Zone de saisie manuelle de la date
5215
-					$retstring.='<div class="nowrap inline-block">';
5216
-					$retstring.='<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
5217
-					$retstring.=($disabled?' disabled':'');
5218
-					$retstring.=' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "';  // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5219
-					$retstring.='>';
5215
+					$retstring .= '<div class="nowrap inline-block">';
5216
+					$retstring .= '<input id="'.$prefix.'" name="'.$prefix.'" type="text" class="maxwidth75" maxlength="11" value="'.$formated_date.'"';
5217
+					$retstring .= ($disabled ? ' disabled' : '');
5218
+					$retstring .= ' onChange="dpChangeDay(\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\'); "'; // FormatDateShortInput for dol_print_date / FormatDateShortJavaInput that is same for javascript
5219
+					$retstring .= '>';
5220 5220
 
5221 5221
 					// Icone calendrier
5222
-					if (! $disabled)
5222
+					if (!$disabled)
5223 5223
 					{
5224 5224
 						/* Not required. Managed by option buttonImage of jquery
5225 5225
                 		$retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"');
@@ -5233,17 +5233,17 @@  discard block
 block discarded – undo
5233 5233
 					}
5234 5234
 					else
5235 5235
 					{
5236
-						$retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5236
+						$retstring .= '<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"), 'calendarday', 'class="datecallink"').'</button>';
5237 5237
 					}
5238 5238
 
5239
-					$retstring.='</div>';
5240
-					$retstring.='<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5241
-					$retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5242
-					$retstring.='<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5239
+					$retstring .= '</div>';
5240
+					$retstring .= '<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5241
+					$retstring .= '<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5242
+					$retstring .= '<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5243 5243
 				}
5244 5244
 				else
5245 5245
 				{
5246
-					$retstring.="Bad value of MAIN_POPUP_CALENDAR";
5246
+					$retstring .= "Bad value of MAIN_POPUP_CALENDAR";
5247 5247
 				}
5248 5248
 			}
5249 5249
 			// Show date with combo selects
@@ -5251,83 +5251,83 @@  discard block
 block discarded – undo
5251 5251
 			{
5252 5252
 				//$retstring.='<div class="inline-block">';
5253 5253
 				// Day
5254
-				$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
5254
+				$retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50imp" id="'.$prefix.'day" name="'.$prefix.'day">';
5255 5255
 
5256 5256
 				if ($emptydate || $set_time == -1)
5257 5257
 				{
5258
-					$retstring.='<option value="0" selected>&nbsp;</option>';
5258
+					$retstring .= '<option value="0" selected>&nbsp;</option>';
5259 5259
 				}
5260 5260
 
5261
-				for ($day = 1 ; $day <= 31; $day++)
5261
+				for ($day = 1; $day <= 31; $day++)
5262 5262
 				{
5263
-					$retstring.='<option value="'.$day.'"'.($day == $sday ? ' selected':'').'>'.$day.'</option>';
5263
+					$retstring .= '<option value="'.$day.'"'.($day == $sday ? ' selected' : '').'>'.$day.'</option>';
5264 5264
 				}
5265 5265
 
5266
-				$retstring.="</select>";
5266
+				$retstring .= "</select>";
5267 5267
 
5268
-				$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
5268
+				$retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'month" name="'.$prefix.'month">';
5269 5269
 				if ($emptydate || $set_time == -1)
5270 5270
 				{
5271
-					$retstring.='<option value="0" selected>&nbsp;</option>';
5271
+					$retstring .= '<option value="0" selected>&nbsp;</option>';
5272 5272
 				}
5273 5273
 
5274 5274
 				// Month
5275
-				for ($month = 1 ; $month <= 12 ; $month++)
5275
+				for ($month = 1; $month <= 12; $month++)
5276 5276
 				{
5277
-					$retstring.='<option value="'.$month.'"'.($month == $smonth?' selected':'').'>';
5278
-					$retstring.=dol_print_date(mktime(12,0,0,$month,1,2000),"%b");
5279
-					$retstring.="</option>";
5277
+					$retstring .= '<option value="'.$month.'"'.($month == $smonth ? ' selected' : '').'>';
5278
+					$retstring .= dol_print_date(mktime(12, 0, 0, $month, 1, 2000), "%b");
5279
+					$retstring .= "</option>";
5280 5280
 				}
5281
-				$retstring.="</select>";
5281
+				$retstring .= "</select>";
5282 5282
 
5283 5283
 				// Year
5284 5284
 				if ($emptydate || $set_time == -1)
5285 5285
 				{
5286
-					$retstring.='<input'.($disabled?' disabled':'').' placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" class="flat maxwidth50imp valignmiddle" type="number" min="0" max="3000" maxlength="4" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">';
5286
+					$retstring .= '<input'.($disabled ? ' disabled' : '').' placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" class="flat maxwidth50imp valignmiddle" type="number" min="0" max="3000" maxlength="4" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">';
5287 5287
 				}
5288 5288
 				else
5289 5289
 				{
5290
-					$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
5290
+					$retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
5291 5291
 
5292
-					for ($year = $syear - 10; $year < $syear + 10 ; $year++)
5292
+					for ($year = $syear - 10; $year < $syear + 10; $year++)
5293 5293
 					{
5294
-						$retstring.='<option value="'.$year.'"'.($year == $syear ? ' selected':'').'>'.$year.'</option>';
5294
+						$retstring .= '<option value="'.$year.'"'.($year == $syear ? ' selected' : '').'>'.$year.'</option>';
5295 5295
 					}
5296
-					$retstring.="</select>\n";
5296
+					$retstring .= "</select>\n";
5297 5297
 				}
5298 5298
 				//$retstring.='</div>';
5299 5299
 			}
5300 5300
 		}
5301 5301
 
5302
-		if ($d && $h) $retstring.=($h==2?'<br>':' ');
5302
+		if ($d && $h) $retstring .= ($h == 2 ? '<br>' : ' ');
5303 5303
 
5304 5304
 		if ($h)
5305 5305
 		{
5306 5306
 			// Show hour
5307
-			$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'hour':'').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
5308
-			if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
5307
+			$retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'hour' : '').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
5308
+			if ($emptyhours) $retstring .= '<option value="-1">&nbsp;</option>';
5309 5309
 			for ($hour = 0; $hour < 24; $hour++)
5310 5310
 			{
5311
-				if (strlen($hour) < 2) $hour = "0" . $hour;
5312
-				$retstring.='<option value="'.$hour.'"'.(($hour == $shour)?' selected':'').'>'.$hour.(empty($conf->dol_optimize_smallscreen)?'':'H').'</option>';
5311
+				if (strlen($hour) < 2) $hour = "0".$hour;
5312
+				$retstring .= '<option value="'.$hour.'"'.(($hour == $shour) ? ' selected' : '').'>'.$hour.(empty($conf->dol_optimize_smallscreen) ? '' : 'H').'</option>';
5313 5313
 			}
5314
-			$retstring.='</select>';
5315
-			if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":";
5314
+			$retstring .= '</select>';
5315
+			if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":";
5316 5316
 		}
5317 5317
 
5318 5318
 		if ($m)
5319 5319
 		{
5320 5320
 			// Show minutes
5321
-			$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'min':'').'" id="'.$prefix.'min" name="'.$prefix.'min">';
5322
-			if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
5323
-			for ($min = 0; $min < 60 ; $min++)
5321
+			$retstring .= '<select'.($disabled ? ' disabled' : '').' class="flat valignmiddle maxwidth50 '.($fullday ? $fullday.'min' : '').'" id="'.$prefix.'min" name="'.$prefix.'min">';
5322
+			if ($emptyhours) $retstring .= '<option value="-1">&nbsp;</option>';
5323
+			for ($min = 0; $min < 60; $min++)
5324 5324
 			{
5325
-				if (strlen($min) < 2) $min = "0" . $min;
5326
-				$retstring.='<option value="'.$min.'"'.(($min == $smin)?' selected':'').'>'.$min.(empty($conf->dol_optimize_smallscreen)?'':'').'</option>';
5325
+				if (strlen($min) < 2) $min = "0".$min;
5326
+				$retstring .= '<option value="'.$min.'"'.(($min == $smin) ? ' selected' : '').'>'.$min.(empty($conf->dol_optimize_smallscreen) ? '' : '').'</option>';
5327 5327
 			}
5328
-			$retstring.='</select>';
5328
+			$retstring .= '</select>';
5329 5329
 
5330
-			$retstring.='<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
5330
+			$retstring .= '<input type="hidden" name="'.$prefix.'sec" value="'.$ssec.'">';
5331 5331
 		}
5332 5332
 
5333 5333
 		// Add a "Now" link
@@ -5337,10 +5337,10 @@  discard block
 block discarded – undo
5337 5337
 			$reset_scripts = "";
5338 5338
 
5339 5339
 			// Generate the date part, depending on the use or not of the javascript calendar
5340
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
5341
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
5342
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
5343
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
5340
+			$reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day').'\');';
5341
+			$reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d').'\');';
5342
+			$reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m').'\');';
5343
+			$reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y').'\');';
5344 5344
 			/*if ($usecalendar == "eldy")
5345 5345
             {
5346 5346
                 $base=DOL_URL_ROOT.'/core/';
@@ -5357,7 +5357,7 @@  discard block
 block discarded – undo
5357 5357
 			{
5358 5358
 				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5359 5359
 				//$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
5360
-				$reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
5360
+				$reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H').'\');';
5361 5361
 				if ($fullday) $reset_scripts .= ' } ';
5362 5362
 			}
5363 5363
 			// Update the minute part
@@ -5365,15 +5365,15 @@  discard block
 block discarded – undo
5365 5365
 			{
5366 5366
 				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5367 5367
 				//$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
5368
-				$reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
5368
+				$reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M').'\');';
5369 5369
 				if ($fullday) $reset_scripts .= ' } ';
5370 5370
 			}
5371 5371
 			// If reset_scripts is not empty, print the link with the reset_scripts in the onClick
5372 5372
 			if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
5373 5373
 			{
5374
-				$retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
5375
-				$retstring.=$langs->trans("Now");
5376
-				$retstring.='</button> ';
5374
+				$retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonNow" type="button" name="_useless" value="now" onClick="'.$reset_scripts.'">';
5375
+				$retstring .= $langs->trans("Now");
5376
+				$retstring .= '</button> ';
5377 5377
 			}
5378 5378
 		}
5379 5379
 
@@ -5384,38 +5384,38 @@  discard block
 block discarded – undo
5384 5384
 			$reset_scripts = "";
5385 5385
 
5386 5386
 			// Generate the date part, depending on the use or not of the javascript calendar
5387
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(),'day').'\');';
5388
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(),'%d').'\');';
5389
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(),'%m').'\');';
5390
-			$reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(),'%Y').'\');';
5387
+			$reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date(dol_now(), 'day').'\');';
5388
+			$reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date(dol_now(), '%d').'\');';
5389
+			$reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date(dol_now(), '%m').'\');';
5390
+			$reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date(dol_now(), '%Y').'\');';
5391 5391
 			// Update the hour part
5392 5392
 			if ($h)
5393 5393
 			{
5394 5394
 				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5395
-				$reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
5395
+				$reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(), '%H').'\');';
5396 5396
 				if ($fullday) $reset_scripts .= ' } ';
5397 5397
 			}
5398 5398
 			// Update the minute part
5399 5399
 			if ($m)
5400 5400
 			{
5401 5401
 				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5402
-				$reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
5402
+				$reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(), '%M').'\');';
5403 5403
 				if ($fullday) $reset_scripts .= ' } ';
5404 5404
 			}
5405 5405
 			// If reset_scripts is not empty, print the link with the reset_scripts in the onClick
5406 5406
 			if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
5407 5407
 			{
5408
-				$retstring.=' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
5409
-				$retstring.=$langs->trans("DateStartPlusOne");
5410
-				$retstring.='</button> ';
5408
+				$retstring .= ' <button class="dpInvisibleButtons datenowlink" id="'.$prefix.'ButtonPlusOne" type="button" name="_useless2" value="plusone" onClick="'.$reset_scripts.'">';
5409
+				$retstring .= $langs->trans("DateStartPlusOne");
5410
+				$retstring .= '</button> ';
5411 5411
 			}
5412 5412
 		}
5413 5413
 
5414 5414
 		// Add a "Plus one hour" link
5415 5415
 		if ($conf->use_javascript_ajax && $adddateof)
5416 5416
 		{
5417
-			$tmparray=dol_getdate($adddateof);
5418
-			$retstring.=' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="jQuery(\'#re\').val(\''.dol_print_date($adddateof,'day').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$langs->trans("DateInvoice").'</a>';
5417
+			$tmparray = dol_getdate($adddateof);
5418
+			$retstring .= ' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="jQuery(\'#re\').val(\''.dol_print_date($adddateof, 'day').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$langs->trans("DateInvoice").'</a>';
5419 5419
 		}
5420 5420
 
5421 5421
 		return $retstring;
@@ -5435,72 +5435,72 @@  discard block
 block discarded – undo
5435 5435
 	 * 	@param	int	$nooutput		    Do not output html string but return it
5436 5436
 	 *  @return	string|void
5437 5437
 	 */
5438
-	function select_duration($prefix, $iSecond='', $disabled=0, $typehour='select', $minunderhours=0, $nooutput=0)
5438
+	function select_duration($prefix, $iSecond = '', $disabled = 0, $typehour = 'select', $minunderhours = 0, $nooutput = 0)
5439 5439
 	{
5440 5440
         // phpcs:enable
5441 5441
 		global $langs;
5442 5442
 
5443
-		$retstring='';
5443
+		$retstring = '';
5444 5444
 
5445
-		$hourSelected=0; $minSelected=0;
5445
+		$hourSelected = 0; $minSelected = 0;
5446 5446
 
5447 5447
 		// Hours
5448 5448
 		if ($iSecond != '')
5449 5449
 		{
5450 5450
 			require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
5451 5451
 
5452
-			$hourSelected = convertSecondToTime($iSecond,'allhour');
5453
-			$minSelected = convertSecondToTime($iSecond,'min');
5452
+			$hourSelected = convertSecondToTime($iSecond, 'allhour');
5453
+			$minSelected = convertSecondToTime($iSecond, 'min');
5454 5454
 		}
5455 5455
 
5456
-		if ($typehour=='select' )
5456
+		if ($typehour == 'select')
5457 5457
 		{
5458
-			$retstring.='<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled?' disabled':'').'>';
5458
+			$retstring .= '<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').'>';
5459 5459
 			for ($hour = 0; $hour < 25; $hour++)	// For a duration, we allow 24 hours
5460 5460
 			{
5461
-				$retstring.='<option value="'.$hour.'"';
5461
+				$retstring .= '<option value="'.$hour.'"';
5462 5462
 				if ($hourSelected == $hour)
5463 5463
 				{
5464
-					$retstring.=" selected";
5464
+					$retstring .= " selected";
5465 5465
 				}
5466
-				$retstring.=">".$hour."</option>";
5466
+				$retstring .= ">".$hour."</option>";
5467 5467
 			}
5468
-			$retstring.="</select>";
5468
+			$retstring .= "</select>";
5469 5469
 		}
5470
-		elseif ($typehour=='text' || $typehour=='textselect')
5470
+		elseif ($typehour == 'text' || $typehour == 'textselect')
5471 5471
 		{
5472
-			$retstring.='<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" size="1" name="'.$prefix.'hour"'.($disabled?' disabled':'').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '')?((int) $hourSelected):'').'">';
5472
+			$retstring .= '<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" size="1" name="'.$prefix.'hour"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '') ? ((int) $hourSelected) : '').'">';
5473 5473
 		}
5474 5474
 		else return 'BadValueForParameterTypeHour';
5475 5475
 
5476
-		if ($typehour!='text') $retstring.=' '.$langs->trans('HourShort');
5477
-		else $retstring.='<span class="hideonsmartphone">:</span>';
5476
+		if ($typehour != 'text') $retstring .= ' '.$langs->trans('HourShort');
5477
+		else $retstring .= '<span class="hideonsmartphone">:</span>';
5478 5478
 
5479 5479
 		// Minutes
5480
-		if ($minunderhours) $retstring.='<br>';
5481
-		else $retstring.='<span class="hideonsmartphone">&nbsp;</span>';
5480
+		if ($minunderhours) $retstring .= '<br>';
5481
+		else $retstring .= '<span class="hideonsmartphone">&nbsp;</span>';
5482 5482
 
5483
-		if ($typehour=='select' || $typehour=='textselect')
5483
+		if ($typehour == 'select' || $typehour == 'textselect')
5484 5484
 		{
5485
-			$retstring.='<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled?' disabled':'').'>';
5486
-			for ($min = 0; $min <= 55; $min=$min+5)
5485
+			$retstring .= '<select class="flat" id="select_'.$prefix.'min" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').'>';
5486
+			for ($min = 0; $min <= 55; $min = $min + 5)
5487 5487
 			{
5488
-				$retstring.='<option value="'.$min.'"';
5489
-				if ($minSelected == $min) $retstring.=' selected';
5490
-				$retstring.='>'.$min.'</option>';
5488
+				$retstring .= '<option value="'.$min.'"';
5489
+				if ($minSelected == $min) $retstring .= ' selected';
5490
+				$retstring .= '>'.$min.'</option>';
5491 5491
 			}
5492
-			$retstring.="</select>";
5492
+			$retstring .= "</select>";
5493 5493
 		}
5494
-		elseif ($typehour=='text' )
5494
+		elseif ($typehour == 'text')
5495 5495
 		{
5496
-			$retstring.='<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" size="1" name="'.$prefix.'min"'.($disabled?' disabled':'').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '')?((int) $minSelected):'').'">';
5496
+			$retstring .= '<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" size="1" name="'.$prefix.'min"'.($disabled ? ' disabled' : '').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '') ? ((int) $minSelected) : '').'">';
5497 5497
 		}
5498 5498
 
5499
-		if ($typehour!='text') $retstring.=' '.$langs->trans('MinuteShort');
5499
+		if ($typehour != 'text') $retstring .= ' '.$langs->trans('MinuteShort');
5500 5500
 
5501 5501
 		//$retstring.="&nbsp;";
5502 5502
 
5503
-		if (! empty($nooutput)) return $retstring;
5503
+		if (!empty($nooutput)) return $retstring;
5504 5504
 
5505 5505
 		print $retstring;
5506 5506
 		return;
@@ -5523,16 +5523,16 @@  discard block
 block discarded – undo
5523 5523
 	 * @return	string								Return HTML string
5524 5524
 	 * @see selectForFormsList select_thirdparty
5525 5525
 	 */
5526
-	function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0)
5526
+	function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0)
5527 5527
 	{
5528 5528
 		global $conf, $user;
5529 5529
 
5530 5530
 		$objecttmp = null;
5531 5531
 
5532 5532
 		$InfoFieldList = explode(":", $objectdesc);
5533
-		$classname=$InfoFieldList[0];
5534
-		$classpath=$InfoFieldList[1];
5535
-		if (! empty($classpath))
5533
+		$classname = $InfoFieldList[0];
5534
+		$classpath = $InfoFieldList[1];
5535
+		if (!empty($classpath))
5536 5536
 		{
5537 5537
 			dol_include_once($classpath);
5538 5538
 			if ($classname && class_exists($classname))
@@ -5540,37 +5540,37 @@  discard block
 block discarded – undo
5540 5540
 				$objecttmp = new $classname($this->db);
5541 5541
 			}
5542 5542
 		}
5543
-		if (! is_object($objecttmp))
5543
+		if (!is_object($objecttmp))
5544 5544
 		{
5545 5545
 			dol_syslog('Error bad setup of type for field '.$InfoFieldList, LOG_WARNING);
5546 5546
 			return 'Error bad setup of type for field '.join(',', $InfoFieldList);
5547 5547
 		}
5548 5548
 
5549
-		$prefixforautocompletemode=$objecttmp->element;
5550
-		if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
5551
-		$confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';	// For example COMPANY_USE_SEARCH_TO_SELECT
5549
+		$prefixforautocompletemode = $objecttmp->element;
5550
+		if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode = 'company';
5551
+		$confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
5552 5552
 
5553 5553
 		dol_syslog(get_class($this)."::selectForForms", LOG_DEBUG);
5554 5554
 
5555
-		$out='';
5556
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->$confkeyforautocompletemode) && ! $forcecombo)
5555
+		$out = '';
5556
+		if (!empty($conf->use_javascript_ajax) && !empty($conf->global->$confkeyforautocompletemode) && !$forcecombo)
5557 5557
 		{
5558
-			$objectdesc=$classname.':'.$classpath;
5558
+			$objectdesc = $classname.':'.$classpath;
5559 5559
 			$urlforajaxcall = DOL_URL_ROOT.'/core/ajax/selectobject.php';
5560 5560
 			//if ($objecttmp->element == 'societe') $urlforajaxcall = DOL_URL_ROOT.'/societe/ajax/company.php';
5561 5561
 
5562 5562
 			// No immediate load of all database
5563
-			$urloption='htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.($moreparams?$moreparams:'');
5563
+			$urloption = 'htmlname='.$htmlname.'&outjson=1&objectdesc='.$objectdesc.($moreparams ? $moreparams : '');
5564 5564
 			// Activate the auto complete using ajax call.
5565
-			$out.=  ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
5566
-			$out.= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
5567
-			if ($placeholder) $placeholder=' placeholder="'.$placeholder.'"';
5568
-			$out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$preselectedvalue.'"'.$placeholder.' />';
5565
+			$out .= ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
5566
+			$out .= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
5567
+			if ($placeholder) $placeholder = ' placeholder="'.$placeholder.'"';
5568
+			$out .= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$preselectedvalue.'"'.$placeholder.' />';
5569 5569
 		}
5570 5570
 		else
5571 5571
 		{
5572 5572
 			// Immediate load of all database
5573
-			$out.=$this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo);
5573
+			$out .= $this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo);
5574 5574
 		}
5575 5575
 
5576 5576
 		return $out;
@@ -5593,70 +5593,70 @@  discard block
 block discarded – undo
5593 5593
 	 * @return	string								Return HTML string
5594 5594
 	 * @see selectForForms
5595 5595
 	 */
5596
-	function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty='', $searchkey='', $placeholder='', $morecss='', $moreparams='', $forcecombo=0, $outputmode=0)
5596
+	function selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $outputmode = 0)
5597 5597
 	{
5598 5598
 		global $conf, $langs, $user;
5599 5599
 
5600
-		$prefixforautocompletemode=$objecttmp->element;
5601
-		if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
5602
-		$confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';	// For example COMPANY_USE_SEARCH_TO_SELECT
5600
+		$prefixforautocompletemode = $objecttmp->element;
5601
+		if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode = 'company';
5602
+		$confkeyforautocompletemode = strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT'; // For example COMPANY_USE_SEARCH_TO_SELECT
5603 5603
 
5604
-		$fieldstoshow='t.ref';
5605
-		if (! empty($objecttmp->fields))	// For object that declare it, it is better to use declared fields ( like societe, contact, ...)
5604
+		$fieldstoshow = 't.ref';
5605
+		if (!empty($objecttmp->fields))	// For object that declare it, it is better to use declared fields ( like societe, contact, ...)
5606 5606
 		{
5607
-			$tmpfieldstoshow='';
5608
-			foreach($objecttmp->fields as $key => $val)
5607
+			$tmpfieldstoshow = '';
5608
+			foreach ($objecttmp->fields as $key => $val)
5609 5609
 			{
5610
-				if ($val['showoncombobox']) $tmpfieldstoshow.=($tmpfieldstoshow?',':'').'t.'.$key;
5610
+				if ($val['showoncombobox']) $tmpfieldstoshow .= ($tmpfieldstoshow ? ',' : '').'t.'.$key;
5611 5611
 			}
5612 5612
 			if ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow;
5613 5613
 		}
5614 5614
 
5615
-		$out='';
5616
-		$outarray=array();
5615
+		$out = '';
5616
+		$outarray = array();
5617 5617
 
5618
-		$num=0;
5618
+		$num = 0;
5619 5619
 
5620 5620
 		// Search data
5621
-		$sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX .$objecttmp->table_element." as t";
5621
+		$sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX.$objecttmp->table_element." as t";
5622 5622
 		if ($objecttmp->ismultientitymanaged == 2)
5623 5623
 			if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
5624
-		$sql.= " WHERE 1=1";
5625
-		if(! empty($objecttmp->ismultientitymanaged)) $sql.= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
5626
-		if ($objecttmp->ismultientitymanaged == 1 && ! empty($user->societe_id))
5624
+		$sql .= " WHERE 1=1";
5625
+		if (!empty($objecttmp->ismultientitymanaged)) $sql .= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
5626
+		if ($objecttmp->ismultientitymanaged == 1 && !empty($user->societe_id))
5627 5627
 		{
5628
-			if ($objecttmp->element == 'societe') $sql.= " AND t.rowid = ".$user->societe_id;
5629
-				else $sql.= " AND t.fk_soc = ".$user->societe_id;
5628
+			if ($objecttmp->element == 'societe') $sql .= " AND t.rowid = ".$user->societe_id;
5629
+				else $sql .= " AND t.fk_soc = ".$user->societe_id;
5630 5630
 		}
5631
-		if ($searchkey != '') $sql.=natural_search(explode(',',$fieldstoshow), $searchkey);
5631
+		if ($searchkey != '') $sql .= natural_search(explode(',', $fieldstoshow), $searchkey);
5632 5632
 		if ($objecttmp->ismultientitymanaged == 2)
5633
-			if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND t.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
5634
-		$sql.=$this->db->order($fieldstoshow,"ASC");
5633
+			if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= " AND t.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
5634
+		$sql .= $this->db->order($fieldstoshow, "ASC");
5635 5635
 		//$sql.=$this->db->plimit($limit, 0);
5636 5636
 
5637 5637
 		// Build output string
5638
-		$resql=$this->db->query($sql);
5638
+		$resql = $this->db->query($sql);
5639 5639
 		if ($resql)
5640 5640
 		{
5641
-			if (! $forcecombo)
5641
+			if (!$forcecombo)
5642 5642
 			{
5643
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5643
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
5644 5644
 				$out .= ajax_combobox($htmlname, null, $conf->global->$confkeyforautocompletemode);
5645 5645
 			}
5646 5646
 
5647 5647
 			// Construct $out and $outarray
5648
-			$out.= '<select id="'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'"'.($moreparams?' '.$moreparams:'').' name="'.$htmlname.'">'."\n";
5648
+			$out .= '<select id="'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'"'.($moreparams ? ' '.$moreparams : '').' name="'.$htmlname.'">'."\n";
5649 5649
 
5650 5650
 			// Warning: Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'. Seems it is no more true with selec2 v4
5651
-			$textifempty='&nbsp;';
5651
+			$textifempty = '&nbsp;';
5652 5652
 
5653 5653
 			//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
5654
-			if (! empty($conf->global->$confkeyforautocompletemode))
5654
+			if (!empty($conf->global->$confkeyforautocompletemode))
5655 5655
 			{
5656
-				if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
5657
-				else $textifempty.=$langs->trans("All");
5656
+				if ($showempty && !is_numeric($showempty)) $textifempty = $langs->trans($showempty);
5657
+				else $textifempty .= $langs->trans("All");
5658 5658
 			}
5659
-			if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
5659
+			if ($showempty) $out .= '<option value="-1">'.$textifempty.'</option>'."\n";
5660 5660
 
5661 5661
 			$num = $this->db->num_rows($resql);
5662 5662
 			$i = 0;
@@ -5665,22 +5665,22 @@  discard block
 block discarded – undo
5665 5665
 				while ($i < $num)
5666 5666
 				{
5667 5667
 					$obj = $this->db->fetch_object($resql);
5668
-					$label='';
5669
-					$tmparray=explode(',', $fieldstoshow);
5670
-					foreach($tmparray as $key => $val)
5668
+					$label = '';
5669
+					$tmparray = explode(',', $fieldstoshow);
5670
+					foreach ($tmparray as $key => $val)
5671 5671
 					{
5672
-						$val = preg_replace('/t\./','',$val);
5673
-						$label .= (($label && $obj->$val)?' - ':'').$obj->$val;
5672
+						$val = preg_replace('/t\./', '', $val);
5673
+						$label .= (($label && $obj->$val) ? ' - ' : '').$obj->$val;
5674 5674
 					}
5675 5675
 					if (empty($outputmode))
5676 5676
 					{
5677 5677
 						if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid)
5678 5678
 						{
5679
-							$out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
5679
+							$out .= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
5680 5680
 						}
5681 5681
 						else
5682 5682
 						{
5683
-							$out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
5683
+							$out .= '<option value="'.$obj->rowid.'">'.$label.'</option>';
5684 5684
 						}
5685 5685
 					}
5686 5686
 					else
@@ -5689,18 +5689,18 @@  discard block
 block discarded – undo
5689 5689
 					}
5690 5690
 
5691 5691
 					$i++;
5692
-					if (($i % 10) == 0) $out.="\n";
5692
+					if (($i % 10) == 0) $out .= "\n";
5693 5693
 				}
5694 5694
 			}
5695 5695
 
5696
-			$out.= '</select>'."\n";
5696
+			$out .= '</select>'."\n";
5697 5697
 		}
5698 5698
 		else
5699 5699
 		{
5700 5700
 			dol_print_error($this->db);
5701 5701
 		}
5702 5702
 
5703
-		$this->result=array('nbofelement'=>$num);
5703
+		$this->result = array('nbofelement'=>$num);
5704 5704
 
5705 5705
 		if ($outputmode) return $outarray;
5706 5706
 		return $out;
@@ -5730,7 +5730,7 @@  discard block
 block discarded – undo
5730 5730
 	 * 	@return	string								HTML select string.
5731 5731
 	 *  @see multiselectarray
5732 5732
 	 */
5733
-	static function selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='', $addjscombo=0, $moreparamonempty='',$disablebademail=0, $nohtmlescape=0)
5733
+	static function selectarray($htmlname, $array, $id = '', $show_empty = 0, $key_in_label = 0, $value_as_key = 0, $moreparam = '', $translate = 0, $maxlen = 0, $disabled = 0, $sort = '', $morecss = '', $addjscombo = 0, $moreparamonempty = '', $disablebademail = 0, $nohtmlescape = 0)
5734 5734
 	{
5735 5735
 		global $conf, $langs;
5736 5736
 
@@ -5739,31 +5739,31 @@  discard block
 block discarded – undo
5739 5739
 		//if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
5740 5740
 		$jsbeautify = 1;
5741 5741
 
5742
-		if ($value_as_key) $array=array_combine($array, $array);
5742
+		if ($value_as_key) $array = array_combine($array, $array);
5743 5743
 
5744
-		$out='';
5744
+		$out = '';
5745 5745
 
5746 5746
 		// Add code for jquery to use multiselect
5747 5747
 		if ($addjscombo && $jsbeautify)
5748 5748
 		{
5749
-			$minLengthToAutocomplete=0;
5750
-			$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?(constant('REQUIRE_JQUERY_MULTISELECT')?constant('REQUIRE_JQUERY_MULTISELECT'):'select2'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
5749
+			$minLengthToAutocomplete = 0;
5750
+			$tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ? (constant('REQUIRE_JQUERY_MULTISELECT') ?constant('REQUIRE_JQUERY_MULTISELECT') : 'select2') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
5751 5751
 
5752 5752
 			// Enhance with select2
5753
-			include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5753
+			include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
5754 5754
 			$out .= ajax_combobox($htmlname);
5755 5755
 		}
5756 5756
 
5757
-		$out.='<select id="'.preg_replace('/^\./','',$htmlname).'" '.($disabled?'disabled ':'').'class="flat '.(preg_replace('/^\./','',$htmlname)).($morecss?' '.$morecss:'').'"';
5758
-		$out.=' name="'.preg_replace('/^\./','',$htmlname).'" '.($moreparam?$moreparam:'');
5759
-		$out.='>';
5757
+		$out .= '<select id="'.preg_replace('/^\./', '', $htmlname).'" '.($disabled ? 'disabled ' : '').'class="flat '.(preg_replace('/^\./', '', $htmlname)).($morecss ? ' '.$morecss : '').'"';
5758
+		$out .= ' name="'.preg_replace('/^\./', '', $htmlname).'" '.($moreparam ? $moreparam : '');
5759
+		$out .= '>';
5760 5760
 
5761 5761
 		if ($show_empty)
5762 5762
 		{
5763
-			$textforempty=' ';
5764
-			if (! empty($conf->use_javascript_ajax)) $textforempty='&nbsp;';	// If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
5765
-			if (! is_numeric($show_empty)) $textforempty=$show_empty;
5766
-			$out.='<option class="optiongrey" '.($moreparamonempty?$moreparamonempty.' ':'').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ?' selected':'').'>'.$textforempty.'</option>'."\n";
5763
+			$textforempty = ' ';
5764
+			if (!empty($conf->use_javascript_ajax)) $textforempty = '&nbsp;'; // If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
5765
+			if (!is_numeric($show_empty)) $textforempty = $show_empty;
5766
+			$out .= '<option class="optiongrey" '.($moreparamonempty ? $moreparamonempty.' ' : '').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ? ' selected' : '').'>'.$textforempty.'</option>'."\n";
5767 5767
 		}
5768 5768
 
5769 5769
 		if (is_array($array))
@@ -5771,9 +5771,9 @@  discard block
 block discarded – undo
5771 5771
 			// Translate
5772 5772
 			if ($translate)
5773 5773
 			{
5774
-				foreach($array as $key => $value)
5774
+				foreach ($array as $key => $value)
5775 5775
 				{
5776
-					$array[$key]=$langs->trans($value);
5776
+					$array[$key] = $langs->trans($value);
5777 5777
 				}
5778 5778
 			}
5779 5779
 
@@ -5781,43 +5781,43 @@  discard block
 block discarded – undo
5781 5781
 			if ($sort == 'ASC') asort($array);
5782 5782
 			elseif ($sort == 'DESC') arsort($array);
5783 5783
 
5784
-			foreach($array as $key => $value)
5784
+			foreach ($array as $key => $value)
5785 5785
 			{
5786
-				$disabled=''; $style='';
5787
-				if (! empty($disablebademail))
5786
+				$disabled = ''; $style = '';
5787
+				if (!empty($disablebademail))
5788 5788
 				{
5789
-					if (! preg_match('/&lt;.+@.+&gt;/', $value))
5789
+					if (!preg_match('/&lt;.+@.+&gt;/', $value))
5790 5790
 					{
5791 5791
 						//$value=preg_replace('/'.preg_quote($a,'/').'/', $b, $value);
5792
-						$disabled=' disabled';
5793
-						$style=' class="warning"';
5792
+						$disabled = ' disabled';
5793
+						$style = ' class="warning"';
5794 5794
 					}
5795 5795
 				}
5796 5796
 
5797 5797
 				if ($key_in_label)
5798 5798
 				{
5799
-					if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));
5800
-					else $selectOptionValue = $key.' - '.($maxlen?dol_trunc($value,$maxlen):$value);
5799
+					if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value));
5800
+					else $selectOptionValue = $key.' - '.($maxlen ?dol_trunc($value, $maxlen) : $value);
5801 5801
 				}
5802 5802
 				else
5803 5803
 				{
5804
-					if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);
5805
-					else $selectOptionValue = $maxlen?dol_trunc($value,$maxlen):$value;
5806
-					if ($value == '' || $value == '-') $selectOptionValue='&nbsp;';
5804
+					if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen ?dol_trunc($value, $maxlen) : $value);
5805
+					else $selectOptionValue = $maxlen ?dol_trunc($value, $maxlen) : $value;
5806
+					if ($value == '' || $value == '-') $selectOptionValue = '&nbsp;';
5807 5807
 				}
5808 5808
 
5809
-				$out.='<option value="'.$key.'"';
5810
-				$out.=$style.$disabled;
5811
-				if ($id != '' && $id == $key && ! $disabled) $out.=' selected';		// To preselect a value
5812
-				if ($nohtmlescape) $out.=' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
5813
-				$out.='>';
5809
+				$out .= '<option value="'.$key.'"';
5810
+				$out .= $style.$disabled;
5811
+				if ($id != '' && $id == $key && !$disabled) $out .= ' selected'; // To preselect a value
5812
+				if ($nohtmlescape) $out .= ' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
5813
+				$out .= '>';
5814 5814
 				//var_dump($selectOptionValue);
5815
-				$out.=$selectOptionValue;
5816
-				$out.="</option>\n";
5815
+				$out .= $selectOptionValue;
5816
+				$out .= "</option>\n";
5817 5817
 			}
5818 5818
 		}
5819 5819
 
5820
-		$out.="</select>";
5820
+		$out .= "</select>";
5821 5821
 		return $out;
5822 5822
 	}
5823 5823
 
@@ -5840,22 +5840,22 @@  discard block
 block discarded – undo
5840 5840
 	 * 	@return	string   						HTML select string
5841 5841
 	 *  @see selectArrayFilter, ajax_combobox in ajax.lib.php
5842 5842
 	 */
5843
-	static function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
5843
+	static function selectArrayAjax($htmlname, $url, $id = '', $moreparam = '', $moreparamtourl = '', $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
5844 5844
 	{
5845 5845
 		global $conf, $langs;
5846 5846
 		global $delayedhtmlcontent;
5847 5847
 
5848 5848
 		// TODO Use an internal dolibarr component instead of select2
5849
-		if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
5849
+		if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) return '';
5850 5850
 
5851
-		$out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"></select>';
5851
+		$out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"></select>';
5852 5852
 
5853
-		$tmpplugin='select2';
5854
-		$outdelayed="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
5853
+		$tmpplugin = 'select2';
5854
+		$outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
5855 5855
 	    	<script type="text/javascript">
5856 5856
 	    	$(document).ready(function () {
5857 5857
 
5858
-    	        '.($callurlonselect ? 'var saveRemoteData = [];':'').'
5858
+    	        '.($callurlonselect ? 'var saveRemoteData = [];' : '').'
5859 5859
 
5860 5860
                 $(".'.$htmlname.'").select2({
5861 5861
 			    	ajax: {
@@ -5908,18 +5908,18 @@  discard block
 block discarded – undo
5908 5908
     			                 location.assign(value.url);
5909 5909
     			            }
5910 5910
                     });
5911
-    			});' : '' ) . '
5911
+    			});' : '').'
5912 5912
 
5913 5913
     	   });
5914 5914
 	       </script>';
5915 5915
 
5916 5916
 		if ($acceptdelayedhtml)
5917 5917
 		{
5918
-			$delayedhtmlcontent.=$outdelayed;
5918
+			$delayedhtmlcontent .= $outdelayed;
5919 5919
 		}
5920 5920
 		else
5921 5921
 		{
5922
-			$out.=$outdelayed;
5922
+			$out .= $outdelayed;
5923 5923
 		}
5924 5924
 		return $out;
5925 5925
 	}
@@ -5942,19 +5942,19 @@  discard block
 block discarded – undo
5942 5942
 	 * 	@return	string   						HTML select string
5943 5943
 	 *  @see selectArrayAjax, ajax_combobox in ajax.lib.php
5944 5944
 	 */
5945
-	static function selectArrayFilter($htmlname, $array, $id='', $moreparam='', $disableFiltering=0, $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
5945
+	static function selectArrayFilter($htmlname, $array, $id = '', $moreparam = '', $disableFiltering = 0, $disabled = 0, $minimumInputLength = 1, $morecss = '', $callurlonselect = 0, $placeholder = '', $acceptdelayedhtml = 0)
5946 5946
 	{
5947 5947
 		global $conf, $langs;
5948 5948
 		global $delayedhtmlcontent;
5949 5949
 
5950 5950
 		// TODO Use an internal dolibarr component instead of select2
5951
-		if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
5951
+		if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && !defined('REQUIRE_JQUERY_MULTISELECT')) return '';
5952 5952
 
5953
-		$out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"><option></option></select>';
5953
+		$out = '<select type="text" class="'.$htmlname.($morecss ? ' '.$morecss : '').'" '.($moreparam ? $moreparam.' ' : '').'name="'.$htmlname.'"><option></option></select>';
5954 5954
 
5955 5955
 		$formattedarrayresult = array();
5956 5956
 
5957
-		foreach($array as $key => $value) {
5957
+		foreach ($array as $key => $value) {
5958 5958
 			$o = new stdClass();
5959 5959
 			$o->id = $key;
5960 5960
 			$o->text = $value['text'];
@@ -5962,13 +5962,13 @@  discard block
 block discarded – undo
5962 5962
 			$formattedarrayresult[] = $o;
5963 5963
 		}
5964 5964
 
5965
-		$tmpplugin='select2';
5966
-		$outdelayed="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
5965
+		$tmpplugin = 'select2';
5966
+		$outdelayed = "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
5967 5967
 			<script type="text/javascript">
5968 5968
 			$(document).ready(function () {
5969 5969
 				var data = '.json_encode($formattedarrayresult).';
5970 5970
 
5971
-				'.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';':'').'
5971
+				'.($callurlonselect ? 'var saveRemoteData = '.json_encode($array).';' : '').'
5972 5972
 
5973 5973
 				$(".'.$htmlname.'").select2({
5974 5974
 					data: data,
@@ -5984,8 +5984,8 @@  discard block
 block discarded – undo
5984 5984
 
5985 5985
 						if(! data.id) return null;';
5986 5986
 
5987
-		if($callurlonselect) {
5988
-			$outdelayed.='
5987
+		if ($callurlonselect) {
5988
+			$outdelayed .= '
5989 5989
 
5990 5990
 						var urlBase = data.url;
5991 5991
 						var separ = urlBase.indexOf("?") >= 0 ? "&" : "?";
@@ -5994,8 +5994,8 @@  discard block
 block discarded – undo
5994 5994
 						saveRemoteData[data.id].url = urlBase + separ + "sall=" + encodeURIComponent(params.term);';
5995 5995
 		}
5996 5996
 
5997
-		if(! $disableFiltering) {
5998
-			$outdelayed.='
5997
+		if (!$disableFiltering) {
5998
+			$outdelayed .= '
5999 5999
 
6000 6000
 						if(data.text.match(new RegExp(params.term))) {
6001 6001
 							return data;
@@ -6003,12 +6003,12 @@  discard block
 block discarded – undo
6003 6003
 
6004 6004
 						return null;';
6005 6005
 		} else {
6006
-			$outdelayed.='
6006
+			$outdelayed .= '
6007 6007
 
6008 6008
 						return data;';
6009 6009
 		}
6010 6010
 
6011
-		$outdelayed.='
6011
+		$outdelayed .= '
6012 6012
 					}
6013 6013
 				});
6014 6014
 
@@ -6026,18 +6026,18 @@  discard block
 block discarded – undo
6026 6026
 							location.assign(value.url);
6027 6027
 						}
6028 6028
 					});
6029
-				});' : '' ) . '
6029
+				});' : '').'
6030 6030
 
6031 6031
 			});
6032 6032
 			</script>';
6033 6033
 
6034 6034
 		if ($acceptdelayedhtml)
6035 6035
 		{
6036
-			$delayedhtmlcontent.=$outdelayed;
6036
+			$delayedhtmlcontent .= $outdelayed;
6037 6037
 		}
6038 6038
 		else
6039 6039
 		{
6040
-			$out.=$outdelayed;
6040
+			$out .= $outdelayed;
6041 6041
 		}
6042 6042
 		return $out;
6043 6043
 	}
@@ -6060,7 +6060,7 @@  discard block
 block discarded – undo
6060 6060
 	 *	@return	string					HTML multiselect string
6061 6061
 	 *  @see selectarray
6062 6062
 	 */
6063
-	static function multiselectarray($htmlname, $array, $selected=array(), $key_in_label=0, $value_as_key=0, $morecss='', $translate=0, $width=0, $moreattrib='', $elemtype='', $placeholder='', $addjscombo=1)
6063
+	static function multiselectarray($htmlname, $array, $selected = array(), $key_in_label = 0, $value_as_key = 0, $morecss = '', $translate = 0, $width = 0, $moreattrib = '', $elemtype = '', $placeholder = '', $addjscombo = 1)
6064 6064
 	{
6065 6065
 		global $conf, $langs;
6066 6066
 
@@ -6068,36 +6068,36 @@  discard block
 block discarded – undo
6068 6068
 
6069 6069
 
6070 6070
 		// Add code for jquery to use multiselect
6071
-		if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
6071
+		if (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
6072 6072
 		{
6073
-			$out.="\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
6073
+			$out .= "\n".'<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
6074 6074
 						<script type="text/javascript">'."\n";
6075 6075
 			if ($addjscombo == 1)
6076 6076
 			{
6077
-				$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
6078
-				$out.=	'function formatResult(record) {'."\n";
6077
+				$tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
6078
+				$out .= 'function formatResult(record) {'."\n";
6079 6079
 				if ($elemtype == 'category')
6080 6080
 				{
6081
-					$out.='	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6081
+					$out .= '	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6082 6082
 									  	return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
6083 6083
 				}
6084 6084
 				else
6085 6085
 				{
6086
-					$out.='return record.text;';
6086
+					$out .= 'return record.text;';
6087 6087
 				}
6088
-				$out.=	'};'."\n";
6089
-				$out.=	'function formatSelection(record) {'."\n";
6088
+				$out .= '};'."\n";
6089
+				$out .= 'function formatSelection(record) {'."\n";
6090 6090
 				if ($elemtype == 'category')
6091 6091
 				{
6092
-					$out.='	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6092
+					$out .= '	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6093 6093
 									  	return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
6094 6094
 				}
6095 6095
 				else
6096 6096
 				{
6097
-					$out.='return record.text;';
6097
+					$out .= 'return record.text;';
6098 6098
 				}
6099
-				$out.=	'};'."\n";
6100
-				$out.=	'$(document).ready(function () {
6099
+				$out .= '};'."\n";
6100
+				$out .= '$(document).ready(function () {
6101 6101
 							$(\'#'.$htmlname.'\').'.$tmpplugin.'({
6102 6102
 								dir: \'ltr\',
6103 6103
 								// Specify format function for dropdown item
@@ -6113,7 +6113,7 @@  discard block
 block discarded – undo
6113 6113
 			{
6114 6114
 				// Add other js lib
6115 6115
 				// ...
6116
-				$out.= '$(document).ready(function () {
6116
+				$out .= '$(document).ready(function () {
6117 6117
 							$(\'#'.$htmlname.'\').multiSelect({
6118 6118
 								containerHTML: \'<div class="multi-select-container">\',
6119 6119
 								menuHTML: \'<div class="multi-select-menu">\',
@@ -6124,35 +6124,35 @@  discard block
 block discarded – undo
6124 6124
 							});
6125 6125
 						})';
6126 6126
 			}
6127
-			$out.=	'</script>';
6127
+			$out .= '</script>';
6128 6128
 		}
6129 6129
 
6130 6130
 		// Try also magic suggest
6131 6131
 
6132
-		$out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss?' '.$morecss:'').'" multiple name="'.$htmlname.'[]"'.($moreattrib?' '.$moreattrib:'').($width?' style="width: '.(preg_match('/%/',$width)?$width:$width.'px').'"':'').'>'."\n";
6133
-		if (is_array($array) && ! empty($array))
6132
+		$out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss ? ' '.$morecss : '').'" multiple name="'.$htmlname.'[]"'.($moreattrib ? ' '.$moreattrib : '').($width ? ' style="width: '.(preg_match('/%/', $width) ? $width : $width.'px').'"' : '').'>'."\n";
6133
+		if (is_array($array) && !empty($array))
6134 6134
 		{
6135
-			if ($value_as_key) $array=array_combine($array, $array);
6135
+			if ($value_as_key) $array = array_combine($array, $array);
6136 6136
 
6137
-			if (! empty($array))
6137
+			if (!empty($array))
6138 6138
 			{
6139 6139
 				foreach ($array as $key => $value)
6140 6140
 				{
6141
-					$out.= '<option value="'.$key.'"';
6142
-					if (is_array($selected) && ! empty($selected) && in_array($key, $selected) && !empty($key))
6141
+					$out .= '<option value="'.$key.'"';
6142
+					if (is_array($selected) && !empty($selected) && in_array($key, $selected) && !empty($key))
6143 6143
 					{
6144
-						$out.= ' selected';
6144
+						$out .= ' selected';
6145 6145
 					}
6146
-					$out.= '>';
6146
+					$out .= '>';
6147 6147
 
6148 6148
 					$newval = ($translate ? $langs->trans($value) : $value);
6149 6149
 					$newval = ($key_in_label ? $key.' - '.$newval : $newval);
6150
-					$out.= dol_htmlentitiesbr($newval);
6151
-					$out.= '</option>'."\n";
6150
+					$out .= dol_htmlentitiesbr($newval);
6151
+					$out .= '</option>'."\n";
6152 6152
 				}
6153 6153
 			}
6154 6154
 		}
6155
-		$out.= '</select>'."\n";
6155
+		$out .= '</select>'."\n";
6156 6156
 
6157 6157
 		return $out;
6158 6158
 	}
@@ -6169,50 +6169,50 @@  discard block
 block discarded – undo
6169 6169
 	 */
6170 6170
 	static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
6171 6171
 	{
6172
-		global $conf,$langs,$user;
6172
+		global $conf, $langs, $user;
6173 6173
 
6174
-		if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
6174
+		if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
6175 6175
 
6176
-		$tmpvar="MAIN_SELECTEDFIELDS_".$varpage;
6177
-		if (! empty($user->conf->$tmpvar))
6176
+		$tmpvar = "MAIN_SELECTEDFIELDS_".$varpage;
6177
+		if (!empty($user->conf->$tmpvar))
6178 6178
 		{
6179
-			$tmparray=explode(',', $user->conf->$tmpvar);
6180
-			foreach($array as $key => $val)
6179
+			$tmparray = explode(',', $user->conf->$tmpvar);
6180
+			foreach ($array as $key => $val)
6181 6181
 			{
6182 6182
 				//var_dump($key);
6183 6183
 				//var_dump($tmparray);
6184
-				if (in_array($key, $tmparray)) $array[$key]['checked']=1;
6185
-				else $array[$key]['checked']=0;
6184
+				if (in_array($key, $tmparray)) $array[$key]['checked'] = 1;
6185
+				else $array[$key]['checked'] = 0;
6186 6186
 			}
6187 6187
 		}
6188 6188
 		//var_dump($array);
6189 6189
 
6190
-		$lis='';
6191
-		$listcheckedstring='';
6190
+		$lis = '';
6191
+		$listcheckedstring = '';
6192 6192
 
6193
-		foreach($array as $key => $val)
6193
+		foreach ($array as $key => $val)
6194 6194
 		{
6195 6195
 		   /* var_dump($val);
6196 6196
             var_dump(array_key_exists('enabled', $val));
6197 6197
             var_dump(!$val['enabled']);*/
6198
-		   if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled'])
6198
+		   if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled'])
6199 6199
 		   {
6200
-			   unset($array[$key]);     // We don't want this field
6200
+			   unset($array[$key]); // We don't want this field
6201 6201
 			   continue;
6202 6202
 		   }
6203 6203
 		   if ($val['label'])
6204 6204
 		   {
6205
-		   	$lis.='<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.(empty($val['checked'])?'':' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
6206
-			   $listcheckedstring.=(empty($val['checked'])?'':$key.',');
6205
+		   	$lis .= '<li><input type="checkbox" id="checkbox'.$key.'" value="'.$key.'"'.(empty($val['checked']) ? '' : ' checked="checked"').'/><label for="checkbox'.$key.'">'.dol_escape_htmltag($langs->trans($val['label'])).'</label></li>';
6206
+			   $listcheckedstring .= (empty($val['checked']) ? '' : $key.',');
6207 6207
 		   }
6208 6208
 		}
6209 6209
 
6210
-		$out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
6210
+		$out = '<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
6211 6211
 
6212 6212
         <dl class="dropdown">
6213 6213
             <dt>
6214 6214
             <a href="#">
6215
-              '.img_picto('','list').'
6215
+              '.img_picto('', 'list').'
6216 6216
             </a>
6217 6217
             <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
6218 6218
             </dt>
@@ -6255,7 +6255,7 @@  discard block
 block discarded – undo
6255 6255
 	 *  @param		int		$rendermode		0=Default, use multiselect. 1=Emulate multiselect (recommended)
6256 6256
 	 * 	@return		string					String with categories
6257 6257
 	 */
6258
-	function showCategories($id, $type, $rendermode=0)
6258
+	function showCategories($id, $type, $rendermode = 0)
6259 6259
 	{
6260 6260
 		global $db;
6261 6261
 
@@ -6267,12 +6267,12 @@  discard block
 block discarded – undo
6267 6267
 		if ($rendermode == 1)
6268 6268
 		{
6269 6269
 			$toprint = array();
6270
-			foreach($categories as $c)
6270
+			foreach ($categories as $c)
6271 6271
 			{
6272
-				$ways = $c->print_all_ways();       // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
6273
-				foreach($ways as $way)
6272
+				$ways = $c->print_all_ways(); // $ways[0] = "ccc2 >> ccc2a >> ccc2a1" with html formated text
6273
+				foreach ($ways as $way)
6274 6274
 				{
6275
-					$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color?' style="background: #'.$c->color.';"':' style="background: #aaa"').'>'.img_object('','category').' '.$way.'</li>';
6275
+					$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories"'.($c->color ? ' style="background: #'.$c->color.';"' : ' style="background: #aaa"').'>'.img_object('', 'category').' '.$way.'</li>';
6276 6276
 				}
6277 6277
 			}
6278 6278
 			return '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
@@ -6281,14 +6281,14 @@  discard block
 block discarded – undo
6281 6281
 		if ($rendermode == 0)
6282 6282
 		{
6283 6283
 			$cate_arbo = $this->select_all_categories($type, '', 'parent', 64, 0, 1);
6284
-			foreach($categories as $c) {
6284
+			foreach ($categories as $c) {
6285 6285
 				$arrayselected[] = $c->id;
6286 6286
 			}
6287 6287
 
6288 6288
 			return $this->multiselectarray('categories', $cate_arbo, $arrayselected, '', 0, '', 0, '100%', 'disabled', 'category');
6289 6289
 		}
6290 6290
 
6291
-		return 'ErrorBadValueForParameterRenderMode';	// Should not happened
6291
+		return 'ErrorBadValueForParameterRenderMode'; // Should not happened
6292 6292
 	}
6293 6293
 
6294 6294
 
@@ -6300,20 +6300,20 @@  discard block
 block discarded – undo
6300 6300
 	 *  @param  array           $compatibleImportElementsList  Array of compatibles elements object for "import from" action
6301 6301
 	 *  @return	int							      <0 if KO, >=0 if OK
6302 6302
 	 */
6303
-	function showLinkedObjectBlock($object, $morehtmlright='',$compatibleImportElementsList=false)
6303
+	function showLinkedObjectBlock($object, $morehtmlright = '', $compatibleImportElementsList = false)
6304 6304
 	{
6305
-		global $conf,$langs,$hookmanager;
6305
+		global $conf, $langs, $hookmanager;
6306 6306
 		global $bc;
6307 6307
 
6308 6308
 		$object->fetchObjectLinked();
6309 6309
 
6310 6310
 		// Bypass the default method
6311 6311
 		$hookmanager->initHooks(array('commonobject'));
6312
-		$parameters=array(
6312
+		$parameters = array(
6313 6313
 			'morehtmlright' => $morehtmlright,
6314 6314
 		    'compatibleImportElementsList' =>& $compatibleImportElementsList,
6315 6315
 		);
6316
-		$reshook=$hookmanager->executeHooks('showLinkedObjectBlock',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
6316
+		$reshook = $hookmanager->executeHooks('showLinkedObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
6317 6317
 
6318 6318
 		if (empty($reshook))
6319 6319
 		{
@@ -6336,65 +6336,65 @@  discard block
 block discarded – undo
6336 6336
 			print '<td></td>';
6337 6337
 			print '</tr>';
6338 6338
 
6339
-			$nboftypesoutput=0;
6339
+			$nboftypesoutput = 0;
6340 6340
 
6341
-			foreach($object->linkedObjects as $objecttype => $objects)
6341
+			foreach ($object->linkedObjects as $objecttype => $objects)
6342 6342
 			{
6343 6343
 				$tplpath = $element = $subelement = $objecttype;
6344 6344
 
6345 6345
 				// to display inport button on tpl
6346
-				$showImportButton=false;
6347
-				if(!empty($compatibleImportElementsList) && in_array($element,$compatibleImportElementsList)){
6348
-				    $showImportButton=true;
6346
+				$showImportButton = false;
6347
+				if (!empty($compatibleImportElementsList) && in_array($element, $compatibleImportElementsList)) {
6348
+				    $showImportButton = true;
6349 6349
 				}
6350 6350
 
6351
-				if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
6351
+				if ($objecttype != 'supplier_proposal' && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
6352 6352
 				{
6353 6353
 					$element = $regs[1];
6354 6354
 					$subelement = $regs[2];
6355 6355
 					$tplpath = $element.'/'.$subelement;
6356 6356
 				}
6357
-				$tplname='linkedobjectblock';
6357
+				$tplname = 'linkedobjectblock';
6358 6358
 
6359 6359
 				// To work with non standard path
6360
-				if ($objecttype == 'facture')          {
6360
+				if ($objecttype == 'facture') {
6361 6361
 					$tplpath = 'compta/'.$element;
6362
-					if (empty($conf->facture->enabled)) continue;	// Do not show if module disabled
6362
+					if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
6363 6363
 				}
6364
-				else if ($objecttype == 'facturerec')          {
6364
+				else if ($objecttype == 'facturerec') {
6365 6365
 					$tplpath = 'compta/facture';
6366 6366
 					$tplname = 'linkedobjectblockForRec';
6367
-					if (empty($conf->facture->enabled)) continue;	// Do not show if module disabled
6367
+					if (empty($conf->facture->enabled)) continue; // Do not show if module disabled
6368 6368
 				}
6369
-				else if ($objecttype == 'propal')           {
6369
+				else if ($objecttype == 'propal') {
6370 6370
 					$tplpath = 'comm/'.$element;
6371
-					if (empty($conf->propal->enabled)) continue;	// Do not show if module disabled
6371
+					if (empty($conf->propal->enabled)) continue; // Do not show if module disabled
6372 6372
 				}
6373
-				else if ($objecttype == 'supplier_proposal')           {
6374
-					if (empty($conf->supplier_proposal->enabled)) continue;	// Do not show if module disabled
6373
+				else if ($objecttype == 'supplier_proposal') {
6374
+					if (empty($conf->supplier_proposal->enabled)) continue; // Do not show if module disabled
6375 6375
 				}
6376 6376
 				else if ($objecttype == 'shipping' || $objecttype == 'shipment') {
6377 6377
 					$tplpath = 'expedition';
6378
-					if (empty($conf->expedition->enabled)) continue;	// Do not show if module disabled
6378
+					if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
6379 6379
 				}
6380 6380
         		else if ($objecttype == 'reception') {
6381 6381
         			$tplpath = 'reception';
6382
-        			if (empty($conf->reception->enabled)) continue;	// Do not show if module disabled
6382
+        			if (empty($conf->reception->enabled)) continue; // Do not show if module disabled
6383 6383
         		}
6384
-				else if ($objecttype == 'delivery')         {
6384
+				else if ($objecttype == 'delivery') {
6385 6385
 					$tplpath = 'livraison';
6386
-					if (empty($conf->expedition->enabled)) continue;	// Do not show if module disabled
6386
+					if (empty($conf->expedition->enabled)) continue; // Do not show if module disabled
6387 6387
 				}
6388 6388
 				else if ($objecttype == 'invoice_supplier') {
6389 6389
 					$tplpath = 'fourn/facture';
6390 6390
 				}
6391
-				else if ($objecttype == 'order_supplier')   {
6391
+				else if ($objecttype == 'order_supplier') {
6392 6392
 					$tplpath = 'fourn/commande';
6393 6393
 				}
6394
-				else if ($objecttype == 'expensereport')   {
6394
+				else if ($objecttype == 'expensereport') {
6395 6395
 					$tplpath = 'expensereport';
6396 6396
 				}
6397
-				else if ($objecttype == 'subscription')   {
6397
+				else if ($objecttype == 'subscription') {
6398 6398
 					$tplpath = 'adherents';
6399 6399
 				}
6400 6400
 
@@ -6403,16 +6403,16 @@  discard block
 block discarded – undo
6403 6403
 
6404 6404
 
6405 6405
 				// Output template part (modules that overwrite templates must declare this into descriptor)
6406
-				$dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));
6407
-				foreach($dirtpls as $reldir)
6406
+				$dirtpls = array_merge($conf->modules_parts['tpl'], array('/'.$tplpath.'/tpl'));
6407
+				foreach ($dirtpls as $reldir)
6408 6408
 				{
6409 6409
 					if ($nboftypesoutput == ($nbofdifferenttypes - 1))    // No more type to show after
6410 6410
 					{
6411 6411
 						global $noMoreLinkedObjectBlockAfter;
6412
-						$noMoreLinkedObjectBlockAfter=1;
6412
+						$noMoreLinkedObjectBlockAfter = 1;
6413 6413
 					}
6414 6414
 
6415
-					$res=@include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
6415
+					$res = @include dol_buildpath($reldir.'/'.$tplname.'.tpl.php');
6416 6416
 					if ($res)
6417 6417
 					{
6418 6418
 						$nboftypesoutput++;
@@ -6421,16 +6421,16 @@  discard block
 block discarded – undo
6421 6421
 				}
6422 6422
 			}
6423 6423
 
6424
-			if (! $nboftypesoutput)
6424
+			if (!$nboftypesoutput)
6425 6425
 			{
6426 6426
 				print '<tr><td class="impair opacitymedium" colspan="7">'.$langs->trans("None").'</td></tr>';
6427 6427
 			}
6428 6428
 
6429 6429
 			print '</table>';
6430 6430
 
6431
-			if(!empty($compatibleImportElementsList))
6431
+			if (!empty($compatibleImportElementsList))
6432 6432
 			{
6433
-			    $res=@include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
6433
+			    $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php');
6434 6434
 			}
6435 6435
 
6436 6436
 
@@ -6448,41 +6448,41 @@  discard block
 block discarded – undo
6448 6448
 	 *  @param	array			$excludelinksto		Do not show links of this type, for exemple array('order') or array('supplier_order'). null or array() if no exclusion.
6449 6449
 	 *  @return	string								<0 if KO, >0 if OK
6450 6450
 	 */
6451
-	function showLinkToObjectBlock($object, $restrictlinksto=array(), $excludelinksto=array())
6451
+	function showLinkToObjectBlock($object, $restrictlinksto = array(), $excludelinksto = array())
6452 6452
 	{
6453 6453
 		global $conf, $langs, $hookmanager;
6454 6454
 		global $bc;
6455 6455
 
6456
-		$linktoelem='';
6457
-		$linktoelemlist='';
6458
-		$listofidcompanytoscan='';
6456
+		$linktoelem = '';
6457
+		$linktoelemlist = '';
6458
+		$listofidcompanytoscan = '';
6459 6459
 
6460
-		if (! is_object($object->thirdparty)) $object->fetch_thirdparty();
6460
+		if (!is_object($object->thirdparty)) $object->fetch_thirdparty();
6461 6461
 
6462
-		$possiblelinks=array();
6463
-		if (is_object($object->thirdparty) && ! empty($object->thirdparty->id) && $object->thirdparty->id > 0)
6462
+		$possiblelinks = array();
6463
+		if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0)
6464 6464
 		{
6465
-			$listofidcompanytoscan=$object->thirdparty->id;
6466
-			if (($object->thirdparty->parent > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan.=','.$object->thirdparty->parent;
6467
-			if (($object->fk_project > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))
6465
+			$listofidcompanytoscan = $object->thirdparty->id;
6466
+			if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan .= ','.$object->thirdparty->parent;
6467
+			if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))
6468 6468
 			{
6469 6469
 				include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
6470
-				$tmpproject=new Project($this->db);
6470
+				$tmpproject = new Project($this->db);
6471 6471
 				$tmpproject->fetch($object->fk_project);
6472
-				if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan.=','.$tmpproject->socid;
6472
+				if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan .= ','.$tmpproject->socid;
6473 6473
 				unset($tmpproject);
6474 6474
 			}
6475 6475
 
6476
-			$possiblelinks=array(
6476
+			$possiblelinks = array(
6477 6477
 				'propal'=>array('enabled'=>$conf->propal->enabled, 'perms'=>1, 'label'=>'LinkToProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('propal').')'),
6478 6478
 				'order'=>array('enabled'=>$conf->commande->enabled, 'perms'=>1, 'label'=>'LinkToOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande').')'),
6479 6479
 				'invoice'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_client, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
6480 6480
 				'invoice_template'=>array('enabled'=>$conf->facture->enabled, 'perms'=>1, 'label'=>'LinkToTemplateInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.titre as ref, t.total as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_rec as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('invoice').')'),
6481
-				'contrat'=>array('enabled'=>$conf->contrat->enabled , 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'),
6481
+				'contrat'=>array('enabled'=>$conf->contrat->enabled, 'perms'=>1, 'label'=>'LinkToContract', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, '' as total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."contrat as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('contract').')'),
6482 6482
 				'fichinter'=>array('enabled'=>$conf->ficheinter->enabled, 'perms'=>1, 'label'=>'LinkToIntervention', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."fichinter as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('intervention').')'),
6483
-				'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled , 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'),
6484
-				'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled , 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
6485
-				'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled , 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')')
6483
+				'supplier_proposal'=>array('enabled'=>$conf->supplier_proposal->enabled, 'perms'=>1, 'label'=>'LinkToSupplierProposal', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, '' as ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."supplier_proposal as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('supplier_proposal').')'),
6484
+				'order_supplier'=>array('enabled'=>$conf->supplier_order->enabled, 'perms'=>1, 'label'=>'LinkToSupplierOrder', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande_fournisseur as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('commande_fournisseur').')'),
6485
+				'invoice_supplier'=>array('enabled'=>$conf->supplier_invoice->enabled, 'perms'=>1, 'label'=>'LinkToSupplierInvoice', 'sql'=>"SELECT s.rowid as socid, s.nom as name, s.client, t.rowid, t.ref, t.ref_supplier, t.total_ht FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as t WHERE t.fk_soc = s.rowid AND t.fk_soc IN (".$listofidcompanytoscan.') AND t.entity IN ('.getEntity('facture_fourn').')')
6486 6486
 			);
6487 6487
 		}
6488 6488
 
@@ -6490,32 +6490,32 @@  discard block
 block discarded – undo
6490 6490
 
6491 6491
 		// Can complete the possiblelink array
6492 6492
 		$hookmanager->initHooks(array('commonobject'));
6493
-		$parameters=array('listofidcompanytoscan' => $listofidcompanytoscan);
6494
-		$reshook=$hookmanager->executeHooks('showLinkToObjectBlock',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
6493
+		$parameters = array('listofidcompanytoscan' => $listofidcompanytoscan);
6494
+		$reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
6495 6495
 		if (empty($reshook))
6496 6496
 		{
6497 6497
 			if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
6498 6498
 			{
6499
-				$possiblelinks=array_merge($possiblelinks, $hookmanager->resArray);
6499
+				$possiblelinks = array_merge($possiblelinks, $hookmanager->resArray);
6500 6500
 			}
6501 6501
 		}
6502 6502
 		else if ($reshook > 0)
6503 6503
 		{
6504 6504
 			if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
6505 6505
 			{
6506
-				$possiblelinks=$hookmanager->resArray;
6506
+				$possiblelinks = $hookmanager->resArray;
6507 6507
 			}
6508 6508
 		}
6509 6509
 
6510
-		foreach($possiblelinks as $key => $possiblelink)
6510
+		foreach ($possiblelinks as $key => $possiblelink)
6511 6511
 		{
6512 6512
 			$num = 0;
6513 6513
 
6514 6514
 			if (empty($possiblelink['enabled'])) continue;
6515 6515
 
6516
-			if (! empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || ! in_array($key, $excludelinksto)))
6516
+			if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto)))
6517 6517
 			{
6518
-				print '<div id="'.$key.'list"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?' style="display:none"':'').'>';
6518
+				print '<div id="'.$key.'list"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ' style="display:none"' : '').'>';
6519 6519
 				$sql = $possiblelink['sql'];
6520 6520
 
6521 6521
 				$resqllist = $this->db->query($sql);
@@ -6531,10 +6531,10 @@  discard block
 block discarded – undo
6531 6531
 					print '<table class="noborder">';
6532 6532
 					print '<tr class="liste_titre">';
6533 6533
 					print '<td class="nowrap"></td>';
6534
-					print '<td align="center">' . $langs->trans("Ref") . '</td>';
6535
-					print '<td align="left">' . $langs->trans("RefCustomer") . '</td>';
6536
-					print '<td align="right">' . $langs->trans("AmountHTShort") . '</td>';
6537
-					print '<td align="left">' . $langs->trans("Company") . '</td>';
6534
+					print '<td align="center">'.$langs->trans("Ref").'</td>';
6535
+					print '<td align="left">'.$langs->trans("RefCustomer").'</td>';
6536
+					print '<td align="right">'.$langs->trans("AmountHTShort").'</td>';
6537
+					print '<td align="left">'.$langs->trans("Company").'</td>';
6538 6538
 					print '</tr>';
6539 6539
 					while ($i < $num)
6540 6540
 					{
@@ -6542,17 +6542,17 @@  discard block
 block discarded – undo
6542 6542
 
6543 6543
 						print '<tr class="oddeven">';
6544 6544
 						print '<td aling="left">';
6545
-						print '<input type="radio" name="idtolinkto" value=' . $objp->rowid . '>';
6545
+						print '<input type="radio" name="idtolinkto" value='.$objp->rowid.'>';
6546 6546
 						print '</td>';
6547
-						print '<td align="center">' . $objp->ref . '</td>';
6548
-						print '<td>' . $objp->ref_client . '</td>';
6549
-						print '<td align="right">' . price($objp->total_ht) . '</td>';
6550
-						print '<td>' . $objp->name . '</td>';
6547
+						print '<td align="center">'.$objp->ref.'</td>';
6548
+						print '<td>'.$objp->ref_client.'</td>';
6549
+						print '<td align="right">'.price($objp->total_ht).'</td>';
6550
+						print '<td>'.$objp->name.'</td>';
6551 6551
 						print '</tr>';
6552 6552
 						$i++;
6553 6553
 					}
6554 6554
 					print '</table>';
6555
-					print '<div class="center"><input type="submit" class="button valignmiddle" value="' . $langs->trans('ToLink') . '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></div>';
6555
+					print '<div class="center"><input type="submit" class="button valignmiddle" value="'.$langs->trans('ToLink').'">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button" name="cancel" value="'.$langs->trans('Cancel').'"></div>';
6556 6556
 
6557 6557
 					print '</form>';
6558 6558
 					$this->db->free($resqllist);
@@ -6565,15 +6565,15 @@  discard block
 block discarded – undo
6565 6565
 				}
6566 6566
 
6567 6567
 				//$linktoelem.=($linktoelem?' &nbsp; ':'');
6568
-				if ($num > 0) $linktoelemlist.='<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">' . $langs->trans($possiblelink['label']) .' ('.$num.')</a></li>';
6568
+				if ($num > 0) $linktoelemlist .= '<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">'.$langs->trans($possiblelink['label']).' ('.$num.')</a></li>';
6569 6569
 				//else $linktoelem.=$langs->trans($possiblelink['label']);
6570
-				else $linktoelemlist.='<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
6570
+				else $linktoelemlist .= '<li><span class="linktodisabled">'.$langs->trans($possiblelink['label']).' (0)</span></li>';
6571 6571
 			}
6572 6572
 		}
6573 6573
 
6574 6574
 		if ($linktoelemlist)
6575 6575
 		{
6576
-			$linktoelem='
6576
+			$linktoelem = '
6577 6577
     		<dl class="dropdown" id="linktoobjectname">
6578 6578
     		<dt><a href="#linktoobjectname">'.$langs->trans("LinkTo").'...</a></dt>
6579 6579
     		<dd>
@@ -6586,7 +6586,7 @@  discard block
 block discarded – undo
6586 6586
 		}
6587 6587
 		else
6588 6588
 		{
6589
-			$linktoelem='';
6589
+			$linktoelem = '';
6590 6590
 		}
6591 6591
 
6592 6592
 		print '<!-- Add js to show linkto box -->
@@ -6614,21 +6614,21 @@  discard block
 block discarded – undo
6614 6614
 	 *  @param	int      	$useempty		1=Add empty line
6615 6615
 	 *	@return	string						See option
6616 6616
 	 */
6617
-	function selectyesno($htmlname, $value='', $option=0, $disabled=false, $useempty=0)
6617
+	function selectyesno($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0)
6618 6618
 	{
6619 6619
 		global $langs;
6620 6620
 
6621
-		$yes="yes"; $no="no";
6621
+		$yes = "yes"; $no = "no";
6622 6622
 		if ($option)
6623 6623
 		{
6624
-			$yes="1";
6625
-			$no="0";
6624
+			$yes = "1";
6625
+			$no = "0";
6626 6626
 		}
6627 6627
 
6628 6628
 		$disabled = ($disabled ? ' disabled' : '');
6629 6629
 
6630 6630
 		$resultyesno = '<select class="flat width75" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
6631
-		if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0)?' selected':'').'>&nbsp;</option>'."\n";
6631
+		if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0) ? ' selected' : '').'>&nbsp;</option>'."\n";
6632 6632
 		if (("$value" == 'yes') || ($value == 1))
6633 6633
 		{
6634 6634
 			$resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
@@ -6636,7 +6636,7 @@  discard block
 block discarded – undo
6636 6636
 		}
6637 6637
 		else
6638 6638
 	   {
6639
-	   		$selected=(($useempty && $value != '0' && $value != 'no')?'':' selected');
6639
+	   		$selected = (($useempty && $value != '0' && $value != 'no') ? '' : ' selected');
6640 6640
 			$resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
6641 6641
 			$resultyesno .= '<option value="'.$no.'"'.$selected.'>'.$langs->trans("No").'</option>'."\n";
6642 6642
 		}
@@ -6656,13 +6656,13 @@  discard block
 block discarded – undo
6656 6656
 	 *  @param  int		$useempty          Affiche valeur vide dans liste
6657 6657
 	 *  @return	void
6658 6658
 	 */
6659
-	function select_export_model($selected='',$htmlname='exportmodelid',$type='',$useempty=0)
6659
+	function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0)
6660 6660
 	{
6661 6661
         // phpcs:enable
6662 6662
 		$sql = "SELECT rowid, label";
6663
-		$sql.= " FROM ".MAIN_DB_PREFIX."export_model";
6664
-		$sql.= " WHERE type = '".$type."'";
6665
-		$sql.= " ORDER BY rowid";
6663
+		$sql .= " FROM ".MAIN_DB_PREFIX."export_model";
6664
+		$sql .= " WHERE type = '".$type."'";
6665
+		$sql .= " ORDER BY rowid";
6666 6666
 		$result = $this->db->query($sql);
6667 6667
 		if ($result)
6668 6668
 		{
@@ -6714,33 +6714,33 @@  discard block
 block discarded – undo
6714 6714
 	 *	  @param	string	$morehtmlright	More html code to show after ref.
6715 6715
 	 * 	  @return	string    				Portion HTML with ref + navigation buttons
6716 6716
 	 */
6717
-	function showrefnav($object,$paramid,$morehtml='',$shownav=1,$fieldid='rowid',$fieldref='ref',$morehtmlref='',$moreparam='',$nodbprefix=0,$morehtmlleft='',$morehtmlstatus='',$morehtmlright='')
6717
+	function showrefnav($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $morehtmlright = '')
6718 6718
 	{
6719
-		global $langs,$conf,$hookmanager;
6719
+		global $langs, $conf, $hookmanager;
6720 6720
 
6721
-		$ret='';
6722
-		if (empty($fieldid))  $fieldid='rowid';
6723
-		if (empty($fieldref)) $fieldref='ref';
6721
+		$ret = '';
6722
+		if (empty($fieldid))  $fieldid = 'rowid';
6723
+		if (empty($fieldref)) $fieldref = 'ref';
6724 6724
 
6725 6725
 		// Add where from hooks
6726 6726
 		if (is_object($hookmanager))
6727 6727
 		{
6728
-			$parameters=array();
6729
-			$reshook=$hookmanager->executeHooks('printFieldListWhere',$parameters, $object);    // Note that $action and $object may have been modified by hook
6730
-			$object->next_prev_filter.=$hookmanager->resPrint;
6728
+			$parameters = array();
6729
+			$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
6730
+			$object->next_prev_filter .= $hookmanager->resPrint;
6731 6731
 		}
6732 6732
 		$previous_ref = $next_ref = '';
6733 6733
 		if ($shownav)
6734 6734
 		{
6735 6735
 			//print "paramid=$paramid,morehtml=$morehtml,shownav=$shownav,$fieldid,$fieldref,$morehtmlref,$moreparam";
6736
-			$object->load_previous_next_ref((isset($object->next_prev_filter)?$object->next_prev_filter:''), $fieldid, $nodbprefix);
6736
+			$object->load_previous_next_ref((isset($object->next_prev_filter) ? $object->next_prev_filter : ''), $fieldid, $nodbprefix);
6737 6737
 
6738 6738
 			$navurl = $_SERVER["PHP_SELF"];
6739 6739
 			// Special case for project/task page
6740 6740
 			if ($paramid == 'project_ref')
6741 6741
 			{
6742
-				$navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/','/tasks.php',$navurl);
6743
-				$paramid='ref';
6742
+				$navurl = preg_replace('/\/tasks\/(task|contact|time|note|document)\.php/', '/tasks.php', $navurl);
6743
+				$paramid = 'ref';
6744 6744
 			}
6745 6745
 
6746 6746
 			// accesskey is for Windows or Linux:  ALT + key for chrome, ALT + SHIFT + KEY for firefox
@@ -6759,96 +6759,96 @@  discard block
 block discarded – undo
6759 6759
 				$stringforfirstkey .= ' CTL +';
6760 6760
 			}
6761 6761
 
6762
-			$previous_ref = $object->ref_previous?'<a accesskey="p" title="'.$stringforfirstkey.' p" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'"><i class="fa fa-chevron-left"></i></a>':'<span class="inactive"><i class="fa fa-chevron-left opacitymedium"></i></span>';
6763
-			$next_ref     = $object->ref_next?'<a accesskey="n" title="'.$stringforfirstkey.' n" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'"><i class="fa fa-chevron-right"></i></a>':'<span class="inactive"><i class="fa fa-chevron-right opacitymedium"></i></span>';
6762
+			$previous_ref = $object->ref_previous ? '<a accesskey="p" title="'.$stringforfirstkey.' p" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_previous).$moreparam.'"><i class="fa fa-chevron-left"></i></a>' : '<span class="inactive"><i class="fa fa-chevron-left opacitymedium"></i></span>';
6763
+			$next_ref     = $object->ref_next ? '<a accesskey="n" title="'.$stringforfirstkey.' n" class="classfortooltip" href="'.$navurl.'?'.$paramid.'='.urlencode($object->ref_next).$moreparam.'"><i class="fa fa-chevron-right"></i></a>' : '<span class="inactive"><i class="fa fa-chevron-right opacitymedium"></i></span>';
6764 6764
 		}
6765 6765
 
6766 6766
 		//print "xx".$previous_ref."x".$next_ref;
6767
-		$ret.='<!-- Start banner content --><div style="vertical-align: middle">';
6767
+		$ret .= '<!-- Start banner content --><div style="vertical-align: middle">';
6768 6768
 
6769 6769
 		// Right part of banner
6770
-		if ($morehtmlright) $ret.='<div class="inline-block floatleft">'.$morehtmlright.'</div>';
6770
+		if ($morehtmlright) $ret .= '<div class="inline-block floatleft">'.$morehtmlright.'</div>';
6771 6771
 
6772 6772
 		if ($previous_ref || $next_ref || $morehtml)
6773 6773
 		{
6774
-			$ret.='<div class="pagination paginationref"><ul class="right">';
6774
+			$ret .= '<div class="pagination paginationref"><ul class="right">';
6775 6775
 		}
6776 6776
 		if ($morehtml)
6777 6777
 		{
6778
-			$ret.='<li class="noborder litext">'.$morehtml.'</li>';
6778
+			$ret .= '<li class="noborder litext">'.$morehtml.'</li>';
6779 6779
 		}
6780 6780
 		if ($shownav && ($previous_ref || $next_ref))
6781 6781
 		{
6782
-			$ret.='<li class="pagination">'.$previous_ref.'</li>';
6783
-			$ret.='<li class="pagination">'.$next_ref.'</li>';
6782
+			$ret .= '<li class="pagination">'.$previous_ref.'</li>';
6783
+			$ret .= '<li class="pagination">'.$next_ref.'</li>';
6784 6784
 		}
6785 6785
 		if ($previous_ref || $next_ref || $morehtml)
6786 6786
 		{
6787
-			$ret.='</ul></div>';
6787
+			$ret .= '</ul></div>';
6788 6788
 		}
6789 6789
 
6790
-		$parameters=array();
6791
-		$reshook=$hookmanager->executeHooks('moreHtmlStatus',$parameters, $object);    // Note that $action and $object may have been modified by hook
6792
-		if (empty($reshook)) $morehtmlstatus.=$hookmanager->resPrint;
6793
-		else $morehtmlstatus=$hookmanager->resPrint;
6794
-		if ($morehtmlstatus) $ret.='<div class="statusref">'.$morehtmlstatus.'</div>';
6790
+		$parameters = array();
6791
+		$reshook = $hookmanager->executeHooks('moreHtmlStatus', $parameters, $object); // Note that $action and $object may have been modified by hook
6792
+		if (empty($reshook)) $morehtmlstatus .= $hookmanager->resPrint;
6793
+		else $morehtmlstatus = $hookmanager->resPrint;
6794
+		if ($morehtmlstatus) $ret .= '<div class="statusref">'.$morehtmlstatus.'</div>';
6795 6795
 
6796 6796
 		$parameters = array();
6797 6797
 		$reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
6798
-		if (empty($reshook)) $morehtmlref.=$hookmanager->resPrint;
6799
-		elseif ($reshook > 0) $morehtmlref=$hookmanager->resPrint;
6798
+		if (empty($reshook)) $morehtmlref .= $hookmanager->resPrint;
6799
+		elseif ($reshook > 0) $morehtmlref = $hookmanager->resPrint;
6800 6800
 
6801 6801
 		// Left part of banner
6802 6802
 		if ($morehtmlleft)
6803 6803
 		{
6804
-			if ($conf->browser->layout == 'phone') $ret.='<div class="floatleft">'.$morehtmlleft.'</div>';    // class="center" to have photo in middle
6805
-			else $ret.='<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
6804
+			if ($conf->browser->layout == 'phone') $ret .= '<div class="floatleft">'.$morehtmlleft.'</div>'; // class="center" to have photo in middle
6805
+			else $ret .= '<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
6806 6806
 		}
6807 6807
 
6808 6808
 		//if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
6809
-		$ret.='<div class="inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref))?' refidpadding':'').'">';
6809
+		$ret .= '<div class="inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref)) ? ' refidpadding' : '').'">';
6810 6810
 
6811 6811
 		// For thirdparty, contact, user, member, the ref is the id, so we show something else
6812 6812
 		if ($object->element == 'societe')
6813 6813
 		{
6814
-			$ret.=dol_htmlentities($object->name);
6814
+			$ret .= dol_htmlentities($object->name);
6815 6815
 		}
6816 6816
 		else if ($object->element == 'member')
6817 6817
 		{
6818
-			$ret.=$object->ref.'<br>';
6819
-			$fullname=$object->getFullName($langs);
6818
+			$ret .= $object->ref.'<br>';
6819
+			$fullname = $object->getFullName($langs);
6820 6820
 			if ($object->morphy == 'mor' && $object->societe) {
6821
-				$ret.= dol_htmlentities($object->societe) . ((! empty($fullname) && $object->societe != $fullname)?' ('.dol_htmlentities($fullname).')':'');
6821
+				$ret .= dol_htmlentities($object->societe).((!empty($fullname) && $object->societe != $fullname) ? ' ('.dol_htmlentities($fullname).')' : '');
6822 6822
 			} else {
6823
-				$ret.= dol_htmlentities($fullname) . ((! empty($object->societe) && $object->societe != $fullname)?' ('.dol_htmlentities($object->societe).')':'');
6823
+				$ret .= dol_htmlentities($fullname).((!empty($object->societe) && $object->societe != $fullname) ? ' ('.dol_htmlentities($object->societe).')' : '');
6824 6824
 			}
6825 6825
 		}
6826 6826
 		else if (in_array($object->element, array('contact', 'user', 'usergroup')))
6827 6827
 		{
6828
-			$ret.=dol_htmlentities($object->getFullName($langs));
6828
+			$ret .= dol_htmlentities($object->getFullName($langs));
6829 6829
 		}
6830 6830
 		else if (in_array($object->element, array('action', 'agenda')))
6831 6831
 		{
6832
-			$ret.=$object->ref.'<br>'.$object->label;
6832
+			$ret .= $object->ref.'<br>'.$object->label;
6833 6833
 		}
6834 6834
 		else if (in_array($object->element, array('adherent_type')))
6835 6835
 		{
6836
-			$ret.=$object->label;
6836
+			$ret .= $object->label;
6837 6837
 		}
6838 6838
 		else if ($object->element == 'ecm_directories')
6839 6839
 		{
6840
-			$ret.='';
6840
+			$ret .= '';
6841 6841
 		}
6842
-		else if ($fieldref != 'none') $ret.=dol_htmlentities($object->$fieldref);
6842
+		else if ($fieldref != 'none') $ret .= dol_htmlentities($object->$fieldref);
6843 6843
 
6844 6844
 
6845 6845
 		if ($morehtmlref)
6846 6846
 		{
6847
-			$ret.=' '.$morehtmlref;
6847
+			$ret .= ' '.$morehtmlref;
6848 6848
 		}
6849
-		$ret.='</div>';
6849
+		$ret .= '</div>';
6850 6850
 
6851
-		$ret.='</div><!-- End banner content -->';
6851
+		$ret .= '</div><!-- End banner content -->';
6852 6852
 
6853 6853
 		return $ret;
6854 6854
 	}
@@ -6861,7 +6861,7 @@  discard block
 block discarded – undo
6861 6861
 	 * 		@param	int		$width			Width of photo
6862 6862
 	 * 	  	@return string    				HTML code to output barcode
6863 6863
 	 */
6864
-	function showbarcode(&$object,$width=100)
6864
+	function showbarcode(&$object, $width = 100)
6865 6865
 	{
6866 6866
 		global $conf;
6867 6867
 
@@ -6877,9 +6877,9 @@  discard block
 block discarded – undo
6877 6877
 		}
6878 6878
 
6879 6879
 		// Barcode image
6880
-		$url=DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
6881
-		$out ='<!-- url barcode = '.$url.' -->';
6882
-		$out.='<img src="'.$url.'">';
6880
+		$url = DOL_URL_ROOT.'/viewimage.php?modulepart=barcode&generator='.urlencode($object->barcode_type_coder).'&code='.urlencode($object->barcode).'&encoding='.urlencode($object->barcode_type_code);
6881
+		$out = '<!-- url barcode = '.$url.' -->';
6882
+		$out .= '<img src="'.$url.'">';
6883 6883
 		return $out;
6884 6884
 	}
6885 6885
 
@@ -6898,80 +6898,80 @@  discard block
 block discarded – undo
6898 6898
 	 *      @param	string		$forcecapture		Force parameter capture on HTML input file element to ask a smartphone to allow to open camera to take photo. Auto if empty.
6899 6899
 	 * 	  	@return string    						HTML code to output photo
6900 6900
 	 */
6901
-	static function showphoto($modulepart, $object, $width=100, $height=0, $caneditfield=0, $cssclass='photowithmargin', $imagesize='', $addlinktofullsize=1, $cache=0, $forcecapture='')
6901
+	static function showphoto($modulepart, $object, $width = 100, $height = 0, $caneditfield = 0, $cssclass = 'photowithmargin', $imagesize = '', $addlinktofullsize = 1, $cache = 0, $forcecapture = '')
6902 6902
 	{
6903
-		global $conf,$langs;
6903
+		global $conf, $langs;
6904 6904
 
6905
-		$entity = (! empty($object->entity) ? $object->entity : $conf->entity);
6906
-		$id = (! empty($object->id) ? $object->id : $object->rowid);
6905
+		$entity = (!empty($object->entity) ? $object->entity : $conf->entity);
6906
+		$id = (!empty($object->id) ? $object->id : $object->rowid);
6907 6907
 
6908
-		$ret='';$dir='';$file='';$originalfile='';$altfile='';$email='';$capture='';
6909
-		if ($modulepart=='societe')
6908
+		$ret = ''; $dir = ''; $file = ''; $originalfile = ''; $altfile = ''; $email = ''; $capture = '';
6909
+		if ($modulepart == 'societe')
6910 6910
 		{
6911
-			$dir=$conf->societe->multidir_output[$entity];
6912
-			if (! empty($object->logo))
6911
+			$dir = $conf->societe->multidir_output[$entity];
6912
+			if (!empty($object->logo))
6913 6913
 			{
6914
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini');             // getImageFileNameForSize include the thumbs
6915
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
6916
-				else $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6917
-				$originalfile=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6914
+				if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini'); // getImageFileNameForSize include the thumbs
6915
+				else if ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
6916
+				else $file = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6917
+				$originalfile = get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6918 6918
 			}
6919
-			$email=$object->email;
6919
+			$email = $object->email;
6920 6920
 		}
6921
-		else if ($modulepart=='contact')
6921
+		else if ($modulepart == 'contact')
6922 6922
 		{
6923
-			$dir=$conf->societe->multidir_output[$entity].'/contact';
6924
-			if (! empty($object->photo))
6923
+			$dir = $conf->societe->multidir_output[$entity].'/contact';
6924
+			if (!empty($object->photo))
6925 6925
 			{
6926
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
6927
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
6928
-				else $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6929
-				$originalfile=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6926
+				if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
6927
+				else if ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
6928
+				else $file = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6929
+				$originalfile = get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6930 6930
 			}
6931
-			$email=$object->email;
6932
-			$capture='user';
6931
+			$email = $object->email;
6932
+			$capture = 'user';
6933 6933
 		}
6934
-		else if ($modulepart=='userphoto')
6934
+		else if ($modulepart == 'userphoto')
6935 6935
 		{
6936
-			$dir=$conf->user->dir_output;
6937
-			if (! empty($object->photo))
6936
+			$dir = $conf->user->dir_output;
6937
+			if (!empty($object->photo))
6938 6938
 			{
6939
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_mini');
6940
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_small');
6941
-				else $file=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6942
-				$originalfile=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6939
+				if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_mini');
6940
+				else if ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_small');
6941
+				else $file = get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6942
+				$originalfile = get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6943 6943
 			}
6944
-			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6945
-			$email=$object->email;
6946
-			$capture='user';
6944
+			if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile = $object->id.".jpg"; // For backward compatibility
6945
+			$email = $object->email;
6946
+			$capture = 'user';
6947 6947
 		}
6948
-		else if ($modulepart=='memberphoto')
6948
+		else if ($modulepart == 'memberphoto')
6949 6949
 		{
6950
-			$dir=$conf->adherent->dir_output;
6951
-			if (! empty($object->photo))
6950
+			$dir = $conf->adherent->dir_output;
6951
+			if (!empty($object->photo))
6952 6952
 			{
6953
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
6954
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
6955
-				else $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6956
-				$originalfile=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6953
+				if ((string) $imagesize == 'mini') $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
6954
+				else if ((string) $imagesize == 'small') $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
6955
+				else $file = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6956
+				$originalfile = get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6957 6957
 			}
6958
-			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6959
-			$email=$object->email;
6960
-			$capture='user';
6958
+			if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile = $object->id.".jpg"; // For backward compatibility
6959
+			$email = $object->email;
6960
+			$capture = 'user';
6961 6961
 		}
6962 6962
 		else
6963 6963
 		{
6964 6964
 			// Generic case to show photos
6965
-			$dir=$conf->$modulepart->dir_output;
6966
-			if (! empty($object->photo))
6965
+			$dir = $conf->$modulepart->dir_output;
6966
+			if (!empty($object->photo))
6967 6967
 			{
6968
-				if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
6969
-				else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
6970
-				else $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6971
-				$originalfile=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6968
+				if ((string) $imagesize == 'mini') $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
6969
+				else if ((string) $imagesize == 'small') $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
6970
+				else $file = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6971
+				$originalfile = get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6972 6972
 			}
6973
-			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
6974
-			$email=$object->email;
6973
+			if (!empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile = $object->id.".jpg"; // For backward compatibility
6974
+			$email = $object->email;
6975 6975
 		}
6976 6976
 
6977 6977
 		if ($forcecapture) $capture = $forcecapture;
@@ -6982,61 +6982,61 @@  discard block
 block discarded – undo
6982 6982
 			{
6983 6983
 				if ($addlinktofullsize)
6984 6984
 				{
6985
-					$urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6986
-					if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
6987
-					else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
6985
+					$urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6986
+					if ($urladvanced) $ret .= '<a href="'.$urladvanced.'">';
6987
+					else $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
6988 6988
 				}
6989
-				$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($file).'&cache='.$cache.'">';
6990
-				if ($addlinktofullsize) $ret.='</a>';
6989
+				$ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="Photo" id="photologo'.(preg_replace('/[^a-z]/i', '_', $file)).'" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($file).'&cache='.$cache.'">';
6990
+				if ($addlinktofullsize) $ret .= '</a>';
6991 6991
 			}
6992 6992
 			else if ($altfile && file_exists($dir."/".$altfile))
6993 6993
 			{
6994 6994
 				if ($addlinktofullsize)
6995 6995
 				{
6996
-					$urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6997
-					if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
6998
-					else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
6996
+					$urladvanced = getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6997
+					if ($urladvanced) $ret .= '<a href="'.$urladvanced.'">';
6998
+					else $ret .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
6999 6999
 				}
7000
-				$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo alt" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" class="'.$cssclass.'" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($altfile).'&cache='.$cache.'">';
7001
-				if ($addlinktofullsize) $ret.='</a>';
7000
+				$ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="Photo alt" id="photologo'.(preg_replace('/[^a-z]/i', '_', $file)).'" class="'.$cssclass.'" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($altfile).'&cache='.$cache.'">';
7001
+				if ($addlinktofullsize) $ret .= '</a>';
7002 7002
 			}
7003 7003
 			else
7004 7004
 			{
7005
-				$nophoto='/public/theme/common/nophoto.png';
7006
-				if (in_array($modulepart,array('userphoto','contact')))	// For module that are "physical" users
7005
+				$nophoto = '/public/theme/common/nophoto.png';
7006
+				if (in_array($modulepart, array('userphoto', 'contact')))	// For module that are "physical" users
7007 7007
 				{
7008
-					$nophoto='/public/theme/common/user_anonymous.png';
7009
-					if ($object->gender == 'man') $nophoto='/public/theme/common/user_man.png';
7010
-					if ($object->gender == 'woman') $nophoto='/public/theme/common/user_woman.png';
7008
+					$nophoto = '/public/theme/common/user_anonymous.png';
7009
+					if ($object->gender == 'man') $nophoto = '/public/theme/common/user_man.png';
7010
+					if ($object->gender == 'woman') $nophoto = '/public/theme/common/user_woman.png';
7011 7011
 				}
7012 7012
 
7013
-				if (! empty($conf->gravatar->enabled) && $email)
7013
+				if (!empty($conf->gravatar->enabled) && $email)
7014 7014
 				{
7015 7015
 					/**
7016 7016
 					 * @see https://gravatar.com/site/implement/images/php/
7017 7017
 					 */
7018 7018
 					global $dolibarr_main_url_root;
7019
-					$ret.='<!-- Put link to gravatar -->';
7019
+					$ret .= '<!-- Put link to gravatar -->';
7020 7020
 					//$defaultimg=urlencode(dol_buildpath($nophoto,3));
7021
-					$defaultimg='mm';
7022
-					$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Gravatar avatar" title="'.$email.' Gravatar avatar" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="https://www.gravatar.com/avatar/'.dol_hash(strtolower(trim($email)),3).'?s='.$width.'&d='.$defaultimg.'">';	// gravatar need md5 hash
7021
+					$defaultimg = 'mm';
7022
+					$ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="Gravatar avatar" title="'.$email.' Gravatar avatar" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="https://www.gravatar.com/avatar/'.dol_hash(strtolower(trim($email)), 3).'?s='.$width.'&d='.$defaultimg.'">'; // gravatar need md5 hash
7023 7023
 				}
7024 7024
 				else
7025 7025
 				{
7026
-					$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'">';
7026
+					$ret .= '<img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" '.($width ? ' width="'.$width.'"' : '').($height ? ' height="'.$height.'"' : '').' src="'.DOL_URL_ROOT.$nophoto.'">';
7027 7027
 				}
7028 7028
 			}
7029 7029
 
7030 7030
 			if ($caneditfield)
7031 7031
 			{
7032
-				if ($object->photo) $ret.="<br>\n";
7033
-				$ret.='<table class="nobordernopadding centpercent">';
7034
-				if ($object->photo) $ret.='<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
7035
-				$ret.='<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput"'.($capture?' capture="'.$capture.'"':'').'></td></tr>';
7036
-				$ret.='</table>';
7032
+				if ($object->photo) $ret .= "<br>\n";
7033
+				$ret .= '<table class="nobordernopadding centpercent">';
7034
+				if ($object->photo) $ret .= '<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
7035
+				$ret .= '<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput"'.($capture ? ' capture="'.$capture.'"' : '').'></td></tr>';
7036
+				$ret .= '</table>';
7037 7037
 			}
7038 7038
 		}
7039
-		else dol_print_error('','Call of showphoto with wrong parameters modulepart='.$modulepart);
7039
+		else dol_print_error('', 'Call of showphoto with wrong parameters modulepart='.$modulepart);
7040 7040
 
7041 7041
 		return $ret;
7042 7042
 	}
@@ -7057,87 +7057,87 @@  discard block
 block discarded – undo
7057 7057
 	 *  @return	string
7058 7058
 	 *  @see select_dolusers
7059 7059
 	 */
7060
-	function select_dolgroups($selected='', $htmlname='groupid', $show_empty=0, $exclude='', $disabled=0, $include='', $enableonly='', $force_entity='0', $multiple=false)
7060
+	function select_dolgroups($selected = '', $htmlname = 'groupid', $show_empty = 0, $exclude = '', $disabled = 0, $include = '', $enableonly = '', $force_entity = '0', $multiple = false)
7061 7061
 	{
7062 7062
         // phpcs:enable
7063
-		global $conf,$user,$langs;
7063
+		global $conf, $user, $langs;
7064 7064
 
7065 7065
 		// Permettre l'exclusion de groupes
7066
-		if (is_array($exclude))	$excludeGroups = implode("','",$exclude);
7066
+		if (is_array($exclude))	$excludeGroups = implode("','", $exclude);
7067 7067
 		// Permettre l'inclusion de groupes
7068
-		if (is_array($include))	$includeGroups = implode("','",$include);
7068
+		if (is_array($include))	$includeGroups = implode("','", $include);
7069 7069
 
7070 7070
 		if (!is_array($selected)) $selected = array($selected);
7071 7071
 
7072
-		$out='';
7072
+		$out = '';
7073 7073
 
7074 7074
 		// On recherche les groupes
7075 7075
 		$sql = "SELECT ug.rowid, ug.nom as name";
7076
-		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
7076
+		if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
7077 7077
 		{
7078
-			$sql.= ", e.label";
7078
+			$sql .= ", e.label";
7079 7079
 		}
7080
-		$sql.= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
7081
-		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
7080
+		$sql .= " FROM ".MAIN_DB_PREFIX."usergroup as ug ";
7081
+		if (!empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && !$user->entity)
7082 7082
 		{
7083
-			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
7084
-			if ($force_entity) $sql.= " WHERE ug.entity IN (0,".$force_entity.")";
7085
-			else $sql.= " WHERE ug.entity IS NOT NULL";
7083
+			$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
7084
+			if ($force_entity) $sql .= " WHERE ug.entity IN (0,".$force_entity.")";
7085
+			else $sql .= " WHERE ug.entity IS NOT NULL";
7086 7086
 		}
7087 7087
 		else
7088 7088
 		{
7089
-			$sql.= " WHERE ug.entity IN (0,".$conf->entity.")";
7089
+			$sql .= " WHERE ug.entity IN (0,".$conf->entity.")";
7090 7090
 		}
7091
-		if (is_array($exclude) && $excludeGroups) $sql.= " AND ug.rowid NOT IN ('".$excludeGroups."')";
7092
-		if (is_array($include) && $includeGroups) $sql.= " AND ug.rowid IN ('".$includeGroups."')";
7093
-		$sql.= " ORDER BY ug.nom ASC";
7091
+		if (is_array($exclude) && $excludeGroups) $sql .= " AND ug.rowid NOT IN ('".$excludeGroups."')";
7092
+		if (is_array($include) && $includeGroups) $sql .= " AND ug.rowid IN ('".$includeGroups."')";
7093
+		$sql .= " ORDER BY ug.nom ASC";
7094 7094
 
7095 7095
 		dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
7096
-		$resql=$this->db->query($sql);
7096
+		$resql = $this->db->query($sql);
7097 7097
 		if ($resql)
7098 7098
 		{
7099 7099
 			// Enhance with select2
7100
-			include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
7100
+			include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
7101 7101
 		   	$out .= ajax_combobox($htmlname);
7102 7102
 
7103
-			$out.= '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
7103
+			$out .= '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled ? ' disabled' : '').'>';
7104 7104
 
7105 7105
 			$num = $this->db->num_rows($resql);
7106 7106
 			$i = 0;
7107 7107
 			if ($num)
7108 7108
 			{
7109
-				if ($show_empty && !$multiple) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'>&nbsp;</option>'."\n";
7109
+				if ($show_empty && !$multiple) $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'>&nbsp;</option>'."\n";
7110 7110
 
7111 7111
 				while ($i < $num)
7112 7112
 				{
7113 7113
 					$obj = $this->db->fetch_object($resql);
7114
-					$disableline=0;
7115
-					if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;
7114
+					$disableline = 0;
7115
+					if (is_array($enableonly) && count($enableonly) && !in_array($obj->rowid, $enableonly)) $disableline = 1;
7116 7116
 
7117
-					$out.= '<option value="'.$obj->rowid.'"';
7118
-					if ($disableline) $out.= ' disabled';
7119
-					if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (! is_object($selected[0]) && in_array($obj->rowid,$selected) ))
7117
+					$out .= '<option value="'.$obj->rowid.'"';
7118
+					if ($disableline) $out .= ' disabled';
7119
+					if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (!is_object($selected[0]) && in_array($obj->rowid, $selected)))
7120 7120
 					{
7121
-						$out.= ' selected';
7121
+						$out .= ' selected';
7122 7122
 					}
7123
-					$out.= '>';
7123
+					$out .= '>';
7124 7124
 
7125
-					$out.= $obj->name;
7126
-					if (! empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)
7125
+					$out .= $obj->name;
7126
+					if (!empty($conf->multicompany->enabled) && empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) && $conf->entity == 1)
7127 7127
 					{
7128
-						$out.= " (".$obj->label.")";
7128
+						$out .= " (".$obj->label.")";
7129 7129
 					}
7130 7130
 
7131
-					$out.= '</option>';
7131
+					$out .= '</option>';
7132 7132
 					$i++;
7133 7133
 				}
7134 7134
 			}
7135 7135
 			else
7136 7136
 			{
7137
-				if ($show_empty) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'></option>'."\n";
7138
-				$out.= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
7137
+				if ($show_empty) $out .= '<option value="-1"'.(in_array(-1, $selected) ? ' selected' : '').'></option>'."\n";
7138
+				$out .= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
7139 7139
 			}
7140
-			$out.= '</select>';
7140
+			$out .= '</select>';
7141 7141
 		}
7142 7142
 		else
7143 7143
 		{
@@ -7157,10 +7157,10 @@  discard block
 block discarded – undo
7157 7157
 	{
7158 7158
 		global $conf, $langs;
7159 7159
 
7160
-		$out='<div class="nowrap">';
7161
-		$out.='<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"),'search.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
7162
-		$out.='<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"),'searchclear.png','','',1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
7163
-		$out.='</div>';
7160
+		$out = '<div class="nowrap">';
7161
+		$out .= '<input type="image" class="liste_titre" name="button_search" src="'.img_picto($langs->trans("Search"), 'search.png', '', '', 1).'" value="'.dol_escape_htmltag($langs->trans("Search")).'" title="'.dol_escape_htmltag($langs->trans("Search")).'">';
7162
+		$out .= '<input type="image" class="liste_titre" name="button_removefilter" src="'.img_picto($langs->trans("Search"), 'searchclear.png', '', '', 1).'" value="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'" title="'.dol_escape_htmltag($langs->trans("RemoveFilter")).'">';
7163
+		$out .= '</div>';
7164 7164
 
7165 7165
 		return $out;
7166 7166
 	}
@@ -7172,13 +7172,13 @@  discard block
 block discarded – undo
7172 7172
 	 *  @param  int     $calljsfunction            0=default. 1=call function initCheckForSelect() after changing status of checkboxes
7173 7173
 	 *  @return	string
7174 7174
 	 */
7175
-	function showCheckAddButtons($cssclass='checkforaction', $calljsfunction=0)
7175
+	function showCheckAddButtons($cssclass = 'checkforaction', $calljsfunction = 0)
7176 7176
 	{
7177 7177
 		global $conf, $langs;
7178 7178
 
7179
-		$out='';
7180
-		if (! empty($conf->use_javascript_ajax)) $out.='<div class="inline-block checkallactions"><input type="checkbox" id="checkallactions" name="checkallactions" class="checkallactions"></div>';
7181
-		$out.='<script type="text/javascript">
7179
+		$out = '';
7180
+		if (!empty($conf->use_javascript_ajax)) $out .= '<div class="inline-block checkallactions"><input type="checkbox" id="checkallactions" name="checkallactions" class="checkallactions"></div>';
7181
+		$out .= '<script type="text/javascript">
7182 7182
             $(document).ready(function() {
7183 7183
             	$("#checkallactions").click(function() {
7184 7184
                     if($(this).is(\':checked\')){
@@ -7190,8 +7190,8 @@  discard block
 block discarded – undo
7190 7190
                         console.log("We uncheck all");
7191 7191
                 		$(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
7192 7192
                     }'."\n";
7193
-		if ($calljsfunction) $out.='if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
7194
-		$out.='         });
7193
+		if ($calljsfunction) $out .= 'if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
7194
+		$out .= '         });
7195 7195
 
7196 7196
         	$(".checkforselect").change(function() {
7197 7197
 				$(this).closest("tr").toggleClass("highlight", this.checked);
@@ -7211,12 +7211,12 @@  discard block
 block discarded – undo
7211 7211
 	 *  @param  int     $calljsfunction            0=default. 1=call function initCheckForSelect() after changing status of checkboxes
7212 7212
 	 *  @return	string
7213 7213
 	 */
7214
-	function showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0)
7214
+	function showFilterAndCheckAddButtons($addcheckuncheckall = 0, $cssclass = 'checkforaction', $calljsfunction = 0)
7215 7215
 	{
7216
-		$out.=$this->showFilterButtons();
7216
+		$out .= $this->showFilterButtons();
7217 7217
 		if ($addcheckuncheckall)
7218 7218
 		{
7219
-			$out.=$this->showCheckAddButtons($cssclass, $calljsfunction);
7219
+			$out .= $this->showCheckAddButtons($cssclass, $calljsfunction);
7220 7220
 		}
7221 7221
 		return $out;
7222 7222
 	}
@@ -7233,27 +7233,27 @@  discard block
 block discarded – undo
7233 7233
 	 * @param	array	$params                param to give
7234 7234
 	 * @return	string
7235 7235
 	 */
7236
-	function selectExpenseCategories($selected='', $htmlname='fk_c_exp_tax_cat', $useempty=0, $excludeid=array(), $target='', $default_selected=0, $params=array())
7236
+	function selectExpenseCategories($selected = '', $htmlname = 'fk_c_exp_tax_cat', $useempty = 0, $excludeid = array(), $target = '', $default_selected = 0, $params = array())
7237 7237
 	{
7238 7238
 		global $db, $conf, $langs, $user;
7239 7239
 
7240 7240
 		$sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';
7241
-		$sql.= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
7242
-		if (!empty($excludeid)) $sql.= ' AND rowid NOT IN ('.implode(',', $excludeid).')';
7243
-		$sql.= ' ORDER BY label';
7241
+		$sql .= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
7242
+		if (!empty($excludeid)) $sql .= ' AND rowid NOT IN ('.implode(',', $excludeid).')';
7243
+		$sql .= ' ORDER BY label';
7244 7244
 
7245 7245
 		$resql = $db->query($sql);
7246 7246
 		if ($resql)
7247 7247
 		{
7248 7248
 			$out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7249
-			if ($useempty) $out.= '<option value="0">&nbsp;</option>';
7249
+			if ($useempty) $out .= '<option value="0">&nbsp;</option>';
7250 7250
 
7251 7251
 			while ($obj = $db->fetch_object($resql))
7252 7252
 			{
7253
-				$out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
7253
+				$out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
7254 7254
 			}
7255
-			$out.= '</select>';
7256
-			if (! empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
7255
+			$out .= '</select>';
7256
+			if (!empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
7257 7257
 
7258 7258
 			if (!empty($target))
7259 7259
 			{
@@ -7264,14 +7264,14 @@  discard block
 block discarded – undo
7264 7264
 					if ($db->num_rows($resql) > 0)
7265 7265
 					{
7266 7266
 						$obj = $db->fetch_object($resql);
7267
-						$out.= '<script type="text/javascript">
7267
+						$out .= '<script type="text/javascript">
7268 7268
 							$(function() {
7269 7269
 								$("select[name='.$target.']").on("change", function() {
7270 7270
 									var current_val = $(this).val();
7271 7271
 									if (current_val == '.$obj->id.') {';
7272
-						if (!empty($default_selected) || !empty($selected)) $out.= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
7272
+						if (!empty($default_selected) || !empty($selected)) $out .= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
7273 7273
 
7274
-						$out.= '
7274
+						$out .= '
7275 7275
 										$("select[name='.$htmlname.']").change();
7276 7276
 									}
7277 7277
 								});
@@ -7322,24 +7322,24 @@  discard block
 block discarded – undo
7322 7322
 	 * @param	integer	$useempty    1=Add empty line
7323 7323
 	 * @return	string
7324 7324
 	 */
7325
-	function selectExpenseRanges($selected='', $htmlname='fk_range', $useempty=0)
7325
+	function selectExpenseRanges($selected = '', $htmlname = 'fk_range', $useempty = 0)
7326 7326
 	{
7327
-		global $db,$conf,$langs;
7327
+		global $db, $conf, $langs;
7328 7328
 
7329 7329
 		$sql = 'SELECT rowid, range_ik FROM '.MAIN_DB_PREFIX.'c_exp_tax_range';
7330
-		$sql.= ' WHERE entity = '.$conf->entity.' AND active = 1';
7330
+		$sql .= ' WHERE entity = '.$conf->entity.' AND active = 1';
7331 7331
 
7332 7332
 		$resql = $db->query($sql);
7333 7333
 		if ($resql)
7334 7334
 		{
7335 7335
 			$out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7336
-			if ($useempty) $out.= '<option value="0"></option>';
7336
+			if ($useempty) $out .= '<option value="0"></option>';
7337 7337
 
7338 7338
 			while ($obj = $db->fetch_object($resql))
7339 7339
 			{
7340
-				$out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
7340
+				$out .= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
7341 7341
 			}
7342
-			$out.= '</select>';
7342
+			$out .= '</select>';
7343 7343
 		}
7344 7344
 		else
7345 7345
 		{
@@ -7359,19 +7359,19 @@  discard block
 block discarded – undo
7359 7359
 	 * @param	integer	$useid       0=use 'code' as key, 1=use 'id' as key
7360 7360
 	 * @return	string
7361 7361
 	 */
7362
-	function selectExpense($selected='', $htmlname='fk_c_type_fees', $useempty=0, $allchoice=1, $useid=0)
7362
+	function selectExpense($selected = '', $htmlname = 'fk_c_type_fees', $useempty = 0, $allchoice = 1, $useid = 0)
7363 7363
 	{
7364
-		global $db,$langs;
7364
+		global $db, $langs;
7365 7365
 
7366 7366
 		$sql = 'SELECT id, code, label FROM '.MAIN_DB_PREFIX.'c_type_fees';
7367
-		$sql.= ' WHERE active = 1';
7367
+		$sql .= ' WHERE active = 1';
7368 7368
 
7369 7369
 		$resql = $db->query($sql);
7370 7370
 		if ($resql)
7371 7371
 		{
7372 7372
 			$out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7373
-			if ($useempty) $out.= '<option value="0"></option>';
7374
-			if ($allchoice) $out.= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
7373
+			if ($useempty) $out .= '<option value="0"></option>';
7374
+			if ($allchoice) $out .= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
7375 7375
 
7376 7376
 			$field = 'code';
7377 7377
 			if ($useid) $field = 'id';
@@ -7379,9 +7379,9 @@  discard block
 block discarded – undo
7379 7379
 			while ($obj = $db->fetch_object($resql))
7380 7380
 			{
7381 7381
 				$key = $langs->trans($obj->code);
7382
-				$out.= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
7382
+				$out .= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
7383 7383
 			}
7384
-			$out.= '</select>';
7384
+			$out .= '</select>';
7385 7385
 		}
7386 7386
 		else
7387 7387
 		{
Please login to merge, or discard this patch.
Braces   +1513 added lines, -814 removed lines patch added patch discarded remove patch
@@ -115,32 +115,60 @@  discard block
 block discarded – undo
115 115
 			{
116 116
 				$tmp=explode(':',$typeofdata);
117 117
 				$ret.= '<div class="editkey_'.$tmp[0].(! empty($tmp[1]) ? ' '.$tmp[1] : '').'" id="'.$htmlname.'">';
118
-				if ($fieldrequired) $ret.='<span class="fieldrequired">';
118
+				if ($fieldrequired) {
119
+				    $ret.='<span class="fieldrequired">';
120
+				}
119 121
 				$ret.= $langs->trans($text);
120
-				if ($fieldrequired) $ret.='</span>';
122
+				if ($fieldrequired) {
123
+				    $ret.='</span>';
124
+				}
121 125
 				$ret.= '</div>'."\n";
122
-			}
123
-			else
126
+			} else
124 127
 			{
125
-				if ($fieldrequired) $ret.='<span class="fieldrequired">';
128
+				if ($fieldrequired) {
129
+				    $ret.='<span class="fieldrequired">';
130
+				}
126 131
 				$ret.= $langs->trans($text);
127
-				if ($fieldrequired) $ret.='</span>';
132
+				if ($fieldrequired) {
133
+				    $ret.='</span>';
134
+				}
128 135
 			}
129
-		}
130
-		else
136
+		} else
131 137
 		{
132
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
133
-			if ($fieldrequired) $ret.='<span class="fieldrequired">';
138
+			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) {
139
+			    $ret.='<table class="nobordernopadding" width="100%"><tr><td class="nowrap">';
140
+			}
141
+			if ($fieldrequired) {
142
+			    $ret.='<span class="fieldrequired">';
143
+			}
134 144
 			$ret.=$langs->trans($text);
135
-			if ($fieldrequired) $ret.='</span>';
136
-			if (! empty($notabletag)) $ret.=' ';
137
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
138
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<td align="right">';
139
-			if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='<a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
140
-			if (! empty($notabletag) && $notabletag == 1) $ret.=' : ';
141
-			if (! empty($notabletag) && $notabletag == 3) $ret.=' ';
142
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</td>';
143
-			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) $ret.='</tr></table>';
145
+			if ($fieldrequired) {
146
+			    $ret.='</span>';
147
+			}
148
+			if (! empty($notabletag)) {
149
+			    $ret.=' ';
150
+			}
151
+			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) {
152
+			    $ret.='</td>';
153
+			}
154
+			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) {
155
+			    $ret.='<td align="right">';
156
+			}
157
+			if ($htmlname && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) {
158
+			    $ret.='<a href="'.$_SERVER["PHP_SELF"].'?action=edit'.$htmlname.'&amp;'.$paramid.'='.$object->id.$moreparam.'">'.img_edit($langs->trans('Edit'), ($notabletag ? 0 : 1)).'</a>';
159
+			}
160
+			if (! empty($notabletag) && $notabletag == 1) {
161
+			    $ret.=' : ';
162
+			}
163
+			if (! empty($notabletag) && $notabletag == 3) {
164
+			    $ret.=' ';
165
+			}
166
+			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) {
167
+			    $ret.='</td>';
168
+			}
169
+			if (empty($notabletag) && GETPOST('action','aZ09') != 'edit'.$htmlname && $perm) {
170
+			    $ret.='</tr></table>';
171
+			}
144 172
 		}
145 173
 
146 174
 		return $ret;
@@ -171,14 +199,17 @@  discard block
 block discarded – undo
171 199
 		$ret='';
172 200
 
173 201
 		// Check parameters
174
-		if (empty($typeofdata)) return 'ErrorBadParameter';
202
+		if (empty($typeofdata)) {
203
+		    return 'ErrorBadParameter';
204
+		}
175 205
 
176 206
 		// When option to edit inline is activated
177
-		if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) // TODO add jquery timepicker
207
+		if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! preg_match('/^select;|datehourpicker/',$typeofdata)) {
208
+		    // TODO add jquery timepicker
178 209
 		{
179 210
 			$ret.=$this->editInPlace($object, $value, $htmlname, $perm, $typeofdata, $editvalue, $extObject, $custommsg);
180 211
 		}
181
-		else
212
+		} else
182 213
 		{
183 214
 			if (GETPOST('action','aZ09') == 'edit'.$htmlname)
184 215
 			{
@@ -187,20 +218,22 @@  discard block
 block discarded – undo
187 218
 				$ret.='<input type="hidden" name="action" value="set'.$htmlname.'">';
188 219
 				$ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
189 220
 				$ret.='<input type="hidden" name="'.$paramid.'" value="'.$object->id.'">';
190
-				if (empty($notabletag)) $ret.='<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
191
-				if (empty($notabletag)) $ret.='<tr><td>';
221
+				if (empty($notabletag)) {
222
+				    $ret.='<table class="nobordernopadding centpercent" cellpadding="0" cellspacing="0">';
223
+				}
224
+				if (empty($notabletag)) {
225
+				    $ret.='<tr><td>';
226
+				}
192 227
 				if (preg_match('/^(string|email)/',$typeofdata))
193 228
 				{
194 229
 					$tmp=explode(':',$typeofdata);
195 230
 					$ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($editvalue?$editvalue:$value).'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
196
-				}
197
-				else if (preg_match('/^(numeric|amount)/',$typeofdata))
231
+				} else if (preg_match('/^(numeric|amount)/',$typeofdata))
198 232
 				{
199 233
 					$tmp=explode(':',$typeofdata);
200 234
 					$valuetoshow=price2num($editvalue?$editvalue:$value);
201 235
 					$ret.='<input type="text" id="'.$htmlname.'" name="'.$htmlname.'" value="'.($valuetoshow!=''?price($valuetoshow):'').'"'.($tmp[1]?' size="'.$tmp[1].'"':'').'>';
202
-				}
203
-				else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))
236
+				} else if (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))
204 237
 				{
205 238
 					$tmp=explode(':',$typeofdata);
206 239
 					$cols=$tmp[2];
@@ -216,16 +249,13 @@  discard block
 block discarded – undo
216 249
 					$ret.='<textarea id="'.$htmlname.'" name="'.$htmlname.'" wrap="soft" rows="'.($tmp[1]?$tmp[1]:'20').'"'.($cols?' cols="'.$cols.'"':'class="quatrevingtpercent"').$morealt.'">';
217 250
 					$ret.=dol_string_neverthesehtmltags($valuetoshow, array('textarea'));
218 251
 					$ret.='</textarea>';
219
-				}
220
-				else if ($typeofdata == 'day' || $typeofdata == 'datepicker')
252
+				} else if ($typeofdata == 'day' || $typeofdata == 'datepicker')
221 253
 				{
222 254
 					$ret.=$this->selectDate($value,$htmlname,0,0,1,'form'.$htmlname,1,0);
223
-				}
224
-				else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
255
+				} else if ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker')
225 256
 				{
226 257
 					$ret.=$this->selectDate($value,$htmlname,1,1,1,'form'.$htmlname,1,0);
227
-				}
228
-				else if (preg_match('/^select;/',$typeofdata))
258
+				} else if (preg_match('/^select;/',$typeofdata))
229 259
 				{
230 260
 					 $arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
231 261
 					 foreach($arraydata as $val)
@@ -234,34 +264,47 @@  discard block
 block discarded – undo
234 264
 						 $arraylist[$tmp[0]]=$tmp[1];
235 265
 					 }
236 266
 					 $ret.=$this->selectarray($htmlname,$arraylist,$value);
237
-				}
238
-				else if (preg_match('/^ckeditor/',$typeofdata))
267
+				} else if (preg_match('/^ckeditor/',$typeofdata))
239 268
 				{
240 269
 					$tmp=explode(':',$typeofdata);		// Example: ckeditor:dolibarr_zzz:width:height:savemethod:toolbarstartexpanded:rows:cols
241 270
 					require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
242 271
 					$doleditor=new DolEditor($htmlname, ($editvalue?$editvalue:$value), ($tmp[2]?$tmp[2]:''), ($tmp[3]?$tmp[3]:'100'), ($tmp[1]?$tmp[1]:'dolibarr_notes'), 'In', ($tmp[5]?$tmp[5]:0), true, true, ($tmp[6]?$tmp[6]:'20'), ($tmp[7]?$tmp[7]:'100'));
243 272
 					$ret.=$doleditor->Create(1);
244 273
 				}
245
-				if (empty($notabletag)) $ret.='</td>';
274
+				if (empty($notabletag)) {
275
+				    $ret.='</td>';
276
+				}
246 277
 
247
-				if (empty($notabletag)) $ret.='<td align="left">';
278
+				if (empty($notabletag)) {
279
+				    $ret.='<td align="left">';
280
+				}
248 281
 				//else $ret.='<div class="clearboth"></div>';
249 282
 			   	$ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="modify" value="'.$langs->trans("Modify").'">';
250
-			   	if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) $ret.='<br>'."\n";
283
+			   	if (preg_match('/ckeditor|textarea/',$typeofdata) && empty($notabletag)) {
284
+			   	    $ret.='<br>'."\n";
285
+			   	}
251 286
 			   	$ret.='<input type="submit" class="button'.(empty($notabletag)?'':' ').'" name="cancel" value="'.$langs->trans("Cancel").'">';
252
-			   	if (empty($notabletag)) $ret.='</td>';
287
+			   	if (empty($notabletag)) {
288
+			   	    $ret.='</td>';
289
+			   	}
253 290
 
254
-			   	if (empty($notabletag)) $ret.='</tr></table>'."\n";
291
+			   	if (empty($notabletag)) {
292
+			   	    $ret.='</tr></table>'."\n";
293
+			   	}
255 294
 				$ret.='</form>'."\n";
256
-			}
257
-			else
258
-			{
259
-				if (preg_match('/^(email)/',$typeofdata))              $ret.=dol_print_email($value,0,0,0,0,1);
260
-				elseif (preg_match('/^(amount|numeric)/',$typeofdata)) $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');
261
-				elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata))  $ret.=dol_htmlentitiesbr($value);
262
-				elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') $ret.=dol_print_date($value,'day');
263
-				elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') $ret.=dol_print_date($value,'dayhour');
264
-				else if (preg_match('/^select;/',$typeofdata))
295
+			} else
296
+			{
297
+				if (preg_match('/^(email)/',$typeofdata)) {
298
+				    $ret.=dol_print_email($value,0,0,0,0,1);
299
+				} elseif (preg_match('/^(amount|numeric)/',$typeofdata)) {
300
+				    $ret.=($value != '' ? price($value,'',$langs,0,-1,-1,$conf->currency) : '');
301
+				} elseif (preg_match('/^text/',$typeofdata) || preg_match('/^note/',$typeofdata)) {
302
+				    $ret.=dol_htmlentitiesbr($value);
303
+				} elseif ($typeofdata == 'day' || $typeofdata == 'datepicker') {
304
+				    $ret.=dol_print_date($value,'day');
305
+				} elseif ($typeofdata == 'dayhour' || $typeofdata == 'datehourpicker') {
306
+				    $ret.=dol_print_date($value,'dayhour');
307
+				} else if (preg_match('/^select;/',$typeofdata))
265 308
 				{
266 309
 					$arraydata=explode(',',preg_replace('/^select;/','',$typeofdata));
267 310
 					foreach($arraydata as $val)
@@ -270,8 +313,7 @@  discard block
 block discarded – undo
270 313
 						$arraylist[$tmp[0]]=$tmp[1];
271 314
 					}
272 315
 					$ret.=$arraylist[$value];
273
-				}
274
-				else if (preg_match('/^ckeditor/',$typeofdata))
316
+				} else if (preg_match('/^ckeditor/',$typeofdata))
275 317
 				{
276 318
 					$tmpcontent=dol_htmlentitiesbr($value);
277 319
 					if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
@@ -281,8 +323,9 @@  discard block
 block discarded – undo
281 323
 						$tmpcontent=$firstline.((strlen($firstline) != strlen($tmpcontent))?'...':'');
282 324
 					}
283 325
 					$ret.=$tmpcontent;
326
+				} else {
327
+				    $ret.=$value;
284 328
 				}
285
-				else $ret.=$value;
286 329
 
287 330
 				if ($formatfunc && method_exists($object, $formatfunc))
288 331
 				{
@@ -313,9 +356,13 @@  discard block
 block discarded – undo
313 356
 		$out='';
314 357
 
315 358
 		// Check parameters
316
-		if (preg_match('/^text/',$inputType)) $value = dol_nl2br($value);
317
-		else if (preg_match('/^numeric/',$inputType)) $value = price($value);
318
-		else if ($inputType == 'day' || $inputType == 'datepicker') $value = dol_print_date($value, 'day');
359
+		if (preg_match('/^text/',$inputType)) {
360
+		    $value = dol_nl2br($value);
361
+		} else if (preg_match('/^numeric/',$inputType)) {
362
+		    $value = price($value);
363
+		} else if ($inputType == 'day' || $inputType == 'datepicker') {
364
+		    $value = dol_print_date($value, 'day');
365
+		}
319 366
 
320 367
 		if ($condition)
321 368
 		{
@@ -344,46 +391,59 @@  discard block
 block discarded – undo
344 391
 			{
345 392
 				$tmp=explode(':',$inputType);
346 393
 				$inputType=$tmp[0];
347
-				if (! empty($tmp[1])) $inputOption=$tmp[1];
348
-				if (! empty($tmp[2])) $savemethod=$tmp[2];
394
+				if (! empty($tmp[1])) {
395
+				    $inputOption=$tmp[1];
396
+				}
397
+				if (! empty($tmp[2])) {
398
+				    $savemethod=$tmp[2];
399
+				}
349 400
 				$out.= '<input id="width_'.$htmlname.'" value="'.$inputOption.'" type="hidden"/>'."\n";
350
-			}
351
-			else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))
401
+			} else if ((preg_match('/^day$/',$inputType)) || (preg_match('/^datepicker/',$inputType)) || (preg_match('/^datehourpicker/',$inputType)))
352 402
 			{
353 403
 				$tmp=explode(':',$inputType);
354 404
 				$inputType=$tmp[0];
355
-				if (! empty($tmp[1])) $inputOption=$tmp[1];
356
-				if (! empty($tmp[2])) $savemethod=$tmp[2];
405
+				if (! empty($tmp[1])) {
406
+				    $inputOption=$tmp[1];
407
+				}
408
+				if (! empty($tmp[2])) {
409
+				    $savemethod=$tmp[2];
410
+				}
357 411
 
358 412
 				$out.= '<input id="timestamp" type="hidden"/>'."\n"; // Use for timestamp format
359
-			}
360
-			else if (preg_match('/^(select|autocomplete)/',$inputType))
413
+			} else if (preg_match('/^(select|autocomplete)/',$inputType))
361 414
 			{
362 415
 				$tmp=explode(':',$inputType);
363 416
 				$inputType=$tmp[0]; $loadmethod=$tmp[1];
364
-				if (! empty($tmp[2])) $savemethod=$tmp[2];
365
-				if (! empty($tmp[3])) $button_only=true;
366
-			}
367
-			else if (preg_match('/^textarea/',$inputType))
417
+				if (! empty($tmp[2])) {
418
+				    $savemethod=$tmp[2];
419
+				}
420
+				if (! empty($tmp[3])) {
421
+				    $button_only=true;
422
+				}
423
+			} else if (preg_match('/^textarea/',$inputType))
368 424
 			{
369 425
 				$tmp=explode(':',$inputType);
370 426
 				$inputType=$tmp[0];
371 427
 				$rows=(empty($tmp[1])?'8':$tmp[1]);
372 428
 				$cols=(empty($tmp[2])?'80':$tmp[2]);
373
-			}
374
-			else if (preg_match('/^ckeditor/',$inputType))
429
+			} else if (preg_match('/^ckeditor/',$inputType))
375 430
 			{
376 431
 				$tmp=explode(':',$inputType);
377 432
 				$inputType=$tmp[0]; $toolbar=$tmp[1];
378
-				if (! empty($tmp[2])) $width=$tmp[2];
379
-				if (! empty($tmp[3])) $heigth=$tmp[3];
380
-				if (! empty($tmp[4])) $savemethod=$tmp[4];
433
+				if (! empty($tmp[2])) {
434
+				    $width=$tmp[2];
435
+				}
436
+				if (! empty($tmp[3])) {
437
+				    $heigth=$tmp[3];
438
+				}
439
+				if (! empty($tmp[4])) {
440
+				    $savemethod=$tmp[4];
441
+				}
381 442
 
382 443
 				if (! empty($conf->fckeditor->enabled))
383 444
 				{
384 445
 					$out.= '<input id="ckeditor_toolbar" value="'.$toolbar.'" type="hidden"/>'."\n";
385
-				}
386
-				else
446
+				} else
387 447
 				{
388 448
 					$inputType = 'textarea';
389 449
 				}
@@ -393,19 +453,25 @@  discard block
 block discarded – undo
393 453
 			$out.= '<input id="table_element_'.$htmlname.'" value="'.$table_element.'" type="hidden"/>'."\n";
394 454
 			$out.= '<input id="fk_element_'.$htmlname.'" value="'.$fk_element.'" type="hidden"/>'."\n";
395 455
 			$out.= '<input id="loadmethod_'.$htmlname.'" value="'.$loadmethod.'" type="hidden"/>'."\n";
396
-			if (! empty($savemethod))	$out.= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
397
-			if (! empty($ext_element))	$out.= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
456
+			if (! empty($savemethod)) {
457
+			    $out.= '<input id="savemethod_'.$htmlname.'" value="'.$savemethod.'" type="hidden"/>'."\n";
458
+			}
459
+			if (! empty($ext_element)) {
460
+			    $out.= '<input id="ext_element_'.$htmlname.'" value="'.$ext_element.'" type="hidden"/>'."\n";
461
+			}
398 462
 			if (! empty($custommsg))
399 463
 			{
400 464
 				if (is_array($custommsg))
401 465
 				{
402
-					if (!empty($custommsg['success']))
403
-						$out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
404
-					if (!empty($custommsg['error']))
405
-						$out.= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
466
+					if (!empty($custommsg['success'])) {
467
+											$out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg['success'].'" type="hidden"/>'."\n";
468
+					}
469
+					if (!empty($custommsg['error'])) {
470
+											$out.= '<input id="errormsg_'.$htmlname.'" value="'.$custommsg['error'].'" type="hidden"/>'."\n";
471
+					}
472
+				} else {
473
+									$out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
406 474
 				}
407
-				else
408
-					$out.= '<input id="successmsg_'.$htmlname.'" value="'.$custommsg.'" type="hidden"/>'."\n";
409 475
 			}
410 476
 			if ($inputType == 'textarea') {
411 477
 				$out.= '<input id="textarea_'.$htmlname.'_rows" value="'.$rows.'" type="hidden"/>'."\n";
@@ -413,8 +479,7 @@  discard block
 block discarded – undo
413 479
 			}
414 480
 			$out.= '<span id="viewval_'.$htmlname.'" class="viewval_'.$inputType.($button_only ? ' inactive' : ' active').'">'.$value.'</span>'."\n";
415 481
 			$out.= '<span id="editval_'.$htmlname.'" class="editval_'.$inputType.($button_only ? ' inactive' : ' active').' hideobject">'.(! empty($editvalue) ? $editvalue : $value).'</span>'."\n";
416
-		}
417
-		else
482
+		} else
418 483
 		{
419 484
 			$out = $value;
420 485
 		}
@@ -445,12 +510,20 @@  discard block
 block discarded – undo
445 510
 	{
446 511
 		global $conf;
447 512
 
448
-		if ($incbefore) $text = $incbefore.$text;
449
-		if (! $htmltext) return $text;
513
+		if ($incbefore) {
514
+		    $text = $incbefore.$text;
515
+		}
516
+		if (! $htmltext) {
517
+		    return $text;
518
+		}
450 519
 
451 520
 		$tag='td';
452
-		if ($notabs == 2) $tag='div';
453
-		if ($notabs == 3) $tag='span';
521
+		if ($notabs == 2) {
522
+		    $tag='div';
523
+		}
524
+		if ($notabs == 3) {
525
+		    $tag='span';
526
+		}
454 527
 		// Sanitize tooltip
455 528
 		$htmltext=str_replace("\\","\\\\",$htmltext);
456 529
 		$htmltext=str_replace("\r","",$htmltext);
@@ -467,8 +540,7 @@  discard block
 block discarded – undo
467 540
 		if ($tooltiptrigger == '')
468 541
 		{
469 542
 			$htmltext=str_replace('"',"&quot;",$htmltext);
470
-		}
471
-		else
543
+		} else
472 544
 		{
473 545
 			$classfortooltip='classfortooltiponclick';
474 546
 			$textfordialog.='<div style="display: none;" id="idfortooltiponclick_'.$tooltiptrigger.'" class="classfortooltiponclicktext">'.$htmltext.'</div>';
@@ -476,19 +548,36 @@  discard block
 block discarded – undo
476 548
 		if ($tooltipon == 2 || $tooltipon == 3)
477 549
 		{
478 550
 			$paramfortooltipimg=' class="'.$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'"';
479
-			if ($tooltiptrigger == '') $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on img tag to store tooltip
480
-			else $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"';
551
+			if ($tooltiptrigger == '') {
552
+			    $paramfortooltipimg.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"';
553
+			}
554
+			// Attribut to put on img tag to store tooltip
555
+			else {
556
+			    $paramfortooltipimg.=' dolid="'.$tooltiptrigger.'"';
557
+			}
558
+		} else {
559
+		    $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':'');
481 560
 		}
482
-		else $paramfortooltipimg =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
561
+		// Attribut to put on td text tag
483 562
 		if ($tooltipon == 1 || $tooltipon == 3)
484 563
 		{
485 564
 			$paramfortooltiptd=' class="'.($tooltipon == 3 ? 'cursorpointer ' : '').$classfortooltip.' inline-block'.($extracss?' '.$extracss:'').'" style="padding: 0px;'.($extrastyle?' '.$extrastyle:'').'" ';
486
-			if ($tooltiptrigger == '') $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"'; // Attribut to put on td tag to store tooltip
487
-			else $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"';
565
+			if ($tooltiptrigger == '') {
566
+			    $paramfortooltiptd.=' title="'.($noencodehtmltext?$htmltext:dol_escape_htmltag($htmltext,1)).'"';
567
+			}
568
+			// Attribut to put on td tag to store tooltip
569
+			else {
570
+			    $paramfortooltiptd.=' dolid="'.$tooltiptrigger.'"';
571
+			}
572
+		} else {
573
+		    $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':'');
574
+		}
575
+		// Attribut to put on td text tag
576
+		if (empty($notabs)) {
577
+		    $s.='<table class="nobordernopadding" summary=""><tr style="height: auto;">';
578
+		} elseif ($notabs == 2) {
579
+		    $s.='<div class="inline-block'.($forcenowrap?' nowrap':'').'">';
488 580
 		}
489
-		else $paramfortooltiptd =($extracss?' class="'.$extracss.'"':'').($extrastyle?' style="'.$extrastyle.'"':''); // Attribut to put on td text tag
490
-		if (empty($notabs)) $s.='<table class="nobordernopadding" summary=""><tr style="height: auto;">';
491
-		elseif ($notabs == 2) $s.='<div class="inline-block'.($forcenowrap?' nowrap':'').'">';
492 581
 		// Define value if value is before
493 582
 		if ($direction < 0) {
494 583
 			$s.='<'.$tag.$paramfortooltipimg;
@@ -499,15 +588,22 @@  discard block
 block discarded – undo
499 588
 		}
500 589
 		// Use another method to help avoid having a space in value in order to use this value with jquery
501 590
 		// Define label
502
-		if ((string) $text != '') $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
591
+		if ((string) $text != '') {
592
+		    $s.='<'.$tag.$paramfortooltiptd.'>'.$text.'</'.$tag.'>';
593
+		}
503 594
 		// Define value if value is after
504 595
 		if ($direction > 0) {
505 596
 			$s.='<'.$tag.$paramfortooltipimg;
506
-			if ($tag == 'td') $s .= ' valign="middle" width="14"';
597
+			if ($tag == 'td') {
598
+			    $s .= ' valign="middle" width="14"';
599
+			}
507 600
 			$s.= '>'.$textfordialog.$img.'</'.$tag.'>';
508 601
 		}
509
-		if (empty($notabs)) $s.='</tr></table>';
510
-		elseif ($notabs == 2) $s.='</div>';
602
+		if (empty($notabs)) {
603
+		    $s.='</tr></table>';
604
+		} elseif ($notabs == 2) {
605
+		    $s.='</div>';
606
+		}
511 607
 
512 608
 		return $s;
513 609
 	}
@@ -531,17 +627,23 @@  discard block
 block discarded – undo
531 627
 		global $conf, $langs;
532 628
 
533 629
 		$alt = '';
534
-		if ($tooltiptrigger) $alt=$langs->transnoentitiesnoconv("ClickToShowHelp");
630
+		if ($tooltiptrigger) {
631
+		    $alt=$langs->transnoentitiesnoconv("ClickToShowHelp");
632
+		}
535 633
 
536 634
 		//For backwards compatibility
537
-		if ($type == '0') $type = 'info';
538
-		elseif ($type == '1') $type = 'help';
635
+		if ($type == '0') {
636
+		    $type = 'info';
637
+		} elseif ($type == '1') {
638
+		    $type = 'help';
639
+		}
539 640
 
540 641
 		// If info or help with no javascript, show only text
541 642
 		if (empty($conf->use_javascript_ajax))
542 643
 		{
543
-			if ($type == 'info' || $type == 'help')	return $text;
544
-			else
644
+			if ($type == 'info' || $type == 'help') {
645
+			    return $text;
646
+			} else
545 647
 			{
546 648
 				$alt = $htmltext;
547 649
 				$htmltext = '';
@@ -551,20 +653,31 @@  discard block
 block discarded – undo
551 653
 		// If info or help with smartphone, show only text (tooltip hover can't works)
552 654
 		if (! empty($conf->dol_no_mouse_hover) && empty($tooltiptrigger))
553 655
 		{
554
-			if ($type == 'info' || $type == 'help') return $text;
656
+			if ($type == 'info' || $type == 'help') {
657
+			    return $text;
658
+			}
555 659
 		}
556 660
 		// If info or help with smartphone, show only text (tooltip on lick does not works with dialog on smaprtphone)
557 661
 		if (! empty($conf->dol_no_mouse_hover) && ! empty($tooltiptrigger))
558 662
 		{
559
-			if ($type == 'info' || $type == 'help') return $text;
663
+			if ($type == 'info' || $type == 'help') {
664
+			    return $text;
665
+			}
560 666
 		}
561 667
 
562
-		if ($type == 'info') $img = img_help(0, $alt);
563
-		elseif ($type == 'help') $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
564
-		elseif ($type == 'superadmin') $img = img_picto($alt, 'redstar');
565
-		elseif ($type == 'admin') $img = img_picto($alt, 'star');
566
-		elseif ($type == 'warning') $img = img_warning($alt);
567
-		else $img = img_picto($alt, $type);
668
+		if ($type == 'info') {
669
+		    $img = img_help(0, $alt);
670
+		} elseif ($type == 'help') {
671
+		    $img = img_help(($tooltiptrigger != '' ? 2 : 1), $alt);
672
+		} elseif ($type == 'superadmin') {
673
+		    $img = img_picto($alt, 'redstar');
674
+		} elseif ($type == 'admin') {
675
+		    $img = img_picto($alt, 'star');
676
+		} elseif ($type == 'warning') {
677
+		    $img = img_warning($alt);
678
+		} else {
679
+		    $img = img_picto($alt, $type);
680
+		}
568 681
 
569 682
 		return $this->textwithtooltip($text, $htmltext, (($tooltiptrigger && ! $img)?3:2), $direction, $img, $extracss, $notabs, '', $noencodehtmltext, $tooltiptrigger, $forcenowrap);
570 683
 	}
@@ -581,7 +694,9 @@  discard block
 block discarded – undo
581 694
 	{
582 695
 		global $conf,$langs,$hookmanager;
583 696
 
584
-		if (count($arrayofaction) == 0) return;
697
+		if (count($arrayofaction) == 0) {
698
+		    return;
699
+		}
585 700
 
586 701
 		$disabled=0;
587 702
 		$ret='<div class="centpercent center">';
@@ -719,20 +834,27 @@  discard block
 block discarded – undo
719 834
 					$i++;
720 835
 				}
721 836
 
722
-				if (empty($disablefavorites)) array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
723
-				else $countryArray = dol_sort_array($countryArray, 'label');
837
+				if (empty($disablefavorites)) {
838
+				    array_multisort($favorite, SORT_DESC, $label, SORT_ASC, $countryArray);
839
+				} else {
840
+				    $countryArray = dol_sort_array($countryArray, 'label');
841
+				}
724 842
 
725 843
 				if ($showempty)
726 844
 				{
727 845
 					$out.='<option value="">&nbsp;</option>'."\n";
728 846
 				}
729 847
 
730
-				if ($addspecialentries)	// Add dedicated entries for groups of countries
848
+				if ($addspecialentries) {
849
+				    // Add dedicated entries for groups of countries
731 850
 				{
732 851
 					//if ($showempty) $out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
733 852
 					$out.= '<option value="special_allnotme"'.($selected == 'special_allnotme' ? ' selected' : '').'>'.$langs->trans("CountriesExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
853
+				}
734 854
 					$out.= '<option value="special_eec"'.($selected == 'special_eec' ? ' selected' : '').'>'.$langs->trans("CountriesInEEC").'</option>';
735
-					if ($mysoc->isInEEC()) $out.= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
855
+					if ($mysoc->isInEEC()) {
856
+					    $out.= '<option value="special_eecnotme"'.($selected == 'special_eecnotme' ? ' selected' : '').'>'.$langs->trans("CountriesInEECExceptMe", $langs->transnoentitiesnoconv("Country".$mysoc->country_code)).'</option>';
857
+					}
736 858
 					$out.= '<option value="special_noteec"'.($selected == 'special_noteec' ? ' selected' : '').'>'.$langs->trans("CountriesNotInEEC").'</option>';
737 859
 					$out.= '<option value="" disabled class="selectoptiondisabledwhite">--------------</option>';
738 860
 				}
@@ -740,9 +862,13 @@  discard block
 block discarded – undo
740 862
 				foreach ($countryArray as $row)
741 863
 				{
742 864
 					//if (empty($showempty) && empty($row['rowid'])) continue;
743
-					if (empty($row['rowid'])) continue;
865
+					if (empty($row['rowid'])) {
866
+					    continue;
867
+					}
744 868
 
745
-					if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) $atleastonefavorite++;
869
+					if (empty($disablefavorites) && $row['favorite'] && $row['code_iso']) {
870
+					    $atleastonefavorite++;
871
+					}
746 872
 					if (empty($row['favorite']) && $atleastonefavorite)
747 873
 					{
748 874
 						$atleastonefavorite=0;
@@ -752,20 +878,23 @@  discard block
 block discarded – undo
752 878
 					{
753 879
 						$foundselected=true;
754 880
 						$out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'" selected>';
755
-					}
756
-					else
881
+					} else
757 882
 					{
758 883
 						$out.= '<option value="'.($usecodeaskey?($usecodeaskey=='code2'?$row['code_iso']:$row['code_iso3']):$row['rowid']).'">';
759 884
 					}
760
-					if ($row['label']) $out.= dol_trunc($row['label'],$maxlength,'middle');
761
-					else $out.= '&nbsp;';
762
-					if ($row['code_iso']) $out.= ' ('.$row['code_iso'] . ')';
885
+					if ($row['label']) {
886
+					    $out.= dol_trunc($row['label'],$maxlength,'middle');
887
+					} else {
888
+					    $out.= '&nbsp;';
889
+					}
890
+					if ($row['code_iso']) {
891
+					    $out.= ' ('.$row['code_iso'] . ')';
892
+					}
763 893
 					$out.= '</option>';
764 894
 				}
765 895
 			}
766 896
 			$out.= '</select>';
767
-		}
768
-		else
897
+		} else
769 898
 		{
770 899
 			dol_print_error($this->db);
771 900
 		}
@@ -843,13 +972,14 @@  discard block
 block discarded – undo
843 972
 					if ($selected && ($selected == $row['rowid'] || $selected == $row['code']))
844 973
 					{
845 974
 						$out.= '<option value="'.$row['rowid'].'" selected>';
846
-					}
847
-					else
975
+					} else
848 976
 					{
849 977
 						$out.= '<option value="'.$row['rowid'].'">';
850 978
 					}
851 979
 
852
-					if ($row['code']) $out.= $row['code'];
980
+					if ($row['code']) {
981
+					    $out.= $row['code'];
982
+					}
853 983
 
854 984
 					$out.= '</option>';
855 985
 				}
@@ -862,8 +992,7 @@  discard block
 block discarded – undo
862 992
 			{
863 993
 				$out .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'"></form>';
864 994
 			}
865
-		}
866
-		else
995
+		} else
867 996
 		{
868 997
 			dol_print_error($this->db);
869 998
 		}
@@ -892,21 +1021,29 @@  discard block
 block discarded – undo
892 1021
 		if ($forceall == 1 || (empty($forceall) && ! empty($conf->product->enabled) && ! empty($conf->service->enabled))
893 1022
 		|| (empty($forceall) && empty($conf->product->enabled) && empty($conf->service->enabled)) )
894 1023
 		{
895
-			if (empty($hidetext)) print $langs->trans("Type").': ';
1024
+			if (empty($hidetext)) {
1025
+			    print $langs->trans("Type").': ';
1026
+			}
896 1027
 			print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
897 1028
 			if ($showempty)
898 1029
 			{
899 1030
 				print '<option value="-1"';
900
-				if ($selected == -1) print ' selected';
1031
+				if ($selected == -1) {
1032
+				    print ' selected';
1033
+				}
901 1034
 				print '>&nbsp;</option>';
902 1035
 			}
903 1036
 
904 1037
 			print '<option value="0"';
905
-			if (0 == $selected) print ' selected';
1038
+			if (0 == $selected) {
1039
+			    print ' selected';
1040
+			}
906 1041
 			print '>'.$langs->trans("Product");
907 1042
 
908 1043
 			print '<option value="1"';
909
-			if (1 == $selected) print ' selected';
1044
+			if (1 == $selected) {
1045
+			    print ' selected';
1046
+			}
910 1047
 			print '>'.$langs->trans("Service");
911 1048
 
912 1049
 			print '</select>';
@@ -922,9 +1059,12 @@  discard block
 block discarded – undo
922 1059
 			print $langs->trans("Product");
923 1060
 			print '<input type="hidden" name="'.$htmlname.'" value="0">';
924 1061
 		}
925
-		if ($forceall < 0)	// This should happened only for contracts when both predefined product and service are disabled.
1062
+		if ($forceall < 0) {
1063
+		    // This should happened only for contracts when both predefined product and service are disabled.
926 1064
 		{
927
-			print '<input type="hidden" name="'.$htmlname.'" value="1">';	// By default we set on service for contract. If CONTRACT_SUPPORT_PRODUCTS is set, forceall should be 1 not -1
1065
+			print '<input type="hidden" name="'.$htmlname.'" value="1">';
1066
+		}
1067
+		// By default we set on service for contract. If CONTRACT_SUPPORT_PRODUCTS is set, forceall should be 1 not -1
928 1068
 		}
929 1069
 	}
930 1070
 
@@ -940,7 +1080,10 @@  discard block
 block discarded – undo
940 1080
 		global $langs;
941 1081
 
942 1082
 		$num = count($this->cache_types_fees);
943
-		if ($num > 0) return 0;    // Cache already loaded
1083
+		if ($num > 0) {
1084
+		    return 0;
1085
+		}
1086
+		// Cache already loaded
944 1087
 
945 1088
 		dol_syslog(__METHOD__, LOG_DEBUG);
946 1089
 
@@ -969,8 +1112,7 @@  discard block
 block discarded – undo
969 1112
 			asort($this->cache_types_fees);
970 1113
 
971 1114
 			return $num;
972
-		}
973
-		else
1115
+		} else
974 1116
 		{
975 1117
 			dol_print_error($this->db);
976 1118
 			return -1;
@@ -999,21 +1141,27 @@  discard block
 block discarded – undo
999 1141
 		if ($showempty)
1000 1142
 		{
1001 1143
 			print '<option value="-1"';
1002
-			if ($selected == -1) print ' selected';
1144
+			if ($selected == -1) {
1145
+			    print ' selected';
1146
+			}
1003 1147
 			print '>&nbsp;</option>';
1004 1148
 		}
1005 1149
 
1006 1150
 		foreach($this->cache_types_fees as $key => $value)
1007 1151
 		{
1008 1152
 			print '<option value="'.$key.'"';
1009
-			if ($key == $selected) print ' selected';
1153
+			if ($key == $selected) {
1154
+			    print ' selected';
1155
+			}
1010 1156
 			print '>';
1011 1157
 			print $value;
1012 1158
 			print '</option>';
1013 1159
 		}
1014 1160
 
1015 1161
 		print '</select>';
1016
-		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
1162
+		if ($user->admin) {
1163
+		    print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
1164
+		}
1017 1165
 	}
1018 1166
 
1019 1167
 
@@ -1079,8 +1227,9 @@  discard block
 block discarded – undo
1079 1227
 			$urloption='htmlname='.$htmlname.'&outjson=1&filter='.$filter.($showtype?'&showtype='.$showtype:'');
1080 1228
 			$out.=  ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/societe/ajax/company.php', $urloption, $conf->global->COMPANY_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
1081 1229
 			$out.='<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
1082
-			if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
1083
-			else if ($hidelabel > 1) {
1230
+			if (empty($hidelabel)) {
1231
+			    print $langs->trans("RefOrLabel").' : ';
1232
+			} else if ($hidelabel > 1) {
1084 1233
 				$placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
1085 1234
 				if ($hidelabel == 2) {
1086 1235
 					$out.=  img_picto($langs->trans("Search"), 'search');
@@ -1090,8 +1239,7 @@  discard block
 block discarded – undo
1090 1239
 			if ($hidelabel == 3) {
1091 1240
 				$out.=  img_picto($langs->trans("Search"), 'search');
1092 1241
 			}
1093
-		}
1094
-		else
1242
+		} else
1095 1243
 		{
1096 1244
 			// Immediate load of all database
1097 1245
 			$out.=$this->select_thirdparty_list($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events, '', 0, $limit, $morecss, $moreparam, $multiple);
@@ -1129,8 +1277,11 @@  discard block
 block discarded – undo
1129 1277
 		$num=0;
1130 1278
 		$outarray=array();
1131 1279
 
1132
-		if ($selected === '') $selected = array();
1133
-		else if (!is_array($selected)) $selected = array($selected);
1280
+		if ($selected === '') {
1281
+		    $selected = array();
1282
+		} else if (!is_array($selected)) {
1283
+		    $selected = array($selected);
1284
+		}
1134 1285
 
1135 1286
 		// Clean $filter that may contains sql conditions so sql code
1136 1287
 		if (function_exists('testSqlAndScriptInject')) {
@@ -1148,16 +1299,26 @@  discard block
 block discarded – undo
1148 1299
 		}
1149 1300
 
1150 1301
 		$sql.= " FROM (".MAIN_DB_PREFIX ."societe as s";
1151
-		if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1302
+		if (!$user->rights->societe->client->voir && !$user->socid) {
1303
+		    $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
1304
+		}
1152 1305
 		$sql.= " )";
1153 1306
 		if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
1154 1307
 			$sql.= " LEFT OUTER JOIN ".MAIN_DB_PREFIX."c_country as dictp ON dictp.rowid=s.fk_pays";
1155 1308
 		}
1156 1309
 		$sql.= " WHERE s.entity IN (".getEntity('societe').")";
1157
-		if (! empty($user->socid)) $sql.= " AND s.rowid = ".$user->socid;
1158
-		if ($filter) $sql.= " AND (".$filter.")";
1159
-		if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
1160
-		if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND s.status <> 0";
1310
+		if (! empty($user->socid)) {
1311
+		    $sql.= " AND s.rowid = ".$user->socid;
1312
+		}
1313
+		if ($filter) {
1314
+		    $sql.= " AND (".$filter.")";
1315
+		}
1316
+		if (!$user->rights->societe->client->voir && !$user->socid) {
1317
+		    $sql.= " AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
1318
+		}
1319
+		if (! empty($conf->global->COMPANY_HIDE_INACTIVE_IN_COMBOBOX)) {
1320
+		    $sql.= " AND s.status <> 0";
1321
+		}
1161 1322
 		// Add criteria
1162 1323
 		if ($filterkey && $filterkey != '')
1163 1324
 		{
@@ -1166,13 +1327,19 @@  discard block
 block discarded – undo
1166 1327
 			// For natural search
1167 1328
 			$scrit = explode(' ', $filterkey);
1168 1329
 			$i=0;
1169
-			if (count($scrit) > 1) $sql.="(";
1330
+			if (count($scrit) > 1) {
1331
+			    $sql.="(";
1332
+			}
1170 1333
 			foreach ($scrit as $crit) {
1171
-				if ($i > 0) $sql.=" AND ";
1334
+				if ($i > 0) {
1335
+				    $sql.=" AND ";
1336
+				}
1172 1337
 				$sql.="(s.nom LIKE '".$this->db->escape($prefix.$crit)."%')";
1173 1338
 				$i++;
1174 1339
 			}
1175
-			if (count($scrit) > 1) $sql.=")";
1340
+			if (count($scrit) > 1) {
1341
+			    $sql.=")";
1342
+			}
1176 1343
 			if (! empty($conf->barcode->enabled))
1177 1344
 			{
1178 1345
 				$sql .= " OR s.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
@@ -1202,10 +1369,15 @@  discard block
 block discarded – undo
1202 1369
 			//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
1203 1370
 			if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
1204 1371
 			{
1205
-				if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
1206
-				else $textifempty.=$langs->trans("All");
1372
+				if ($showempty && ! is_numeric($showempty)) {
1373
+				    $textifempty=$langs->trans($showempty);
1374
+				} else {
1375
+				    $textifempty.=$langs->trans("All");
1376
+				}
1377
+			}
1378
+			if ($showempty) {
1379
+			    $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
1207 1380
 			}
1208
-			if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
1209 1381
 
1210 1382
 			$num = $this->db->num_rows($resql);
1211 1383
 			$i = 0;
@@ -1223,8 +1395,7 @@  discard block
 block discarded – undo
1223 1395
 							$label .= $obj->code_fournisseur. ' - ';
1224 1396
 						}
1225 1397
 						$label.=' '.$obj->name;
1226
-					}
1227
-					else
1398
+					} else
1228 1399
 					{
1229 1400
 						$label=$obj->name;
1230 1401
 					}
@@ -1235,11 +1406,21 @@  discard block
 block discarded – undo
1235 1406
 
1236 1407
 					if ($showtype)
1237 1408
 					{
1238
-						if ($obj->client || $obj->fournisseur) $label.=' (';
1239
-						if ($obj->client == 1 || $obj->client == 3) $label.=$langs->trans("Customer");
1240
-						if ($obj->client == 2 || $obj->client == 3) $label.=($obj->client==3?', ':'').$langs->trans("Prospect");
1241
-						if ($obj->fournisseur) $label.=($obj->client?', ':'').$langs->trans("Supplier");
1242
-						if ($obj->client || $obj->fournisseur) $label.=')';
1409
+						if ($obj->client || $obj->fournisseur) {
1410
+						    $label.=' (';
1411
+						}
1412
+						if ($obj->client == 1 || $obj->client == 3) {
1413
+						    $label.=$langs->trans("Customer");
1414
+						}
1415
+						if ($obj->client == 2 || $obj->client == 3) {
1416
+						    $label.=($obj->client==3?', ':'').$langs->trans("Prospect");
1417
+						}
1418
+						if ($obj->fournisseur) {
1419
+						    $label.=($obj->client?', ':'').$langs->trans("Supplier");
1420
+						}
1421
+						if ($obj->client || $obj->fournisseur) {
1422
+						    $label.=')';
1423
+						}
1243 1424
 					}
1244 1425
 
1245 1426
 					if ($conf->global->COMPANY_SHOW_ADDRESS_SELECTLIST) {
@@ -1254,31 +1435,32 @@  discard block
 block discarded – undo
1254 1435
 						if (in_array($obj->rowid,$selected))
1255 1436
 						{
1256 1437
 							$out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
1257
-						}
1258
-						else
1438
+						} else
1259 1439
 						{
1260 1440
 							$out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
1261 1441
 						}
1262
-					}
1263
-					else
1442
+					} else
1264 1443
 					{
1265 1444
 						array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
1266 1445
 					}
1267 1446
 
1268 1447
 					$i++;
1269
-					if (($i % 10) == 0) $out.="\n";
1448
+					if (($i % 10) == 0) {
1449
+					    $out.="\n";
1450
+					}
1270 1451
 				}
1271 1452
 			}
1272 1453
 			$out.= '</select>'."\n";
1273
-		}
1274
-		else
1454
+		} else
1275 1455
 		{
1276 1456
 			dol_print_error($this->db);
1277 1457
 		}
1278 1458
 
1279 1459
 		$this->result=array('nbofthirdparties'=>$num);
1280 1460
 
1281
-		if ($outputmode) return $outarray;
1461
+		if ($outputmode) {
1462
+		    return $outarray;
1463
+		}
1282 1464
 		return $out;
1283 1465
 	}
1284 1466
 
@@ -1305,7 +1487,9 @@  discard block
 block discarded – undo
1305 1487
 		$sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
1306 1488
 		$sql.= " WHERE re.fk_soc = ".(int) $socid;
1307 1489
 		$sql.= " AND re.entity = " . $conf->entity;
1308
-		if ($filter) $sql.= " AND ".$filter;
1490
+		if ($filter) {
1491
+		    $sql.= " AND ".$filter;
1492
+		}
1309 1493
 		$sql.= " ORDER BY re.description ASC";
1310 1494
 
1311 1495
 		dol_syslog(get_class($this)."::select_remises", LOG_DEBUG);
@@ -1325,13 +1509,23 @@  discard block
 block discarded – undo
1325 1509
 				{
1326 1510
 					$obj = $this->db->fetch_object($resql);
1327 1511
 					$desc=dol_trunc($obj->description,40);
1328
-					if (preg_match('/\(CREDIT_NOTE\)/', $desc)) $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
1329
-					if (preg_match('/\(DEPOSIT\)/', $desc)) $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
1330
-					if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
1331
-					if (preg_match('/\(EXCESS PAID\)/', $desc)) $desc=preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
1512
+					if (preg_match('/\(CREDIT_NOTE\)/', $desc)) {
1513
+					    $desc=preg_replace('/\(CREDIT_NOTE\)/', $langs->trans("CreditNote"), $desc);
1514
+					}
1515
+					if (preg_match('/\(DEPOSIT\)/', $desc)) {
1516
+					    $desc=preg_replace('/\(DEPOSIT\)/', $langs->trans("Deposit"), $desc);
1517
+					}
1518
+					if (preg_match('/\(EXCESS RECEIVED\)/', $desc)) {
1519
+					    $desc=preg_replace('/\(EXCESS RECEIVED\)/', $langs->trans("ExcessReceived"), $desc);
1520
+					}
1521
+					if (preg_match('/\(EXCESS PAID\)/', $desc)) {
1522
+					    $desc=preg_replace('/\(EXCESS PAID\)/', $langs->trans("ExcessPaid"), $desc);
1523
+					}
1332 1524
 
1333 1525
 					$selectstring='';
1334
-					if ($selected > 0 && $selected == $obj->rowid) $selectstring=' selected';
1526
+					if ($selected > 0 && $selected == $obj->rowid) {
1527
+					    $selectstring=' selected';
1528
+					}
1335 1529
 
1336 1530
 					$disabled='';
1337 1531
 					if ($maxvalue > 0 && $obj->amount_ttc > $maxvalue)
@@ -1343,7 +1537,9 @@  discard block
 block discarded – undo
1343 1537
 					if (!empty($conf->global->MAIN_SHOW_FACNUMBER_IN_DISCOUNT_LIST) && !empty($obj->fk_facture_source))
1344 1538
 					{
1345 1539
 						$tmpfac = new Facture($this->db);
1346
-						if ($tmpfac->fetch($obj->fk_facture_source) > 0) $desc=$desc.' - '.$tmpfac->ref;
1540
+						if ($tmpfac->fetch($obj->fk_facture_source) > 0) {
1541
+						    $desc=$desc.' - '.$tmpfac->ref;
1542
+						}
1347 1543
 					}
1348 1544
 
1349 1545
 					print '<option value="'.$obj->rowid.'"'.$selectstring.$disabled.'>'.$desc.' ('.price($obj->amount_ht).' '.$langs->trans("HT").' - '.price($obj->amount_ttc).' '.$langs->trans("TTC").')</option>';
@@ -1352,8 +1548,7 @@  discard block
 block discarded – undo
1352 1548
 			}
1353 1549
 			print '</select>';
1354 1550
 			return $qualifiedlines;
1355
-		}
1356
-		else
1551
+		} else
1357 1552
 		{
1358 1553
 			dol_print_error($this->db);
1359 1554
 			return -1;
@@ -1417,10 +1612,15 @@  discard block
 block discarded – undo
1417 1612
 
1418 1613
 		$langs->load('companies');
1419 1614
 
1420
-		if (empty($htmlid)) $htmlid = $htmlname;
1615
+		if (empty($htmlid)) {
1616
+		    $htmlid = $htmlname;
1617
+		}
1421 1618
 
1422
-		if ($selected === '') $selected = array();
1423
-		else if (!is_array($selected)) $selected = array($selected);
1619
+		if ($selected === '') {
1620
+		    $selected = array();
1621
+		} else if (!is_array($selected)) {
1622
+		    $selected = array($selected);
1623
+		}
1424 1624
 		$out='';
1425 1625
 
1426 1626
 		if (! is_object($hookmanager))
@@ -1431,12 +1631,20 @@  discard block
 block discarded – undo
1431 1631
 
1432 1632
 		// We search third parties
1433 1633
 		$sql = "SELECT sp.rowid, sp.lastname, sp.statut, sp.firstname, sp.poste";
1434
-		if ($showsoc > 0) $sql.= " , s.nom as company";
1634
+		if ($showsoc > 0) {
1635
+		    $sql.= " , s.nom as company";
1636
+		}
1435 1637
 		$sql.= " FROM ".MAIN_DB_PREFIX ."socpeople as sp";
1436
-		if ($showsoc > 0) $sql.= " LEFT OUTER JOIN  ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc";
1638
+		if ($showsoc > 0) {
1639
+		    $sql.= " LEFT OUTER JOIN  ".MAIN_DB_PREFIX ."societe as s ON s.rowid=sp.fk_soc";
1640
+		}
1437 1641
 		$sql.= " WHERE sp.entity IN (".getEntity('socpeople').")";
1438
-		if ($socid > 0 || $socid == -1) $sql.= " AND sp.fk_soc=".$socid;
1439
-		if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) $sql.= " AND sp.statut <> 0";
1642
+		if ($socid > 0 || $socid == -1) {
1643
+		    $sql.= " AND sp.fk_soc=".$socid;
1644
+		}
1645
+		if (! empty($conf->global->CONTACT_HIDE_INACTIVE_IN_COMBOBOX)) {
1646
+		    $sql.= " AND sp.statut <> 0";
1647
+		}
1440 1648
 		$sql.= " ORDER BY sp.lastname ASC";
1441 1649
 
1442 1650
 		dol_syslog(get_class($this)."::select_contacts", LOG_DEBUG);
@@ -1451,9 +1659,15 @@  discard block
 block discarded – undo
1451 1659
 				$out .= ajax_combobox($htmlid, $events, $conf->global->CONTACT_USE_SEARCH_TO_SELECT);
1452 1660
 			}
1453 1661
 
1454
-			if ($htmlname != 'none' || $options_only) $out.= '<select class="flat'.($moreclass?' '.$moreclass:'').'" id="'.$htmlid.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
1455
-			if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>&nbsp;</option>';
1456
-			if ($showempty == 2) $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>'.$langs->trans("Internal").'</option>';
1662
+			if ($htmlname != 'none' || $options_only) {
1663
+			    $out.= '<select class="flat'.($moreclass?' '.$moreclass:'').'" id="'.$htmlid.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.(!empty($moreparam) ? $moreparam : '').'>';
1664
+			}
1665
+			if (($showempty == 1 || ($showempty == 3 && $num > 1)) && !$multiple) {
1666
+			    $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>&nbsp;</option>';
1667
+			}
1668
+			if ($showempty == 2) {
1669
+			    $out.= '<option value="0"'.(in_array(0,$selected)?' selected':'').'>'.$langs->trans("Internal").'</option>';
1670
+			}
1457 1671
 			$num = $this->db->num_rows($resql);
1458 1672
 			$i = 0;
1459 1673
 			if ($num)
@@ -1472,43 +1686,60 @@  discard block
 block discarded – undo
1472 1686
 					if ($htmlname != 'none')
1473 1687
 					{
1474 1688
 						$disabled=0;
1475
-						if (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) $disabled=1;
1476
-						if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) $disabled=1;
1689
+						if (is_array($exclude) && count($exclude) && in_array($obj->rowid,$exclude)) {
1690
+						    $disabled=1;
1691
+						}
1692
+						if (is_array($limitto) && count($limitto) && ! in_array($obj->rowid,$limitto)) {
1693
+						    $disabled=1;
1694
+						}
1477 1695
 						if (!empty($selected) && in_array($obj->rowid, $selected))
1478 1696
 						{
1479 1697
 							$out.= '<option value="'.$obj->rowid.'"';
1480
-							if ($disabled) $out.= ' disabled';
1698
+							if ($disabled) {
1699
+							    $out.= ' disabled';
1700
+							}
1481 1701
 							$out.= ' selected>';
1482 1702
 							$out.= $contactstatic->getFullName($langs);
1483
-							if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1484
-							if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1703
+							if ($showfunction && $obj->poste) {
1704
+							    $out.= ' ('.$obj->poste.')';
1705
+							}
1706
+							if (($showsoc > 0) && $obj->company) {
1707
+							    $out.= ' - ('.$obj->company.')';
1708
+							}
1485 1709
 							$out.= '</option>';
1486
-						}
1487
-						else
1710
+						} else
1488 1711
 						{
1489 1712
 							$out.= '<option value="'.$obj->rowid.'"';
1490
-							if ($disabled) $out.= ' disabled';
1713
+							if ($disabled) {
1714
+							    $out.= ' disabled';
1715
+							}
1491 1716
 							$out.= '>';
1492 1717
 							$out.= $contactstatic->getFullName($langs);
1493
-							if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1494
-							if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1718
+							if ($showfunction && $obj->poste) {
1719
+							    $out.= ' ('.$obj->poste.')';
1720
+							}
1721
+							if (($showsoc > 0) && $obj->company) {
1722
+							    $out.= ' - ('.$obj->company.')';
1723
+							}
1495 1724
 							$out.= '</option>';
1496 1725
 						}
1497
-					}
1498
-					else
1726
+					} else
1499 1727
 					{
1500 1728
 						if (in_array($obj->rowid, $selected))
1501 1729
 						{
1502 1730
 							$out.= $contactstatic->getFullName($langs);
1503
-							if ($showfunction && $obj->poste) $out.= ' ('.$obj->poste.')';
1504
-							if (($showsoc > 0) && $obj->company) $out.= ' - ('.$obj->company.')';
1731
+							if ($showfunction && $obj->poste) {
1732
+							    $out.= ' ('.$obj->poste.')';
1733
+							}
1734
+							if (($showsoc > 0) && $obj->company) {
1735
+							    $out.= ' - ('.$obj->company.')';
1736
+							}
1505 1737
 						}
1506 1738
 					}
1507 1739
 				}
1508 1740
 					$i++;
1509 1741
 				}
1510
-			}
1511
-			else
1742
+			} else
1512 1743
 			{
1513 1744
 				$out.= '<option value="-1"'.(($showempty==2 || $multiple) ? '' : ' selected').' disabled>';
1514 1745
 				$out.= ($socid != -1) ? ($langs->trans($socid?"NoContactDefinedForThirdParty":"NoContactDefined")) : $langs->trans('SelectAThirdPartyFirst');
@@ -1533,8 +1764,7 @@  discard block
 block discarded – undo
1533 1764
 
1534 1765
 			$this->num = $num;
1535 1766
 			return $out;
1536
-		}
1537
-		else
1767
+		} else
1538 1768
 		{
1539 1769
 			dol_print_error($this->db);
1540 1770
 			return -1;
@@ -1593,24 +1823,31 @@  discard block
 block discarded – undo
1593 1823
 		global $conf,$user,$langs;
1594 1824
 
1595 1825
 		// If no preselected user defined, we take current user
1596
-		if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) $selected=$user->id;
1826
+		if ((is_numeric($selected) && ($selected < -2 || empty($selected))) && empty($conf->global->SOCIETE_DISABLE_DEFAULT_SALESREPRESENTATIVE)) {
1827
+		    $selected=$user->id;
1828
+		}
1597 1829
 
1598
-		if ($selected === '') $selected = array();
1599
-		else if (!is_array($selected)) $selected = array($selected);
1830
+		if ($selected === '') {
1831
+		    $selected = array();
1832
+		} else if (!is_array($selected)) {
1833
+		    $selected = array($selected);
1834
+		}
1600 1835
 
1601 1836
 		$excludeUsers=null;
1602 1837
 		$includeUsers=null;
1603 1838
 
1604 1839
 		// Permettre l'exclusion d'utilisateurs
1605
-		if (is_array($exclude))	$excludeUsers = implode(",",$exclude);
1840
+		if (is_array($exclude)) {
1841
+		    $excludeUsers = implode(",",$exclude);
1842
+		}
1606 1843
 		// Permettre l'inclusion d'utilisateurs
1607
-		if (is_array($include))	$includeUsers = implode(",",$include);
1608
-		else if ($include == 'hierarchy')
1844
+		if (is_array($include)) {
1845
+		    $includeUsers = implode(",",$include);
1846
+		} else if ($include == 'hierarchy')
1609 1847
 		{
1610 1848
 			// Build list includeUsers to have only hierarchy
1611 1849
 			$includeUsers = implode(",",$user->getAllChildIds(0));
1612
-		}
1613
-		else if ($include == 'hierarchyme')
1850
+		} else if ($include == 'hierarchyme')
1614 1851
 		{
1615 1852
 			// Build list includeUsers to have only hierarchy and current user
1616 1853
 			$includeUsers = implode(",",$user->getAllChildIds(1));
@@ -1629,33 +1866,45 @@  discard block
 block discarded – undo
1629 1866
 		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
1630 1867
 		{
1631 1868
 			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX ."entity as e ON e.rowid=u.entity";
1632
-			if ($force_entity) $sql.= " WHERE u.entity IN (0,".$force_entity.")";
1633
-			else $sql.= " WHERE u.entity IS NOT NULL";
1634
-		}
1635
-		else
1869
+			if ($force_entity) {
1870
+			    $sql.= " WHERE u.entity IN (0,".$force_entity.")";
1871
+			} else {
1872
+			    $sql.= " WHERE u.entity IS NOT NULL";
1873
+			}
1874
+		} else
1636 1875
 		{
1637 1876
 			if (! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE))
1638 1877
 			{
1639 1878
 				$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ug";
1640 1879
 				$sql.= " ON ug.fk_user = u.rowid";
1641 1880
 				$sql.= " WHERE ug.entity = ".$conf->entity;
1642
-			}
1643
-			else
1881
+			} else
1644 1882
 			{
1645 1883
 				$sql.= " WHERE u.entity IN (0,".$conf->entity.")";
1646 1884
 			}
1647 1885
 		}
1648
-		if (! empty($user->societe_id)) $sql.= " AND u.fk_soc = ".$user->societe_id;
1649
-		if (is_array($exclude) && $excludeUsers) $sql.= " AND u.rowid NOT IN (".$excludeUsers.")";
1650
-		if ($includeUsers) $sql.= " AND u.rowid IN (".$includeUsers.")";
1651
-		if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) $sql.= " AND u.statut <> 0";
1652
-		if (! empty($morefilter)) $sql.=" ".$morefilter;
1886
+		if (! empty($user->societe_id)) {
1887
+		    $sql.= " AND u.fk_soc = ".$user->societe_id;
1888
+		}
1889
+		if (is_array($exclude) && $excludeUsers) {
1890
+		    $sql.= " AND u.rowid NOT IN (".$excludeUsers.")";
1891
+		}
1892
+		if ($includeUsers) {
1893
+		    $sql.= " AND u.rowid IN (".$includeUsers.")";
1894
+		}
1895
+		if (! empty($conf->global->USER_HIDE_INACTIVE_IN_COMBOBOX) || $noactive) {
1896
+		    $sql.= " AND u.statut <> 0";
1897
+		}
1898
+		if (! empty($morefilter)) {
1899
+		    $sql.=" ".$morefilter;
1900
+		}
1653 1901
 
1654
-		if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION))	// MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
1902
+		if (empty($conf->global->MAIN_FIRSTNAME_NAME_POSITION)) {
1903
+		    // MAIN_FIRSTNAME_NAME_POSITION is 0 means firstname+lastname
1655 1904
 		{
1656 1905
 			$sql.= " ORDER BY u.firstname ASC";
1657 1906
 		}
1658
-		else
1907
+		} else
1659 1908
 		{
1660 1909
 			$sql.= " ORDER BY u.lastname ASC";
1661 1910
 		}
@@ -1674,8 +1923,12 @@  discard block
 block discarded – undo
1674 1923
 
1675 1924
 				// do not use maxwidthonsmartphone by default. Set it by caller so auto size to 100% will work when not defined
1676 1925
 				$out.= '<select class="flat'.($morecss?' minwidth100 '.$morecss:' minwidth200').'" id="'.$htmlname.'" name="'.$htmlname.($multiple ? '[]' : '').'" '.($multiple ? 'multiple' : '').' '.($disabled?' disabled':'').'>';
1677
-				if ($show_empty && !$multiple) $out.= '<option value="-1"'.((empty($selected) || in_array(-1,$selected))?' selected':'').'>&nbsp;</option>'."\n";
1678
-				if ($show_every) $out.= '<option value="-2"'.((in_array(-2,$selected))?' selected':'').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
1926
+				if ($show_empty && !$multiple) {
1927
+				    $out.= '<option value="-1"'.((empty($selected) || in_array(-1,$selected))?' selected':'').'>&nbsp;</option>'."\n";
1928
+				}
1929
+				if ($show_every) {
1930
+				    $out.= '<option value="-2"'.((in_array(-2,$selected))?' selected':'').'>-- '.$langs->trans("Everybody").' --</option>'."\n";
1931
+				}
1679 1932
 
1680 1933
 				$userstatic=new User($this->db);
1681 1934
 
@@ -1688,18 +1941,23 @@  discard block
 block discarded – undo
1688 1941
 					$userstatic->firstname=$obj->firstname;
1689 1942
 
1690 1943
 					$disableline='';
1691
-					if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=($enableonlytext?$enableonlytext:'1');
1944
+					if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) {
1945
+					    $disableline=($enableonlytext?$enableonlytext:'1');
1946
+					}
1692 1947
 
1693 1948
 					if ((is_object($selected) && $selected->id == $obj->rowid) || (! is_object($selected) && in_array($obj->rowid,$selected) ))
1694 1949
 					{
1695 1950
 						$out.= '<option value="'.$obj->rowid.'"';
1696
-						if ($disableline) $out.= ' disabled';
1951
+						if ($disableline) {
1952
+						    $out.= ' disabled';
1953
+						}
1697 1954
 						$out.= ' selected>';
1698
-					}
1699
-					else
1955
+					} else
1700 1956
 					{
1701 1957
 						$out.= '<option value="'.$obj->rowid.'"';
1702
-						if ($disableline) $out.= ' disabled';
1958
+						if ($disableline) {
1959
+						    $out.= ' disabled';
1960
+						}
1703 1961
 						$out.= '>';
1704 1962
 					}
1705 1963
 
@@ -1737,8 +1995,7 @@  discard block
 block discarded – undo
1737 1995
 						{
1738 1996
 							$out.=($moreinfo?' - ':' (').$langs->trans("AllEntities");
1739 1997
 							$moreinfo++;
1740
-						}
1741
-						else
1998
+						} else
1742 1999
 						{
1743 2000
 							$out.=($moreinfo?' - ':' (').($obj->label?$obj->label:$langs->trans("EntityNameNotDefined"));
1744 2001
 							$moreinfo++;
@@ -1754,20 +2011,20 @@  discard block
 block discarded – undo
1754 2011
 
1755 2012
 					$i++;
1756 2013
 				}
1757
-			}
1758
-			else
2014
+			} else
1759 2015
 			{
1760 2016
 				$out.= '<select class="flat" id="'.$htmlname.'" name="'.$htmlname.'" disabled>';
1761 2017
 				$out.= '<option value="">'.$langs->trans("None").'</option>';
1762 2018
 			}
1763 2019
 			$out.= '</select>';
1764
-		}
1765
-		else
2020
+		} else
1766 2021
 		{
1767 2022
 			dol_print_error($this->db);
1768 2023
 		}
1769 2024
 
1770
-		if ($outputmode) return $outarray;
2025
+		if ($outputmode) {
2026
+		    return $outarray;
2027
+		}
1771 2028
 		return $out;
1772 2029
 	}
1773 2030
 
@@ -1808,8 +2065,7 @@  discard block
 block discarded – undo
1808 2065
 		if ($action == 'view')
1809 2066
 		{
1810 2067
 			$out.='';
1811
-		}
1812
-		else
2068
+		} else
1813 2069
 		{
1814 2070
 			$out.='<input type="hidden" class="removedassignedhidden" name="removedassigned" value="">';
1815 2071
 			$out.='<script type="text/javascript" language="javascript">jQuery(document).ready(function () {    jQuery(".removedassigned").click(function() {        jQuery(".removedassignedhidden").val(jQuery(this).val());    });})</script>';
@@ -1824,12 +2080,18 @@  discard block
 block discarded – undo
1824 2080
 		}
1825 2081
 		$nbassignetouser=count($assignedtouser);
1826 2082
 
1827
-		if ($nbassignetouser && $action != 'view') $out.='<br>';
1828
-		if ($nbassignetouser) $out.='<ul class="attendees">';
2083
+		if ($nbassignetouser && $action != 'view') {
2084
+		    $out.='<br>';
2085
+		}
2086
+		if ($nbassignetouser) {
2087
+		    $out.='<ul class="attendees">';
2088
+		}
1829 2089
 		$i=0; $ownerid=0;
1830 2090
 		foreach($assignedtouser as $key => $value)
1831 2091
 		{
1832
-			if ($value['id'] == $ownerid) continue;
2092
+			if ($value['id'] == $ownerid) {
2093
+			    continue;
2094
+			}
1833 2095
 
1834 2096
 			$out.='<li>';
1835 2097
 			$userstatic->fetch($value['id']);
@@ -1855,7 +2117,9 @@  discard block
 block discarded – undo
1855 2117
 			$out.='</li>';
1856 2118
 			$i++;
1857 2119
 		}
1858
-		if ($nbassignetouser) $out.='</ul>';
2120
+		if ($nbassignetouser) {
2121
+		    $out.='</ul>';
2122
+		}
1859 2123
 
1860 2124
 		//$out.='</form>';
1861 2125
 		return $out;
@@ -1988,8 +2252,9 @@  discard block
 block discarded – undo
1988 2252
 				</script>
1989 2253
                 <?php
1990 2254
 			}
1991
-			if (empty($hidelabel)) print $langs->trans("RefOrLabel").' : ';
1992
-			else if ($hidelabel > 1) {
2255
+			if (empty($hidelabel)) {
2256
+			    print $langs->trans("RefOrLabel").' : ';
2257
+			} else if ($hidelabel > 1) {
1993 2258
 				$placeholder=' placeholder="'.$langs->trans("RefOrLabel").'"';
1994 2259
 				if ($hidelabel == 2) {
1995 2260
 					print img_picto($langs->trans("Search"), 'search');
@@ -1999,8 +2264,7 @@  discard block
 block discarded – undo
1999 2264
 			if ($hidelabel == 3) {
2000 2265
 				print img_picto($langs->trans("Search"), 'search');
2001 2266
 			}
2002
-		}
2003
-		else
2267
+		} else
2004 2268
 		{
2005 2269
 			print $this->select_produits_list($selected,$htmlname,$filtertype,$limit,$price_level,'',$status,$finished,0,$socid,$showempty,$forcecombo,$morecss,$hidepriceinlabel, $warehouseStatus);
2006 2270
 		}
@@ -2090,11 +2354,15 @@  discard block
 block discarded – undo
2090 2354
 		if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES))
2091 2355
 		{
2092 2356
 			$sql.= ", (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";
2093
-			if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
2357
+			if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
2358
+			    $sql.= " AND price_level=".$price_level;
2359
+			}
2094 2360
 			$sql.= " ORDER BY date_price";
2095 2361
 			$sql.= " DESC LIMIT 1) as price_rowid";
2096 2362
 			$sql.= ", (SELECT pp.price_by_qty FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = p.rowid";	// price_by_qty is 1 if some prices by qty exists in subtable
2097
-			if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) $sql.= " AND price_level=".$price_level;
2363
+			if ($price_level >= 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
2364
+			    $sql.= " AND price_level=".$price_level;
2365
+			}
2098 2366
 			$sql.= " ORDER BY date_price";
2099 2367
 			$sql.= " DESC LIMIT 1) as price_by_qty";
2100 2368
 			$selectFields.= ", price_rowid, price_by_qty";
@@ -2139,17 +2407,19 @@  discard block
 block discarded – undo
2139 2407
 		if ($finished == 0)
2140 2408
 		{
2141 2409
 			$sql.= " AND p.finished = ".$finished;
2142
-		}
2143
-		elseif ($finished == 1)
2410
+		} elseif ($finished == 1)
2144 2411
 		{
2145 2412
 			$sql.= " AND p.finished = ".$finished;
2146
-			if ($status >= 0)  $sql.= " AND p.tosell = ".$status;
2147
-		}
2148
-		elseif ($status >= 0)
2413
+			if ($status >= 0) {
2414
+			    $sql.= " AND p.tosell = ".$status;
2415
+			}
2416
+		} elseif ($status >= 0)
2149 2417
 		{
2150 2418
 			$sql.= " AND p.tosell = ".$status;
2151 2419
 		}
2152
-		if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$filtertype;
2420
+		if (strval($filtertype) != '') {
2421
+		    $sql.=" AND p.fk_product_type=".$filtertype;
2422
+		}
2153 2423
 		// Add criteria on ref/label
2154 2424
 		if ($filterkey != '')
2155 2425
 		{
@@ -2158,23 +2428,37 @@  discard block
 block discarded – undo
2158 2428
 			// For natural search
2159 2429
 			$scrit = explode(' ', $filterkey);
2160 2430
 			$i=0;
2161
-			if (count($scrit) > 1) $sql.="(";
2431
+			if (count($scrit) > 1) {
2432
+			    $sql.="(";
2433
+			}
2162 2434
 			foreach ($scrit as $crit)
2163 2435
 			{
2164
-				if ($i > 0) $sql.=" AND ";
2436
+				if ($i > 0) {
2437
+				    $sql.=" AND ";
2438
+				}
2165 2439
 				$sql.="(p.ref LIKE '".$db->escape($prefix.$crit)."%' OR p.label LIKE '".$db->escape($prefix.$crit)."%'";
2166
-				if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
2440
+				if (! empty($conf->global->MAIN_MULTILANGS)) {
2441
+				    $sql.=" OR pl.label LIKE '".$db->escape($prefix.$crit)."%'";
2442
+				}
2167 2443
 				if (!empty($conf->global->PRODUCT_AJAX_SEARCH_ON_DESCRIPTION))
2168 2444
 				{
2169 2445
 					$sql.=" OR p.description LIKE '".$db->escape($prefix.$crit)."%'";
2170
-					if (! empty($conf->global->MAIN_MULTILANGS)) $sql.=" OR pl.description LIKE '".$db->escape($prefix.$crit)."%'";
2446
+					if (! empty($conf->global->MAIN_MULTILANGS)) {
2447
+					    $sql.=" OR pl.description LIKE '".$db->escape($prefix.$crit)."%'";
2448
+					}
2449
+				}
2450
+				if (! empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) {
2451
+				    $sql.=" OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'";
2171 2452
 				}
2172
-				if (! empty($conf->global->MAIN_SEARCH_PRODUCT_BY_FOURN_REF)) $sql.=" OR pfp.ref_fourn LIKE '".$db->escape($prefix.$crit)."%'";
2173 2453
 				$sql.=")";
2174 2454
 				$i++;
2175 2455
 			}
2176
-			if (count($scrit) > 1) $sql.=")";
2177
-		  	if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
2456
+			if (count($scrit) > 1) {
2457
+			    $sql.=")";
2458
+			}
2459
+		  	if (! empty($conf->barcode->enabled)) {
2460
+		  	    $sql.= " OR p.barcode LIKE '".$db->escape($prefix.$filterkey)."%'";
2461
+		  	}
2178 2462
 			$sql.=')';
2179 2463
 		}
2180 2464
 		if (count($warehouseStatusArray))
@@ -2188,8 +2472,7 @@  discard block
 block discarded – undo
2188 2472
 			$sql .= " ORDER BY categorie_product_id ";
2189 2473
 			//ASC OR DESC order
2190 2474
 			($conf->global->PRODUCT_SORT_BY_CATEGORY == 1) ? $sql .="ASC" : $sql .="DESC";
2191
-		}
2192
-		else
2475
+		} else
2193 2476
 		{
2194 2477
 			$sql.= $db->order("p.ref");
2195 2478
 		}
@@ -2220,10 +2503,15 @@  discard block
 block discarded – undo
2220 2503
 			//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
2221 2504
 			if (! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
2222 2505
 			{
2223
-				if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
2224
-				else $textifempty.=$langs->trans("All");
2506
+				if ($showempty && ! is_numeric($showempty)) {
2507
+				    $textifempty=$langs->trans($showempty);
2508
+				} else {
2509
+				    $textifempty.=$langs->trans("All");
2510
+				}
2511
+			}
2512
+			if ($showempty) {
2513
+			    $out.='<option value="0" selected>'.$textifempty.'</option>';
2225 2514
 			}
2226
-			if ($showempty) $out.='<option value="0" selected>'.$textifempty.'</option>';
2227 2515
 
2228 2516
 			$i = 0;
2229 2517
 			while ($num && $i < $num)
@@ -2271,8 +2559,7 @@  discard block
 block discarded – undo
2271 2559
 							array_push($outarray, $optJson);
2272 2560
 						}
2273 2561
 					}
2274
-				}
2275
-				else
2562
+				} else
2276 2563
 				{
2277 2564
 					if (!empty($conf->dynamicprices->enabled) && !empty($objp->fk_price_expression)) {
2278 2565
 						$price_product = new Product($this->db);
@@ -2302,10 +2589,11 @@  discard block
 block discarded – undo
2302 2589
 
2303 2590
 			$this->db->free($result);
2304 2591
 
2305
-			if (empty($outputmode)) return $out;
2592
+			if (empty($outputmode)) {
2593
+			    return $out;
2594
+			}
2306 2595
 			return $outarray;
2307
-		}
2308
-		else
2596
+		} else
2309 2597
 		{
2310 2598
 			dol_print_error($db);
2311 2599
 		}
@@ -2343,8 +2631,12 @@  discard block
 block discarded – undo
2343 2631
 		$maxlengtharticle=(empty($conf->global->PRODUCT_MAX_LENGTH_COMBO)?48:$conf->global->PRODUCT_MAX_LENGTH_COMBO);
2344 2632
 
2345 2633
 		$label=$objp->label;
2346
-		if (! empty($objp->label_translated)) $label=$objp->label_translated;
2347
-		if (! empty($filterkey) && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
2634
+		if (! empty($objp->label_translated)) {
2635
+		    $label=$objp->label_translated;
2636
+		}
2637
+		if (! empty($filterkey) && $filterkey != '') {
2638
+		    $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
2639
+		}
2348 2640
 
2349 2641
 		$outkey=$objp->rowid;
2350 2642
 		$outref=$objp->ref;
@@ -2364,18 +2656,27 @@  discard block
 block discarded – undo
2364 2656
 		}
2365 2657
 		if (! empty($conf->stock->enabled) && $objp->fk_product_type == 0 && isset($objp->stock))
2366 2658
 		{
2367
-			if ($objp->stock > 0) $opt.= ' class="product_line_stock_ok"';
2368
-			else if ($objp->stock <= 0) $opt.= ' class="product_line_stock_too_low"';
2659
+			if ($objp->stock > 0) {
2660
+			    $opt.= ' class="product_line_stock_ok"';
2661
+			} else if ($objp->stock <= 0) {
2662
+			    $opt.= ' class="product_line_stock_too_low"';
2663
+			}
2369 2664
 		}
2370 2665
 		$opt.= '>';
2371 2666
 		$opt.= $objp->ref;
2372
-		if ($outbarcode) $opt.=' ('.$outbarcode.')';
2667
+		if ($outbarcode) {
2668
+		    $opt.=' ('.$outbarcode.')';
2669
+		}
2373 2670
 		$opt.=' - '.dol_trunc($label,$maxlengtharticle);
2374 2671
 
2375 2672
 		$objRef = $objp->ref;
2376
-		if (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2673
+		if (! empty($filterkey) && $filterkey != '') {
2674
+		    $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2675
+		}
2377 2676
 		$outval.=$objRef;
2378
-		if ($outbarcode) $outval.=' ('.$outbarcode.')';
2677
+		if ($outbarcode) {
2678
+		    $outval.=' ('.$outbarcode.')';
2679
+		}
2379 2680
 		$outval.=' - '.dol_trunc($label,$maxlengtharticle);
2380 2681
 
2381 2682
 		$found=0;
@@ -2404,8 +2705,7 @@  discard block
 block discarded – undo
2404 2705
 					{
2405 2706
 						$opt.= ' - '.price($objp2->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2406 2707
 						$outval.= ' - '.price($objp2->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2407
-					}
2408
-					else
2708
+					} else
2409 2709
 					{
2410 2710
 						$opt.= ' - '.price($objp2->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2411 2711
 						$outval.= ' - '.price($objp2->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
@@ -2415,8 +2715,7 @@  discard block
 block discarded – undo
2415 2715
 					$outpricebasetype=$objp2->price_base_type;
2416 2716
 					$outtva_tx=$objp2->tva_tx;
2417 2717
 				}
2418
-			}
2419
-			else
2718
+			} else
2420 2719
 			{
2421 2720
 				dol_print_error($this->db);
2422 2721
 			}
@@ -2434,8 +2733,7 @@  discard block
 block discarded – undo
2434 2733
 				$outval.= ' - '.price($objp->unitprice,0,$langs,0,0,-1,$conf->currency)."/";
2435 2734
 				$opt.= $langs->trans("Unit");	// Do not use strtolower because it breaks utf8 encoding
2436 2735
 				$outval.=$langs->transnoentities("Unit");
2437
-			}
2438
-			else
2736
+			} else
2439 2737
 			{
2440 2738
 				$opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2441 2739
 				$outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
@@ -2470,8 +2768,7 @@  discard block
 block discarded – undo
2470 2768
 				{
2471 2769
 					$opt.= ' - '.price($objp->custprice,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2472 2770
 					$outval.= ' - '.price($objp->custprice,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2473
-				}
2474
-				else
2771
+				} else
2475 2772
 				{
2476 2773
 					$opt.= ' - '.price($objp->custprice_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2477 2774
 					$outval.= ' - '.price($objp->custprice_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
@@ -2491,8 +2788,7 @@  discard block
 block discarded – undo
2491 2788
 			{
2492 2789
 				$opt.= ' - '.price($objp->price,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("HT");
2493 2790
 				$outval.= ' - '.price($objp->price,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("HT");
2494
-			}
2495
-			else
2791
+			} else
2496 2792
 			{
2497 2793
 				$opt.= ' - '.price($objp->price_ttc,1,$langs,0,0,-1,$conf->currency).' '.$langs->trans("TTC");
2498 2794
 				$outval.= ' - '.price($objp->price_ttc,0,$langs,0,0,-1,$conf->currency).' '.$langs->transnoentities("TTC");
@@ -2509,7 +2805,7 @@  discard block
 block discarded – undo
2509 2805
 
2510 2806
 			if ($objp->stock > 0) {
2511 2807
 				$outval.= ' - <span class="product_line_stock_ok">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2512
-			}elseif ($objp->stock <= 0) {
2808
+			} elseif ($objp->stock <= 0) {
2513 2809
 				$outval.= ' - <span class="product_line_stock_too_low">'.$langs->transnoentities("Stock").':'.$objp->stock.'</span>';
2514 2810
 			}
2515 2811
 		}
@@ -2565,8 +2861,7 @@  discard block
 block discarded – undo
2565 2861
 			$urloption=($socid > 0?'socid='.$socid.'&':'').'htmlname='.$htmlname.'&outjson=1&price_level='.$price_level.'&type='.$filtertype.'&mode=2&status='.$status.'&finished='.$finished.'&alsoproductwithnosupplierprice='.$alsoproductwithnosupplierprice;
2566 2862
 			print ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/product/ajax/products.php', $urloption, $conf->global->PRODUIT_USE_SEARCH_TO_SELECT, 0, $ajaxoptions);
2567 2863
 			print ($hidelabel?'':$langs->trans("RefOrLabel").' : ').'<input type="text" size="20" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'">';
2568
-		}
2569
-		else
2864
+		} else
2570 2865
 		{
2571 2866
 			print $this->select_produits_fournisseurs_list($socid,$selected,$htmlname,$filtertype,$filtre,'',-1,0,0,$alsoproductwithnosupplierprice);
2572 2867
 		}
@@ -2604,12 +2899,18 @@  discard block
 block discarded – undo
2604 2899
 		$sql.= " pfp.supplier_reputation";
2605 2900
 		$sql.= " FROM ".MAIN_DB_PREFIX."product as p";
2606 2901
 		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON p.rowid = pfp.fk_product";
2607
-		if ($socid) $sql.= " AND pfp.fk_soc = ".$socid;
2902
+		if ($socid) {
2903
+		    $sql.= " AND pfp.fk_soc = ".$socid;
2904
+		}
2608 2905
 		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON pfp.fk_soc = s.rowid";
2609 2906
 		$sql.= " WHERE p.entity IN (".getEntity('product').")";
2610 2907
 		$sql.= " AND p.tobuy = 1";
2611
-		if (strval($filtertype) != '') $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype);
2612
-		if (! empty($filtre)) $sql.=" ".$filtre;
2908
+		if (strval($filtertype) != '') {
2909
+		    $sql.=" AND p.fk_product_type=".$this->db->escape($filtertype);
2910
+		}
2911
+		if (! empty($filtre)) {
2912
+		    $sql.=" ".$filtre;
2913
+		}
2613 2914
 		// Add criteria on ref/label
2614 2915
 		if ($filterkey != '')
2615 2916
 		{
@@ -2618,15 +2919,23 @@  discard block
 block discarded – undo
2618 2919
 			// For natural search
2619 2920
 			$scrit = explode(' ', $filterkey);
2620 2921
 			$i=0;
2621
-			if (count($scrit) > 1) $sql.="(";
2922
+			if (count($scrit) > 1) {
2923
+			    $sql.="(";
2924
+			}
2622 2925
 			foreach ($scrit as $crit)
2623 2926
 			{
2624
-				if ($i > 0) $sql.=" AND ";
2927
+				if ($i > 0) {
2928
+				    $sql.=" AND ";
2929
+				}
2625 2930
 				$sql.="(pfp.ref_fourn LIKE '".$this->db->escape($prefix.$crit)."%' OR p.ref LIKE '".$this->db->escape($prefix.$crit)."%' OR p.label LIKE '".$this->db->escape($prefix.$crit)."%')";
2626 2931
 				$i++;
2627 2932
 			}
2628
-			if (count($scrit) > 1) $sql.=")";
2629
-			if (! empty($conf->barcode->enabled)) $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
2933
+			if (count($scrit) > 1) {
2934
+			    $sql.=")";
2935
+			}
2936
+			if (! empty($conf->barcode->enabled)) {
2937
+			    $sql.= " OR p.barcode LIKE '".$this->db->escape($prefix.$filterkey)."%'";
2938
+			}
2630 2939
 			$sql.=')';
2631 2940
 		}
2632 2941
 		$sql.= " ORDER BY pfp.ref_fourn DESC, pfp.quantity ASC";
@@ -2644,8 +2953,11 @@  discard block
 block discarded – undo
2644 2953
 
2645 2954
 			//$out.='<select class="flat" id="select'.$htmlname.'" name="'.$htmlname.'">';	// remove select to have id same with combo and ajax
2646 2955
 			$out.='<select class="flat maxwidthonsmartphone" id="'.$htmlname.'" name="'.$htmlname.'">';
2647
-			if (! $selected) $out.='<option value="0" selected>&nbsp;</option>';
2648
-			else $out.='<option value="0">&nbsp;</option>';
2956
+			if (! $selected) {
2957
+			    $out.='<option value="0" selected>&nbsp;</option>';
2958
+			} else {
2959
+			    $out.='<option value="0">&nbsp;</option>';
2960
+			}
2649 2961
 
2650 2962
 			$i = 0;
2651 2963
 			while ($i < $num)
@@ -2653,7 +2965,10 @@  discard block
 block discarded – undo
2653 2965
 				$objp = $this->db->fetch_object($result);
2654 2966
 
2655 2967
 				$outkey=$objp->idprodfournprice;                                                    // id in table of price
2656
-				if (! $outkey && $alsoproductwithnosupplierprice) $outkey='idprod_'.$objp->rowid;   // id of product
2968
+				if (! $outkey && $alsoproductwithnosupplierprice) {
2969
+				    $outkey='idprod_'.$objp->rowid;
2970
+				}
2971
+				// id of product
2657 2972
 
2658 2973
 				$outref=$objp->ref;
2659 2974
 				$outval='';
@@ -2664,8 +2979,12 @@  discard block
 block discarded – undo
2664 2979
 				$outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
2665 2980
 
2666 2981
 				$opt = '<option value="'.$outkey.'"';
2667
-				if ($selected && $selected == $objp->idprodfournprice) $opt.= ' selected';
2668
-				if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) $opt.=' disabled';
2982
+				if ($selected && $selected == $objp->idprodfournprice) {
2983
+				    $opt.= ' selected';
2984
+				}
2985
+				if (empty($objp->idprodfournprice) && empty($alsoproductwithnosupplierprice)) {
2986
+				    $opt.=' disabled';
2987
+				}
2669 2988
 				if (!empty($objp->idprodfournprice) && $objp->idprodfournprice > 0)
2670 2989
 				{
2671 2990
 					$opt.= ' pbq="'.$objp->idprodfournprice.'" data-pbq="'.$objp->idprodfournprice.'" data-pbqqty="'.$objp->quantity.'" data-pbqpercent="'.$objp->remise_percent.'"';
@@ -2673,19 +2992,27 @@  discard block
 block discarded – undo
2673 2992
 				$opt.= '>';
2674 2993
 
2675 2994
 				$objRef = $objp->ref;
2676
-				if ($filterkey && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2995
+				if ($filterkey && $filterkey != '') {
2996
+				    $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
2997
+				}
2677 2998
 				$objRefFourn = $objp->ref_fourn;
2678
-				if ($filterkey && $filterkey != '') $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);
2999
+				if ($filterkey && $filterkey != '') {
3000
+				    $objRefFourn=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRefFourn,1);
3001
+				}
2679 3002
 				$label = $objp->label;
2680
-				if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
3003
+				if ($filterkey && $filterkey != '') {
3004
+				    $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
3005
+				}
2681 3006
 
2682 3007
 				$opt.=$objp->ref;
2683
-				if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2684
-					$opt.=' ('.$objp->ref_fourn.')';
3008
+				if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
3009
+									$opt.=' ('.$objp->ref_fourn.')';
3010
+				}
2685 3011
 				$opt.=' - ';
2686 3012
 				$outval.=$objRef;
2687
-				if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
2688
-					$outval.=' ('.$objRefFourn.')';
3013
+				if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) {
3014
+									$outval.=' ('.$objRefFourn.')';
3015
+				}
2689 3016
 				$outval.=' - ';
2690 3017
 				$opt.=dol_trunc($label, 72).' - ';
2691 3018
 				$outval.=dol_trunc($label, 72).' - ';
@@ -2717,8 +3044,7 @@  discard block
 block discarded – undo
2717 3044
 						$outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/";
2718 3045
 						$opt.= $langs->trans("Unit");	// Do not use strtolower because it breaks utf8 encoding
2719 3046
 						$outval.=$langs->transnoentities("Unit");
2720
-					}
2721
-					else
3047
+					} else
2722 3048
 					{
2723 3049
 						$opt.= price($objp->fprice,1,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
2724 3050
 						$outval.= price($objp->fprice,0,$langs,0,0,-1,$conf->currency)."/".$objp->quantity;
@@ -2754,15 +3080,15 @@  discard block
 block discarded – undo
2754 3080
 						$opt .= " - ".$reputations[$objp->supplier_reputation];
2755 3081
 						$outval.=" - ".$reputations[$objp->supplier_reputation];
2756 3082
 					}
2757
-				}
2758
-				else
3083
+				} else
2759 3084
 				{
2760
-					if (empty($alsoproductwithnosupplierprice))     // No supplier price defined for couple product/supplier
3085
+					if (empty($alsoproductwithnosupplierprice)) {
3086
+					    // No supplier price defined for couple product/supplier
2761 3087
 					{
2762 3088
 						$opt.= $langs->trans("NoPriceDefinedForThisSupplier");
2763
-						$outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
2764 3089
 					}
2765
-					else                                            // No supplier price defined for product, even on other suppliers
3090
+						$outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
3091
+					} else                                            // No supplier price defined for product, even on other suppliers
2766 3092
 					{
2767 3093
 						$opt.= $langs->trans("NoPriceDefinedForThisSupplier");
2768 3094
 						$outval.=$langs->transnoentities("NoPriceDefinedForThisSupplier");
@@ -2794,10 +3120,11 @@  discard block
 block discarded – undo
2794 3120
 			include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
2795 3121
 			$out.=ajax_combobox($htmlname);
2796 3122
 
2797
-			if (empty($outputmode)) return $out;
3123
+			if (empty($outputmode)) {
3124
+			    return $out;
3125
+			}
2798 3126
 			return $outarray;
2799
-		}
2800
-		else
3127
+		} else
2801 3128
 		{
2802 3129
 			dol_print_error($this->db);
2803 3130
 		}
@@ -2843,8 +3170,7 @@  discard block
 block discarded – undo
2843 3170
 			if (! $num)
2844 3171
 			{
2845 3172
 				$form.= '<option value="0">-- '.$langs->trans("NoSupplierPriceDefinedForThisProduct").' --</option>';
2846
-			}
2847
-			else
3173
+			} else
2848 3174
 			{
2849 3175
 				require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
2850 3176
 				$form.= '<option value="0">&nbsp;</option>';
@@ -2888,8 +3214,7 @@  discard block
 block discarded – undo
2888 3214
 					if ($objp->quantity == 1)
2889 3215
 					{
2890 3216
 						$opt.= $langs->trans("Unit");
2891
-					}
2892
-					else
3217
+					} else
2893 3218
 					{
2894 3219
 						$opt.= $langs->trans("Units");
2895 3220
 					}
@@ -2898,7 +3223,9 @@  discard block
 block discarded – undo
2898 3223
 						$opt.=" - ";
2899 3224
 						$opt.= price($objp->unitprice,1,$langs,0,0,-1,$conf->currency)."/".$langs->trans("Unit");
2900 3225
 					}
2901
-					if ($objp->duration) $opt .= " - ".$objp->duration;
3226
+					if ($objp->duration) {
3227
+					    $opt .= " - ".$objp->duration;
3228
+					}
2902 3229
 					$opt .= "</option>\n";
2903 3230
 
2904 3231
 					$form.= $opt;
@@ -2909,8 +3236,7 @@  discard block
 block discarded – undo
2909 3236
 			$form.= '</select>';
2910 3237
 			$this->db->free($result);
2911 3238
 			return $form;
2912
-		}
2913
-		else
3239
+		} else
2914 3240
 		{
2915 3241
 			dol_print_error($this->db);
2916 3242
 		}
@@ -2940,7 +3266,9 @@  discard block
 block discarded – undo
2940 3266
 		if ($resql)
2941 3267
 		{
2942 3268
 			print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
2943
-			if ($showempty) print '<option value="0">&nbsp;</option>';
3269
+			if ($showempty) {
3270
+			    print '<option value="0">&nbsp;</option>';
3271
+			}
2944 3272
 			$num = $this->db->num_rows($resql);
2945 3273
 			$i = 0;
2946 3274
 			if ($num)
@@ -2952,8 +3280,7 @@  discard block
 block discarded – undo
2952 3280
 					if ($selected && $selected == $obj->rowid)
2953 3281
 					{
2954 3282
 						print '<option value="'.$obj->rowid.'" selected>'.$obj->label.'</option>';
2955
-					}
2956
-					else
3283
+					} else
2957 3284
 					{
2958 3285
 						print '<option value="'.$obj->rowid.'">'.$obj->label.'</option>';
2959 3286
 					}
@@ -2962,8 +3289,7 @@  discard block
 block discarded – undo
2962 3289
 			}
2963 3290
 			print '</select>';
2964 3291
 			return $num;
2965
-		}
2966
-		else
3292
+		} else
2967 3293
 		{
2968 3294
 			dol_print_error($this->db);
2969 3295
 		}
@@ -2982,7 +3308,10 @@  discard block
 block discarded – undo
2982 3308
 		global $langs;
2983 3309
 
2984 3310
 		$num = count($this->cache_conditions_paiements);
2985
-		if ($num > 0) return 0;    // Cache already loaded
3311
+		if ($num > 0) {
3312
+		    return 0;
3313
+		}
3314
+		// Cache already loaded
2986 3315
 
2987 3316
 		dol_syslog(__METHOD__, LOG_DEBUG);
2988 3317
 
@@ -3011,8 +3340,7 @@  discard block
 block discarded – undo
3011 3340
 			//$this->cache_conditions_paiements=dol_sort_array($this->cache_conditions_paiements, 'label', 'asc', 0, 0, 1);		// We use the field sortorder of table
3012 3341
 
3013 3342
 			return $num;
3014
-		}
3015
-		else
3343
+		} else
3016 3344
 		{
3017 3345
 			dol_print_error($this->db);
3018 3346
 			return -1;
@@ -3031,7 +3359,10 @@  discard block
 block discarded – undo
3031 3359
 		global $langs;
3032 3360
 
3033 3361
 		$num = count($this->cache_availability);
3034
-		if ($num > 0) return 0;    // Cache already loaded
3362
+		if ($num > 0) {
3363
+		    return 0;
3364
+		}
3365
+		// Cache already loaded
3035 3366
 
3036 3367
 		dol_syslog(__METHOD__, LOG_DEBUG);
3037 3368
 
@@ -3060,8 +3391,7 @@  discard block
 block discarded – undo
3060 3391
 			$this->cache_availability = dol_sort_array($this->cache_availability, 'label', 'asc', 0, 0, 1);
3061 3392
 
3062 3393
 			return $num;
3063
-		}
3064
-		else
3394
+		} else
3065 3395
 		{
3066 3396
 			dol_print_error($this->db);
3067 3397
 			return -1;
@@ -3086,14 +3416,15 @@  discard block
 block discarded – undo
3086 3416
 		dol_syslog(__METHOD__." selected=".$selected.", htmlname=".$htmlname, LOG_DEBUG);
3087 3417
 
3088 3418
 		print '<select id="'.$htmlname.'" class="flat" name="'.$htmlname.'">';
3089
-		if ($addempty) print '<option value="0">&nbsp;</option>';
3419
+		if ($addempty) {
3420
+		    print '<option value="0">&nbsp;</option>';
3421
+		}
3090 3422
 		foreach($this->cache_availability as $id => $arrayavailability)
3091 3423
 		{
3092 3424
 			if ($selected == $id)
3093 3425
 			{
3094 3426
 				print '<option value="'.$id.'" selected>';
3095
-			}
3096
-			else
3427
+			} else
3097 3428
 			{
3098 3429
 				print '<option value="'.$id.'">';
3099 3430
 			}
@@ -3101,7 +3432,9 @@  discard block
 block discarded – undo
3101 3432
 			print '</option>';
3102 3433
 		}
3103 3434
 		print '</select>';
3104
-		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3435
+		if ($user->admin) {
3436
+		    print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3437
+		}
3105 3438
 	}
3106 3439
 
3107 3440
 	/**
@@ -3114,7 +3447,10 @@  discard block
 block discarded – undo
3114 3447
 		global $langs;
3115 3448
 
3116 3449
 		$num = count($this->cache_demand_reason);
3117
-		if ($num > 0) return 0;    // Cache already loaded
3450
+		if ($num > 0) {
3451
+		    return 0;
3452
+		}
3453
+		// Cache already loaded
3118 3454
 
3119 3455
 		$sql = "SELECT rowid, code, label";
3120 3456
 		$sql.= " FROM ".MAIN_DB_PREFIX.'c_input_reason';
@@ -3132,8 +3468,14 @@  discard block
 block discarded – undo
3132 3468
 
3133 3469
 				// Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
3134 3470
 				$label=($obj->label!='-'?$obj->label:'');
3135
-				if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) $label = $langs->trans("DemandReasonType".$obj->code); // So translation key DemandReasonTypeSRC_XXX will work
3136
-				if ($langs->trans($obj->code) != $obj->code) $label=$langs->trans($obj->code);																// So translation key SRC_XXX will work
3471
+				if ($langs->trans("DemandReasonType".$obj->code) != ("DemandReasonType".$obj->code)) {
3472
+				    $label = $langs->trans("DemandReasonType".$obj->code);
3473
+				}
3474
+				// So translation key DemandReasonTypeSRC_XXX will work
3475
+				if ($langs->trans($obj->code) != $obj->code) {
3476
+				    $label=$langs->trans($obj->code);
3477
+				}
3478
+				// So translation key SRC_XXX will work
3137 3479
 
3138 3480
 				$tmparray[$obj->rowid]['id']   =$obj->rowid;
3139 3481
 				$tmparray[$obj->rowid]['code'] =$obj->code;
@@ -3145,8 +3487,7 @@  discard block
 block discarded – undo
3145 3487
 
3146 3488
 			unset($tmparray);
3147 3489
 			return $num;
3148
-		}
3149
-		else
3490
+		} else
3150 3491
 		{
3151 3492
 			dol_print_error($this->db);
3152 3493
 			return -1;
@@ -3170,16 +3511,19 @@  discard block
 block discarded – undo
3170 3511
 		$this->loadCacheInputReason();
3171 3512
 
3172 3513
 		print '<select class="flat" id="select_'.$htmlname.'" name="'.$htmlname.'">';
3173
-		if ($addempty) print '<option value="0"'.(empty($selected)?' selected':'').'>&nbsp;</option>';
3514
+		if ($addempty) {
3515
+		    print '<option value="0"'.(empty($selected)?' selected':'').'>&nbsp;</option>';
3516
+		}
3174 3517
 		foreach($this->cache_demand_reason as $id => $arraydemandreason)
3175 3518
 		{
3176
-			if ($arraydemandreason['code']==$exclude) continue;
3519
+			if ($arraydemandreason['code']==$exclude) {
3520
+			    continue;
3521
+			}
3177 3522
 
3178 3523
 			if ($selected && ($selected == $arraydemandreason['id'] || $selected == $arraydemandreason['code']))
3179 3524
 			{
3180 3525
 				print '<option value="'.$arraydemandreason['id'].'" selected>';
3181
-			}
3182
-			else
3526
+			} else
3183 3527
 			{
3184 3528
 				print '<option value="'.$arraydemandreason['id'].'">';
3185 3529
 			}
@@ -3188,7 +3532,9 @@  discard block
 block discarded – undo
3188 3532
 			print '</option>';
3189 3533
 		}
3190 3534
 		print '</select>';
3191
-		if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3535
+		if ($user->admin) {
3536
+		    print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3537
+		}
3192 3538
 	}
3193 3539
 
3194 3540
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -3203,7 +3549,10 @@  discard block
 block discarded – undo
3203 3549
 		global $langs;
3204 3550
 
3205 3551
 		$num=count($this->cache_types_paiements);
3206
-		if ($num > 0) return $num;    // Cache already loaded
3552
+		if ($num > 0) {
3553
+		    return $num;
3554
+		}
3555
+		// Cache already loaded
3207 3556
 
3208 3557
 		dol_syslog(__METHOD__, LOG_DEBUG);
3209 3558
 
@@ -3236,8 +3585,7 @@  discard block
 block discarded – undo
3236 3585
 			$this->cache_types_paiements = dol_sort_array($this->cache_types_paiements, 'label', 'asc', 0, 0, 1);
3237 3586
 
3238 3587
 			return $num;
3239
-		}
3240
-		else
3588
+		} else
3241 3589
 		{
3242 3590
 			dol_print_error($this->db);
3243 3591
 			return -1;
@@ -3269,17 +3617,20 @@  discard block
 block discarded – undo
3269 3617
 		$this->load_cache_conditions_paiements();
3270 3618
 
3271 3619
 		// Set default value if not already set by caller
3272
-		if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
3620
+		if (empty($selected) && ! empty($conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID)) {
3621
+		    $selected = $conf->global->MAIN_DEFAULT_PAYMENT_TERM_ID;
3622
+		}
3273 3623
 
3274 3624
 		print '<select id="'.$htmlname.'" class="flat selectpaymentterms'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
3275
-		if ($addempty) print '<option value="0">&nbsp;</option>';
3625
+		if ($addempty) {
3626
+		    print '<option value="0">&nbsp;</option>';
3627
+		}
3276 3628
 		foreach($this->cache_conditions_paiements as $id => $arrayconditions)
3277 3629
 		{
3278 3630
 			if ($selected == $id)
3279 3631
 			{
3280 3632
 				print '<option value="'.$id.'" selected>';
3281
-			}
3282
-			else
3633
+			} else
3283 3634
 			{
3284 3635
 				print '<option value="'.$id.'">';
3285 3636
 			}
@@ -3287,7 +3638,9 @@  discard block
 block discarded – undo
3287 3638
 			print '</option>';
3288 3639
 		}
3289 3640
 		print '</select>';
3290
-		if ($user->admin && empty($noinfoadmin)) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3641
+		if ($user->admin && empty($noinfoadmin)) {
3642
+		    print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3643
+		}
3291 3644
 	}
3292 3645
 
3293 3646
 
@@ -3314,42 +3667,69 @@  discard block
 block discarded – undo
3314 3667
 		dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$filtertype.", ".$format, LOG_DEBUG);
3315 3668
 
3316 3669
 		$filterarray=array();
3317
-		if ($filtertype == 'CRDT')  	$filterarray=array(0,2,3);
3318
-		elseif ($filtertype == 'DBIT') 	$filterarray=array(1,2,3);
3319
-		elseif ($filtertype != '' && $filtertype != '-1') $filterarray=explode(',',$filtertype);
3670
+		if ($filtertype == 'CRDT') {
3671
+		    $filterarray=array(0,2,3);
3672
+		} elseif ($filtertype == 'DBIT') {
3673
+		    $filterarray=array(1,2,3);
3674
+		} elseif ($filtertype != '' && $filtertype != '-1') {
3675
+		    $filterarray=explode(',',$filtertype);
3676
+		}
3320 3677
 
3321 3678
 		$this->load_cache_types_paiements();
3322 3679
 
3323 3680
 		print '<select id="select'.$htmlname.'" class="flat selectpaymenttypes'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'">';
3324
-		if ($empty) print '<option value="">&nbsp;</option>';
3681
+		if ($empty) {
3682
+		    print '<option value="">&nbsp;</option>';
3683
+		}
3325 3684
 		foreach($this->cache_types_paiements as $id => $arraytypes)
3326 3685
 		{
3327 3686
 			// If not good status
3328
-			if ($active >= 0 && $arraytypes['active'] != $active) continue;
3687
+			if ($active >= 0 && $arraytypes['active'] != $active) {
3688
+			    continue;
3689
+			}
3329 3690
 
3330 3691
 			// On passe si on a demande de filtrer sur des modes de paiments particuliers
3331
-			if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;
3692
+			if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) {
3693
+			    continue;
3694
+			}
3332 3695
 
3333 3696
 			// We discard empty line if showempty is on because an empty line has already been output.
3334
-			if ($empty && empty($arraytypes['code'])) continue;
3697
+			if ($empty && empty($arraytypes['code'])) {
3698
+			    continue;
3699
+			}
3335 3700
 
3336
-			if ($format == 0) print '<option value="'.$id.'"';
3337
-			elseif ($format == 1) print '<option value="'.$arraytypes['code'].'"';
3338
-			elseif ($format == 2) print '<option value="'.$arraytypes['code'].'"';
3339
-			elseif ($format == 3) print '<option value="'.$id.'"';
3701
+			if ($format == 0) {
3702
+			    print '<option value="'.$id.'"';
3703
+			} elseif ($format == 1) {
3704
+			    print '<option value="'.$arraytypes['code'].'"';
3705
+			} elseif ($format == 2) {
3706
+			    print '<option value="'.$arraytypes['code'].'"';
3707
+			} elseif ($format == 3) {
3708
+			    print '<option value="'.$id.'"';
3709
+			}
3340 3710
 			// Si selected est text, on compare avec code, sinon avec id
3341
-			if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected';
3342
-			elseif ($selected == $id) print ' selected';
3711
+			if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) {
3712
+			    print ' selected';
3713
+			} elseif ($selected == $id) {
3714
+			    print ' selected';
3715
+			}
3343 3716
 			print '>';
3344
-			if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3345
-			elseif ($format == 1) $value=$arraytypes['code'];
3346
-			elseif ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3347
-			elseif ($format == 3) $value=$arraytypes['code'];
3717
+			if ($format == 0) {
3718
+			    $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3719
+			} elseif ($format == 1) {
3720
+			    $value=$arraytypes['code'];
3721
+			} elseif ($format == 2) {
3722
+			    $value=($maxlength?dol_trunc($arraytypes['label'],$maxlength):$arraytypes['label']);
3723
+			} elseif ($format == 3) {
3724
+			    $value=$arraytypes['code'];
3725
+			}
3348 3726
 			print $value?$value:'&nbsp;';
3349 3727
 			print '</option>';
3350 3728
 		}
3351 3729
 		print '</select>';
3352
-		if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3730
+		if ($user->admin && ! $noadmininfo) {
3731
+		    print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3732
+		}
3353 3733
 	}
3354 3734
 
3355 3735
 
@@ -3376,8 +3756,7 @@  discard block
 block discarded – undo
3376 3756
 			if ($selected == $id)
3377 3757
 			{
3378 3758
 				$return.= '<option value="'.$id.'" selected>'.$value;
3379
-			}
3380
-			else
3759
+			} else
3381 3760
 			{
3382 3761
 				$return.= '<option value="'.$id.'">'.$value;
3383 3762
 			}
@@ -3408,7 +3787,9 @@  discard block
 block discarded – undo
3408 3787
 		$sql = "SELECT rowid, code, libelle as label";
3409 3788
 		$sql.= " FROM ".MAIN_DB_PREFIX."c_shipment_mode";
3410 3789
 		$sql.= " WHERE active > 0";
3411
-		if ($filtre) $sql.=" AND ".$filtre;
3790
+		if ($filtre) {
3791
+		    $sql.=" AND ".$filtre;
3792
+		}
3412 3793
 		$sql.= " ORDER BY libelle ASC";
3413 3794
 
3414 3795
 		dol_syslog(get_class($this)."::selectShippingMode", LOG_DEBUG);
@@ -3433,7 +3814,9 @@  discard block
 block discarded – undo
3433 3814
 					$i++;
3434 3815
 				}
3435 3816
 				print "</select>";
3436
-				if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3817
+				if ($user->admin) {
3818
+				    print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
3819
+				}
3437 3820
 			} else {
3438 3821
 				print $langs->trans("NoShippingMethodDefined");
3439 3822
 			}
@@ -3516,8 +3899,7 @@  discard block
 block discarded – undo
3516 3899
 					}
3517 3900
 				}
3518 3901
 			}
3519
-		}
3520
-		else
3902
+		} else
3521 3903
 		{
3522 3904
 				dol_syslog("Error sql=" . $sql . ", error=" . $this->error, LOG_ERR);
3523 3905
 		}
@@ -3550,21 +3932,24 @@  discard block
 block discarded – undo
3550 3932
 		$resql = $this->db->query($sql);
3551 3933
 		if($resql && $this->db->num_rows($resql) > 0)
3552 3934
 		{
3553
-			if ($showempty) $return .= '<option value="none"></option>';
3935
+			if ($showempty) {
3936
+			    $return .= '<option value="none"></option>';
3937
+			}
3554 3938
 
3555 3939
 			while($res = $this->db->fetch_object($resql))
3556 3940
 			{
3557 3941
 			    $unitLabel = $res->label;
3558
-			    if (! empty($langs->tab_translate['unit'.$res->code]))	// check if Translation is available before
3942
+			    if (! empty($langs->tab_translate['unit'.$res->code])) {
3943
+			        // check if Translation is available before
3559 3944
 			    {
3560 3945
 			        $unitLabel = $langs->trans('unit'.$res->code)!=$res->label?$langs->trans('unit'.$res->code):$res->label;
3561 3946
 			    }
3947
+			    }
3562 3948
 
3563 3949
 				if ($selected == $res->rowid)
3564 3950
 				{
3565 3951
 				    $return.='<option value="'.$res->rowid.'" selected>'.$unitLabel.'</option>';
3566
-				}
3567
-				else
3952
+				} else
3568 3953
 				{
3569 3954
 				    $return.='<option value="'.$res->rowid.'">'.$unitLabel.'</option>';
3570 3955
 				}
@@ -3598,8 +3983,12 @@  discard block
 block discarded – undo
3598 3983
 		$sql = "SELECT rowid, label, bank, clos as status, currency_code";
3599 3984
 		$sql.= " FROM ".MAIN_DB_PREFIX."bank_account";
3600 3985
 		$sql.= " WHERE entity IN (".getEntity('bank_account').")";
3601
-		if ($statut != 2) $sql.= " AND clos = '".$statut."'";
3602
-		if ($filtre) $sql.=" AND ".$filtre;
3986
+		if ($statut != 2) {
3987
+		    $sql.= " AND clos = '".$statut."'";
3988
+		}
3989
+		if ($filtre) {
3990
+		    $sql.=" AND ".$filtre;
3991
+		}
3603 3992
 		$sql.= " ORDER BY label";
3604 3993
 
3605 3994
 		dol_syslog(get_class($this)."::select_comptes", LOG_DEBUG);
@@ -3622,26 +4011,30 @@  discard block
 block discarded – undo
3622 4011
 					if ($selected == $obj->rowid)
3623 4012
 					{
3624 4013
 						print '<option value="'.$obj->rowid.'" selected>';
3625
-					}
3626
-					else
4014
+					} else
3627 4015
 					{
3628 4016
 						print '<option value="'.$obj->rowid.'">';
3629 4017
 					}
3630 4018
 					print trim($obj->label);
3631
-					if ($showcurrency) print ' ('.$obj->currency_code.')';
3632
-					if ($statut == 2 && $obj->status == 1) print ' ('.$langs->trans("Closed").')';
4019
+					if ($showcurrency) {
4020
+					    print ' ('.$obj->currency_code.')';
4021
+					}
4022
+					if ($statut == 2 && $obj->status == 1) {
4023
+					    print ' ('.$langs->trans("Closed").')';
4024
+					}
3633 4025
 					print '</option>';
3634 4026
 					$i++;
3635 4027
 				}
3636 4028
 				print "</select>";
3637
-			}
3638
-			else
4029
+			} else
3639 4030
 			{
3640
-				if ($statut == 0) print '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
3641
-				else print '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
4031
+				if ($statut == 0) {
4032
+				    print '<span class="opacitymedium">'.$langs->trans("NoActiveBankAccountDefined").'</span>';
4033
+				} else {
4034
+				    print '<span class="opacitymedium">'.$langs->trans("NoBankAccountFound").'</span>';
4035
+				}
3642 4036
 			}
3643
-		}
3644
-		else {
4037
+		} else {
3645 4038
 			dol_print_error($this->db);
3646 4039
 		}
3647 4040
 
@@ -3665,7 +4058,9 @@  discard block
 block discarded – undo
3665 4058
 			print '<input type="hidden" name="action" value="setbankaccount">';
3666 4059
 			print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
3667 4060
 			$nbaccountfound = $this->select_comptes($selected, $htmlname, 0, '', $addempty);
3668
-			if ($nbaccountfound > 0) print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4061
+			if ($nbaccountfound > 0) {
4062
+			    print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4063
+			}
3669 4064
 			print '</form>';
3670 4065
 		} else {
3671 4066
 
@@ -3675,7 +4070,9 @@  discard block
 block discarded – undo
3675 4070
 				require_once DOL_DOCUMENT_ROOT .'/compta/bank/class/account.class.php';
3676 4071
 				$bankstatic=new Account($this->db);
3677 4072
 				$result = $bankstatic->fetch($selected);
3678
-				if ($result) print $bankstatic->getNomUrl(1);
4073
+				if ($result) {
4074
+				    print $bankstatic->getNomUrl(1);
4075
+				}
3679 4076
 			} else {
3680 4077
 				print "&nbsp;";
3681 4078
 			}
@@ -3725,14 +4122,16 @@  discard block
 block discarded – undo
3725 4122
 				while ($i < $num)
3726 4123
 				{
3727 4124
 					$objp = $this->db->fetch_object($result);
3728
-					if ($objp) $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
4125
+					if ($objp) {
4126
+					    $cate_arbo[$objp->rowid]=array('id'=>$objp->rowid, 'fulllabel'=>$objp->label);
4127
+					}
3729 4128
 					$i++;
3730 4129
 				}
3731 4130
 				$this->db->free($result);
4131
+			} else {
4132
+			    dol_print_error($this->db);
3732 4133
 			}
3733
-			else dol_print_error($this->db);
3734
-		}
3735
-		else
4134
+		} else
3736 4135
 		{
3737 4136
 			$cat = new Categorie($this->db);
3738 4137
 			$cate_arbo = $cat->get_full_arbo($type, $excludeafterid);
@@ -3742,8 +4141,9 @@  discard block
 block discarded – undo
3742 4141
 		$outarray=array();
3743 4142
 		if (is_array($cate_arbo))
3744 4143
 		{
3745
-			if (! count($cate_arbo)) $output.= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
3746
-			else
4144
+			if (! count($cate_arbo)) {
4145
+			    $output.= '<option value="-1" disabled>'.$langs->trans("NoCategoriesDefined").'</option>';
4146
+			} else
3747 4147
 			{
3748 4148
 				$output.= '<option value="-1">&nbsp;</option>';
3749 4149
 				foreach($cate_arbo as $key => $value)
@@ -3751,8 +4151,7 @@  discard block
 block discarded – undo
3751 4151
 					if ($cate_arbo[$key]['id'] == $selected || ($selected == 'auto' && count($cate_arbo) == 1))
3752 4152
 					{
3753 4153
 						$add = 'selected ';
3754
-					}
3755
-					else
4154
+					} else
3756 4155
 					{
3757 4156
 						$add = '';
3758 4157
 					}
@@ -3765,7 +4164,9 @@  discard block
 block discarded – undo
3765 4164
 		$output.= '</select>';
3766 4165
 		$output.= "\n";
3767 4166
 
3768
-		if ($outputmode) return $outarray;
4167
+		if ($outputmode) {
4168
+		    return $outarray;
4169
+		}
3769 4170
 		return $output;
3770 4171
 	}
3771 4172
 
@@ -3829,7 +4230,9 @@  discard block
 block discarded – undo
3829 4230
 
3830 4231
 		// Clean parameters
3831 4232
 		$newselectedchoice=empty($selectedchoice)?"no":$selectedchoice;
3832
-		if ($conf->browser->layout == 'phone') $width='95%';
4233
+		if ($conf->browser->layout == 'phone') {
4234
+		    $width='95%';
4235
+		}
3833 4236
 
3834 4237
 		if (is_array($formquestion) && ! empty($formquestion))
3835 4238
 		{
@@ -3847,7 +4250,9 @@  discard block
 block discarded – undo
3847 4250
 
3848 4251
 			// Now add questions
3849 4252
 			$more.='<table class="paddingtopbottomonly" width="100%">'."\n";
3850
-			if (! empty($formquestion['text'])) $more.='<tr><td colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
4253
+			if (! empty($formquestion['text'])) {
4254
+			    $more.='<tr><td colspan="2">'.$formquestion['text'].'</td></tr>'."\n";
4255
+			}
3851 4256
 			foreach ($formquestion as $key => $input)
3852 4257
 			{
3853 4258
 				if (is_array($input) && ! empty($input))
@@ -3859,46 +4264,54 @@  discard block
 block discarded – undo
3859 4264
 					if ($input['type'] == 'text')
3860 4265
 					{
3861 4266
 						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="text" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3862
-					}
3863
-					elseif ($input['type'] == 'password')
4267
+					} elseif ($input['type'] == 'password')
3864 4268
 					{
3865 4269
 						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td><td align="left"><input type="password" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$size.' value="'.$input['value'].'"'.$moreattr.' /></td></tr>'."\n";
3866
-					}
3867
-					elseif ($input['type'] == 'select')
4270
+					} elseif ($input['type'] == 'select')
3868 4271
 					{
3869 4272
 						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
3870
-						if (! empty($input['label'])) $more.=$input['label'].'</td><td class="tdtop" align="left">';
4273
+						if (! empty($input['label'])) {
4274
+						    $more.=$input['label'].'</td><td class="tdtop" align="left">';
4275
+						}
3871 4276
 						$more.=$this->selectarray($input['name'],$input['values'],$input['default'],1,0,0,$moreattr,0,0,0,'',$morecss);
3872 4277
 						$more.='</td></tr>'."\n";
3873
-					}
3874
-					elseif ($input['type'] == 'checkbox')
4278
+					} elseif ($input['type'] == 'checkbox')
3875 4279
 					{
3876 4280
 						$more.='<tr>';
3877 4281
 						$more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].' </td><td align="left">';
3878 4282
 						$more.='<input type="checkbox" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'"'.$moreattr;
3879
-						if (! is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') $more.=' checked';
3880
-						if (is_bool($input['value']) && $input['value']) $more.=' checked';
3881
-						if (isset($input['disabled'])) $more.=' disabled';
4283
+						if (! is_bool($input['value']) && $input['value'] != 'false' && $input['value'] != '0') {
4284
+						    $more.=' checked';
4285
+						}
4286
+						if (is_bool($input['value']) && $input['value']) {
4287
+						    $more.=' checked';
4288
+						}
4289
+						if (isset($input['disabled'])) {
4290
+						    $more.=' disabled';
4291
+						}
3882 4292
 						$more.=' /></td>';
3883 4293
 						$more.='</tr>'."\n";
3884
-					}
3885
-					elseif ($input['type'] == 'radio')
4294
+					} elseif ($input['type'] == 'radio')
3886 4295
 					{
3887 4296
 						$i=0;
3888 4297
 						foreach($input['values'] as $selkey => $selval)
3889 4298
 						{
3890 4299
 							$more.='<tr>';
3891
-							if ($i==0) $more.='<td'.(empty($input['tdclass'])?' class="tdtop"':(' class="tdtop '.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3892
-							else $more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>&nbsp;</td>';
4300
+							if ($i==0) {
4301
+							    $more.='<td'.(empty($input['tdclass'])?' class="tdtop"':(' class="tdtop '.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
4302
+							} else {
4303
+							    $more.='<td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>&nbsp;</td>';
4304
+							}
3893 4305
 							$more.='<td><input type="radio" class="flat'.$morecss.'" id="'.$input['name'].'" name="'.$input['name'].'" value="'.$selkey.'"'.$moreattr;
3894
-							if ($input['disabled']) $more.=' disabled';
4306
+							if ($input['disabled']) {
4307
+							    $more.=' disabled';
4308
+							}
3895 4309
 							$more.=' /> ';
3896 4310
 							$more.=$selval;
3897 4311
 							$more.='</td></tr>'."\n";
3898 4312
 							$i++;
3899 4313
 						}
3900
-					}
3901
-					elseif ($input['type'] == 'date')
4314
+					} elseif ($input['type'] == 'date')
3902 4315
 					{
3903 4316
 						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>'.$input['label'].'</td>';
3904 4317
 						$more.='<td align="left">';
@@ -3909,16 +4322,15 @@  discard block
 block discarded – undo
3909 4322
 						$formquestion[] = array('name'=>$input['name'].'year');
3910 4323
 						$formquestion[] = array('name'=>$input['name'].'hour');
3911 4324
 						$formquestion[] = array('name'=>$input['name'].'min');
3912
-					}
3913
-					elseif ($input['type'] == 'other')
4325
+					} elseif ($input['type'] == 'other')
3914 4326
 					{
3915 4327
 						$more.='<tr><td'.(empty($input['tdclass'])?'':(' class="'.$input['tdclass'].'"')).'>';
3916
-						if (! empty($input['label'])) $more.=$input['label'].'</td><td align="left">';
4328
+						if (! empty($input['label'])) {
4329
+						    $more.=$input['label'].'</td><td align="left">';
4330
+						}
3917 4331
 						$more.=$input['value'];
3918 4332
 						$more.='</td></tr>'."\n";
3919
-					}
3920
-
3921
-					elseif ($input['type'] == 'onecolumn')
4333
+					} elseif ($input['type'] == 'onecolumn')
3922 4334
 					{
3923 4335
 						$more.='<tr><td colspan="2" align="left">';
3924 4336
 						$more.=$input['value'];
@@ -3932,8 +4344,12 @@  discard block
 block discarded – undo
3932 4344
 		// JQUI method dialog is broken with jmobile, we use standard HTML.
3933 4345
 		// Note: When using dol_use_jmobile or no js, you must also check code for button use a GET url with action=xxx and check that you also output the confirm code when action=xxx
3934 4346
 		// See page product/card.php for example
3935
-		if (! empty($conf->dol_use_jmobile)) $useajax=0;
3936
-		if (empty($conf->use_javascript_ajax)) $useajax=0;
4347
+		if (! empty($conf->dol_use_jmobile)) {
4348
+		    $useajax=0;
4349
+		}
4350
+		if (empty($conf->use_javascript_ajax)) {
4351
+		    $useajax=0;
4352
+		}
3937 4353
 
3938 4354
 		if ($useajax)
3939 4355
 		{
@@ -3955,8 +4371,12 @@  discard block
 block discarded – undo
3955 4371
 				foreach ($formquestion as $key => $input)
3956 4372
 				{
3957 4373
 					//print "xx ".$key." rr ".is_array($input)."<br>\n";
3958
-					if (is_array($input) && isset($input['name'])) array_push($inputok,$input['name']);
3959
-					if (isset($input['inputko']) && $input['inputko'] == 1) array_push($inputko,$input['name']);
4374
+					if (is_array($input) && isset($input['name'])) {
4375
+					    array_push($inputok,$input['name']);
4376
+					}
4377
+					if (isset($input['inputko']) && $input['inputko'] == 1) {
4378
+					    array_push($inputko,$input['name']);
4379
+					}
3960 4380
 				}
3961 4381
 			}
3962 4382
 			// Show JQuery confirm box. Note that global var $useglobalvars is used inside this template
@@ -4039,15 +4459,18 @@  discard block
 block discarded – undo
4039 4459
             });
4040 4460
             </script>';
4041 4461
 			$formconfirm.= "<!-- end ajax formconfirm -->\n";
4042
-		}
4043
-		else
4462
+		} else
4044 4463
 		{
4045 4464
 			$formconfirm.= "\n<!-- begin formconfirm page=".$page." -->\n";
4046 4465
 
4047
-			if (empty($disableformtag)) $formconfirm.= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
4466
+			if (empty($disableformtag)) {
4467
+			    $formconfirm.= '<form method="POST" action="'.$page.'" class="notoptoleftroright">'."\n";
4468
+			}
4048 4469
 
4049 4470
 			$formconfirm.= '<input type="hidden" name="action" value="'.$action.'">'."\n";
4050
-			if (empty($disableformtag)) $formconfirm.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
4471
+			if (empty($disableformtag)) {
4472
+			    $formconfirm.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">'."\n";
4473
+			}
4051 4474
 
4052 4475
 			$formconfirm.= '<table width="100%" class="valid">'."\n";
4053 4476
 
@@ -4073,7 +4496,9 @@  discard block
 block discarded – undo
4073 4496
 
4074 4497
 			$formconfirm.= '</table>'."\n";
4075 4498
 
4076
-			if (empty($disableformtag)) $formconfirm.= "</form>\n";
4499
+			if (empty($disableformtag)) {
4500
+			    $formconfirm.= "</form>\n";
4501
+			}
4077 4502
 			$formconfirm.= '<br>';
4078 4503
 
4079 4504
 			$formconfirm.= "<!-- end formconfirm -->\n";
@@ -4119,8 +4544,7 @@  discard block
 block discarded – undo
4119 4544
 			$out.=$formproject->select_projects($socid, $selected, $htmlname, $maxlength, 0, 1, $discard_closed, $forcefocus, 0, 0, '', 1);
4120 4545
 			$out.='<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4121 4546
 			$out.='</form>';
4122
-		}
4123
-		else
4547
+		} else
4124 4548
 		{
4125 4549
 			if ($selected)
4126 4550
 			{
@@ -4128,8 +4552,7 @@  discard block
 block discarded – undo
4128 4552
 				$projet->fetch($selected);
4129 4553
 				//print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>';
4130 4554
 				$out.=$projet->getNomUrl(0,'',1);
4131
-			}
4132
-			else
4555
+			} else
4133 4556
 			{
4134 4557
 				$out.="&nbsp;";
4135 4558
 			}
@@ -4165,8 +4588,7 @@  discard block
 block discarded – undo
4165 4588
 			$this->select_conditions_paiements($selected,$htmlname,-1,$addempty);
4166 4589
 			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4167 4590
 			print '</form>';
4168
-		}
4169
-		else
4591
+		} else
4170 4592
 		{
4171 4593
 			if ($selected)
4172 4594
 			{
@@ -4200,8 +4622,7 @@  discard block
 block discarded – undo
4200 4622
 			$this->selectAvailabilityDelay($selected,$htmlname,-1,$addempty);
4201 4623
 			print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4202 4624
 			print '</form>';
4203
-		}
4204
-		else
4625
+		} else
4205 4626
 		{
4206 4627
 			if ($selected)
4207 4628
 			{
@@ -4234,8 +4655,7 @@  discard block
 block discarded – undo
4234 4655
 			$this->selectInputReason($selected,$htmlname,-1,$addempty);
4235 4656
 			print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
4236 4657
 			print '</form>';
4237
-		}
4238
-		else
4658
+		} else
4239 4659
 		{
4240 4660
 			if ($selected)
4241 4661
 			{
@@ -4285,14 +4705,18 @@  discard block
 block discarded – undo
4285 4705
 			$ret.='</td>';
4286 4706
 			$ret.='<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
4287 4707
 			$ret.='</tr></table></form>';
4288
-		}
4289
-		else
4708
+		} else
4290 4709
 		{
4291
-			if ($displayhour) $ret.=dol_print_date($selected,'dayhour');
4292
-			else $ret.=dol_print_date($selected,'day');
4710
+			if ($displayhour) {
4711
+			    $ret.=dol_print_date($selected,'dayhour');
4712
+			} else {
4713
+			    $ret.=dol_print_date($selected,'day');
4714
+			}
4293 4715
 		}
4294 4716
 
4295
-		if (empty($nooutput)) print $ret;
4717
+		if (empty($nooutput)) {
4718
+		    print $ret;
4719
+		}
4296 4720
 		return $ret;
4297 4721
 	}
4298 4722
 
@@ -4321,8 +4745,7 @@  discard block
 block discarded – undo
4321 4745
 			print $this->select_dolusers($selected,$htmlname,1,$exclude,0,$include);
4322 4746
 			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4323 4747
 			print '</form>';
4324
-		}
4325
-		else
4748
+		} else
4326 4749
 		{
4327 4750
 			if ($selected)
4328 4751
 			{
@@ -4360,8 +4783,7 @@  discard block
 block discarded – undo
4360 4783
 			$this->select_types_paiements($selected,$htmlname,$filtertype,0,0,0,0,$active);
4361 4784
 			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4362 4785
 			print '</form>';
4363
-		}
4364
-		else
4786
+		} else
4365 4787
 		{
4366 4788
 			if ($selected)
4367 4789
 			{
@@ -4394,8 +4816,7 @@  discard block
 block discarded – undo
4394 4816
 			print $this->selectMultiCurrency($selected, $htmlname, 0);
4395 4817
 			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4396 4818
 			print '</form>';
4397
-		}
4398
-		else
4819
+		} else
4399 4820
 		{
4400 4821
 			dol_include_once('/core/lib/company.lib.php');
4401 4822
 			print !empty($selected) ? currency_name($selected,1) : '&nbsp;';
@@ -4429,15 +4850,15 @@  discard block
 block discarded – undo
4429 4850
 			print '</select> ';
4430 4851
 			print '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4431 4852
 			print '</form>';
4432
-		}
4433
-		else
4853
+		} else
4434 4854
 		{
4435 4855
 			if (! empty($rate))
4436 4856
 			{
4437
-				print price($rate, 1, $langs, 1, 0);
4438
-				if ($currency && $rate != 1) print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
4439
-			}
4440
-			else
4857
+				print price($rate, 1, $langs, 1, 0);
4858
+				if ($currency && $rate != 1) {
4859
+				    print ' &nbsp; ('.price($rate, 1, $langs, 1, 0).' '.$currency.' = 1 '.$conf->currency.')';
4860
+				}
4861
+			} else
4441 4862
 			{
4442 4863
 				print 1;
4443 4864
 			}
@@ -4474,28 +4895,44 @@  discard block
 block discarded – undo
4474 4895
 			if(! empty($discount_type)) {
4475 4896
 				if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4476 4897
 				{
4477
-					if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") $translationKey = 'HasAbsoluteDiscountFromSupplier';    // If we want deposit to be substracted to payments only and not to total of final invoice
4478
-					else $translationKey = 'HasCreditNoteFromSupplier';
4479
-				}
4480
-				else
4898
+					if (! $filter || $filter=="fk_invoice_supplier_source IS NULL") {
4899
+					    $translationKey = 'HasAbsoluteDiscountFromSupplier';
4900
+					}
4901
+					// If we want deposit to be substracted to payments only and not to total of final invoice
4902
+					else {
4903
+					    $translationKey = 'HasCreditNoteFromSupplier';
4904
+					}
4905
+				} else
4481 4906
 				{
4482
-					if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") $translationKey = 'HasAbsoluteDiscountFromSupplier';
4483
-					else $translationKey = 'HasCreditNoteFromSupplier';
4907
+					if (! $filter || $filter=="fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
4908
+					    $translationKey = 'HasAbsoluteDiscountFromSupplier';
4909
+					} else {
4910
+					    $translationKey = 'HasCreditNoteFromSupplier';
4911
+					}
4484 4912
 				}
4485 4913
 			} else {
4486 4914
 				if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS))
4487 4915
 				{
4488
-					if (! $filter || $filter=="fk_facture_source IS NULL") $translationKey = 'CompanyHasAbsoluteDiscount';    // If we want deposit to be substracted to payments only and not to total of final invoice
4489
-					else $translationKey = 'CompanyHasCreditNote';
4490
-				}
4491
-				else
4916
+					if (! $filter || $filter=="fk_facture_source IS NULL") {
4917
+					    $translationKey = 'CompanyHasAbsoluteDiscount';
4918
+					}
4919
+					// If we want deposit to be substracted to payments only and not to total of final invoice
4920
+					else {
4921
+					    $translationKey = 'CompanyHasCreditNote';
4922
+					}
4923
+				} else
4492 4924
 				{
4493
-					if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") $translationKey = 'CompanyHasAbsoluteDiscount';
4494
-					else $translationKey = 'CompanyHasCreditNote';
4925
+					if (! $filter || $filter=="fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
4926
+					    $translationKey = 'CompanyHasAbsoluteDiscount';
4927
+					} else {
4928
+					    $translationKey = 'CompanyHasCreditNote';
4929
+					}
4495 4930
 				}
4496 4931
 			}
4497 4932
 			print $langs->trans($translationKey,price($amount,0,$langs,0,0,-1,$conf->currency));
4498
-			if (empty($hidelist)) print ': ';
4933
+			if (empty($hidelist)) {
4934
+			    print ': ';
4935
+			}
4499 4936
 			print '</div>';
4500 4937
 			if (empty($hidelist))
4501 4938
 			{
@@ -4506,15 +4943,19 @@  discard block
 block discarded – undo
4506 4943
 				} else {
4507 4944
 					$newfilter.= ' AND fk_facture IS NULL AND fk_facture_line IS NULL'; // Customer discounts available
4508 4945
 				}
4509
-				if ($filter) $newfilter.=' AND ('.$filter.')';
4946
+				if ($filter) {
4947
+				    $newfilter.=' AND ('.$filter.')';
4948
+				}
4510 4949
 				$nbqualifiedlines=$this->select_remises($selected,$htmlname,$newfilter,$socid,$maxvalue);
4511 4950
 				if ($nbqualifiedlines > 0)
4512 4951
 				{
4513 4952
 					print ' &nbsp; <input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("UseLine")).'"';
4514
-					if(! empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')")
4515
-						print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4516
-					if(empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')")
4517
-						print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4953
+					if(! empty($discount_type) && $filter && $filter != "fk_invoice_supplier_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS PAID)%')") {
4954
+											print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4955
+					}
4956
+					if(empty($discount_type) && $filter && $filter != "fk_facture_source IS NULL OR (description LIKE '(DEPOSIT)%' AND description NOT LIKE '(EXCESS RECEIVED)%')") {
4957
+											print ' title="'.$langs->trans("UseCreditNoteInInvoicePayment").'"';
4958
+					}
4518 4959
 
4519 4960
 					print '>';
4520 4961
 				}
@@ -4527,14 +4968,12 @@  discard block
 block discarded – undo
4527 4968
 				print '</div>';
4528 4969
 			}
4529 4970
 			print '</form>';
4530
-		}
4531
-		else
4971
+		} else
4532 4972
 		{
4533 4973
 			if ($selected)
4534 4974
 			{
4535 4975
 				print $selected;
4536
-			}
4537
-			else
4976
+			} else
4538 4977
 			{
4539 4978
 				print "0";
4540 4979
 			}
@@ -4573,8 +5012,7 @@  discard block
 block discarded – undo
4573 5012
 			print '</td>';
4574 5013
 			print '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>';
4575 5014
 			print '</tr></table></form>';
4576
-		}
4577
-		else
5015
+		} else
4578 5016
 		{
4579 5017
 			if ($selected)
4580 5018
 			{
@@ -4617,8 +5055,7 @@  discard block
 block discarded – undo
4617 5055
 			$out.= $this->select_company($selected, $htmlname, $filter, $showempty, $showtype, $forcecombo, $events);
4618 5056
 			$out.= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">';
4619 5057
 			$out.= '</form>';
4620
-		}
4621
-		else
5058
+		} else
4622 5059
 		{
4623 5060
 			if ($selected)
4624 5061
 			{
@@ -4626,15 +5063,17 @@  discard block
 block discarded – undo
4626 5063
 				$soc = new Societe($this->db);
4627 5064
 				$soc->fetch($selected);
4628 5065
 				$out.= $soc->getNomUrl($langs);
4629
-			}
4630
-			else
5066
+			} else
4631 5067
 			{
4632 5068
 				$out.= "&nbsp;";
4633 5069
 			}
4634 5070
 		}
4635 5071
 
4636
-		if ($nooutput) return $out;
4637
-		else print $out;
5072
+		if ($nooutput) {
5073
+		    return $out;
5074
+		} else {
5075
+		    print $out;
5076
+		}
4638 5077
 	}
4639 5078
 
4640 5079
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -4667,7 +5106,10 @@  discard block
 block discarded – undo
4667 5106
 
4668 5107
 		$out='';
4669 5108
 
4670
-		if ($selected=='euro' || $selected=='euros') $selected='EUR';   // Pour compatibilite
5109
+		if ($selected=='euro' || $selected=='euros') {
5110
+		    $selected='EUR';
5111
+		}
5112
+		// Pour compatibilite
4671 5113
 
4672 5114
 		$out.= '<select class="flat maxwidth200onsmartphone minwidth300" name="'.$htmlname.'" id="'.$htmlname.'">';
4673 5115
 		foreach ($langs->cache_currencies as $code_iso => $currency)
@@ -4675,8 +5117,7 @@  discard block
 block discarded – undo
4675 5117
 			if ($selected && $selected == $code_iso)
4676 5118
 			{
4677 5119
 				$out.= '<option value="'.$code_iso.'" selected>';
4678
-			}
4679
-			else
5120
+			} else
4680 5121
 			{
4681 5122
 				$out.= '<option value="'.$code_iso.'">';
4682 5123
 			}
@@ -4685,7 +5126,9 @@  discard block
 block discarded – undo
4685 5126
 			$out.= '</option>';
4686 5127
 		}
4687 5128
 		$out.= '</select>';
4688
-		if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
5129
+		if ($user->admin) {
5130
+		    $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
5131
+		}
4689 5132
 
4690 5133
 		// Make select dynamic
4691 5134
 		include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
@@ -4715,12 +5158,16 @@  discard block
 block discarded – undo
4715 5158
 		$resql = $db->query($sql);
4716 5159
 		if ($resql)
4717 5160
 		{
4718
-			while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
5161
+			while ($obj = $db->fetch_object($resql)) {
5162
+			    $TCurrency[$obj->code] = $obj->code;
5163
+			}
4719 5164
 		}
4720 5165
 
4721 5166
 		$out='';
4722 5167
 		$out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
4723
-		if ($useempty) $out .= '<option value=""></option>';
5168
+		if ($useempty) {
5169
+		    $out .= '<option value=""></option>';
5170
+		}
4724 5171
 		// If company current currency not in table, we add it into list. Should always be available.
4725 5172
 		if (! in_array($conf->currency, $TCurrency))
4726 5173
 		{
@@ -4732,8 +5179,11 @@  discard block
 block discarded – undo
4732 5179
 			{
4733 5180
 				if (isset($TCurrency[$code_iso]))
4734 5181
 				{
4735
-					if (!empty($selected) && $selected == $code_iso) $out.= '<option value="'.$code_iso.'" selected="selected">';
4736
-					else $out.= '<option value="'.$code_iso.'">';
5182
+					if (!empty($selected) && $selected == $code_iso) {
5183
+					    $out.= '<option value="'.$code_iso.'" selected="selected">';
5184
+					} else {
5185
+					    $out.= '<option value="'.$code_iso.'">';
5186
+					}
4737 5187
 
4738 5188
 					$out.= $currency['label'];
4739 5189
 					$out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
@@ -4763,7 +5213,10 @@  discard block
 block discarded – undo
4763 5213
 		global $langs;
4764 5214
 
4765 5215
 		$num = count($this->cache_vatrates);
4766
-		if ($num > 0) return $num;    // Cache already loaded
5216
+		if ($num > 0) {
5217
+		    return $num;
5218
+		}
5219
+		// Cache already loaded
4767 5220
 
4768 5221
 		dol_syslog(__METHOD__, LOG_DEBUG);
4769 5222
 
@@ -4795,22 +5248,28 @@  discard block
 block discarded – undo
4795 5248
 					$this->cache_vatrates[$i]['label']	= $obj->taux.'%'.($obj->code?' ('.$obj->code.')':'');   // Label must contains only 0-9 , . % or *
4796 5249
 					$this->cache_vatrates[$i]['labelallrates'] = $obj->taux.'/'.($obj->localtax1?$obj->localtax1:'0').'/'.($obj->localtax2?$obj->localtax2:'0').($obj->code?' ('.$obj->code.')':'');	// Must never be used as key, only label
4797 5250
 					$positiverates='';
4798
-					if ($obj->taux) $positiverates.=($positiverates?'/':'').$obj->taux;
4799
-					if ($obj->localtax1) $positiverates.=($positiverates?'/':'').$obj->localtax1;
4800
-					if ($obj->localtax2) $positiverates.=($positiverates?'/':'').$obj->localtax2;
4801
-					if (empty($positiverates)) $positiverates='0';
5251
+					if ($obj->taux) {
5252
+					    $positiverates.=($positiverates?'/':'').$obj->taux;
5253
+					}
5254
+					if ($obj->localtax1) {
5255
+					    $positiverates.=($positiverates?'/':'').$obj->localtax1;
5256
+					}
5257
+					if ($obj->localtax2) {
5258
+					    $positiverates.=($positiverates?'/':'').$obj->localtax2;
5259
+					}
5260
+					if (empty($positiverates)) {
5261
+					    $positiverates='0';
5262
+					}
4802 5263
 					$this->cache_vatrates[$i]['labelpositiverates'] = $positiverates.($obj->code?' ('.$obj->code.')':'');	// Must never be used as key, only label
4803 5264
 				}
4804 5265
 
4805 5266
 				return $num;
4806
-			}
4807
-			else
5267
+			} else
4808 5268
 			{
4809 5269
 				$this->error = '<font class="error">'.$langs->trans("ErrorNoVATRateDefinedForSellerCountry",$country_code).'</font>';
4810 5270
 				return -1;
4811 5271
 			}
4812
-		}
4813
-		else
5272
+		} else
4814 5273
 		{
4815 5274
 			$this->error = '<font class="error">'.$this->db->error().'</font>';
4816 5275
 			return -2;
@@ -4866,8 +5325,7 @@  discard block
 block discarded – undo
4866 5325
 			if ($societe_vendeuse->id == $mysoc->id)
4867 5326
 			{
4868 5327
 				$return.= '<font class="error">'.$langs->trans("ErrorYourCountryIsNotDefined").'</div>';
4869
-			}
4870
-			else
5328
+			} else
4871 5329
 			{
4872 5330
 				$return.= '<font class="error">'.$langs->trans("ErrorSupplierCountryIsNotDefined").'</div>';
4873 5331
 			}
@@ -4883,36 +5341,41 @@  discard block
 block discarded – undo
4883 5341
 		if (is_object($societe_vendeuse))
4884 5342
 		{
4885 5343
 			$code_country="'".$societe_vendeuse->country_code."'";
4886
-		}
4887
-		else
5344
+		} else
4888 5345
 		{
4889 5346
 			$code_country="'".$mysoc->country_code."'";   // Pour compatibilite ascendente
4890 5347
 		}
4891
-		if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC))    // If option to have vat for end customer for services is on
5348
+		if (! empty($conf->global->SERVICE_ARE_ECOMMERCE_200238EC)) {
5349
+		    // If option to have vat for end customer for services is on
4892 5350
 		{
4893 5351
 			require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
5352
+		}
4894 5353
 			if (! isInEEC($societe_vendeuse) && (! is_object($societe_acheteuse) || (isInEEC($societe_acheteuse) && ! $societe_acheteuse->isACompany())))
4895 5354
 			{
4896 5355
 				// We also add the buyer
4897 5356
 				if (is_numeric($type))
4898 5357
 				{
4899
-					if ($type == 1) // We know product is a service
5358
+					if ($type == 1) {
5359
+					    // We know product is a service
4900 5360
 					{
4901 5361
 						$code_country.=",'".$societe_acheteuse->country_code."'";
4902 5362
 					}
4903
-				}
4904
-				else if (! $idprod)  // We don't know type of product
5363
+					}
5364
+				} else if (! $idprod) {
5365
+				    // We don't know type of product
4905 5366
 				{
4906 5367
 					$code_country.=",'".$societe_acheteuse->country_code."'";
4907 5368
 				}
4908
-				else
5369
+				} else
4909 5370
 				{
4910 5371
 					$prodstatic=new Product($this->db);
4911 5372
 					$prodstatic->fetch($idprod);
4912
-					if ($prodstatic->type == Product::TYPE_SERVICE)   // We know product is a service
5373
+					if ($prodstatic->type == Product::TYPE_SERVICE) {
5374
+					    // We know product is a service
4913 5375
 					{
4914 5376
 						$code_country.=",'".$societe_acheteuse->country_code."'";
4915 5377
 					}
5378
+					}
4916 5379
 				}
4917 5380
 			}
4918 5381
 		}
@@ -4932,15 +5395,20 @@  discard block
 block discarded – undo
4932 5395
 			        $defaultcode=$reg[1];
4933 5396
 			        $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
4934 5397
 		        }
4935
-				if (empty($defaulttx)) $defaultnpr=0;
5398
+				if (empty($defaulttx)) {
5399
+				    $defaultnpr=0;
5400
+				}
4936 5401
 			}
4937 5402
 
4938 5403
 			// Si taux par defaut n'a pu etre determine, on prend dernier de la liste.
4939 5404
 			// Comme ils sont tries par ordre croissant, dernier = plus eleve = taux courant
4940 5405
 			if ($defaulttx < 0 || dol_strlen($defaulttx) == 0)
4941 5406
 			{
4942
-				if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) $defaulttx = $this->cache_vatrates[$num-1]['txtva'];
4943
-				else $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
5407
+				if (empty($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
5408
+				    $defaulttx = $this->cache_vatrates[$num-1]['txtva'];
5409
+				} else {
5410
+				    $defaulttx=($conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS == 'none' ? '' : $conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS);
5411
+				}
4944 5412
 			}
4945 5413
 
4946 5414
 			// Disabled if seller is not subject to VAT
@@ -4955,32 +5423,41 @@  discard block
 block discarded – undo
4955 5423
 				}
4956 5424
 			}
4957 5425
 
4958
-			if (! $options_only) $return.= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$title.'>';
5426
+			if (! $options_only) {
5427
+			    $return.= '<select class="flat minwidth75imp" id="'.$htmlname.'" name="'.$htmlname.'"'.($disabled?' disabled':'').$title.'>';
5428
+			}
4959 5429
 
4960 5430
 			$selectedfound=false;
4961 5431
 			foreach ($this->cache_vatrates as $rate)
4962 5432
 			{
4963 5433
 				// Keep only 0 if seller is not subject to VAT
4964
-				if ($disabled && $rate['txtva'] != 0) continue;
5434
+				if ($disabled && $rate['txtva'] != 0) {
5435
+				    continue;
5436
+				}
4965 5437
 
4966 5438
 				// Define key to use into select list
4967 5439
 				$key = $rate['txtva'];
4968 5440
 				$key.= $rate['nprtva'] ? '*': '';
4969
-				if ($mode > 0 && $rate['code']) $key.=' ('.$rate['code'].')';
4970
-				if ($mode < 0) $key = $rate['rowid'];
5441
+				if ($mode > 0 && $rate['code']) {
5442
+				    $key.=' ('.$rate['code'].')';
5443
+				}
5444
+				if ($mode < 0) {
5445
+				    $key = $rate['rowid'];
5446
+				}
4971 5447
 
4972 5448
 				$return.= '<option value="'.$key.'"';
4973 5449
 				if (! $selectedfound)
4974 5450
 				{
4975
-					if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
5451
+					if ($defaultcode) {
5452
+					    // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
4976 5453
 					{
4977 5454
 						if ($defaultcode == $rate['code'])
4978 5455
 						{
4979 5456
 							$return.= ' selected';
5457
+					}
4980 5458
 							$selectedfound=true;
4981 5459
 						}
4982
-					}
4983
-					elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
5460
+					} elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
4984 5461
 			   		{
4985 5462
 			   			$return.= ' selected';
4986 5463
 			   			$selectedfound=true;
@@ -4991,8 +5468,7 @@  discard block
 block discarded – undo
4991 5468
 				if ($mysoc->country_code == 'IN' || ! empty($conf->global->MAIN_VAT_LABEL_IS_POSITIVE_RATES))
4992 5469
 				{
4993 5470
 					$return.= $rate['labelpositiverates'];
4994
-				}
4995
-				else
5471
+				} else
4996 5472
 				{
4997 5473
 					$return.= vatrate($rate['label']);
4998 5474
 				}
@@ -5002,9 +5478,10 @@  discard block
 block discarded – undo
5002 5478
 				$return.= '</option>';
5003 5479
 			}
5004 5480
 
5005
-			if (! $options_only) $return.= '</select>';
5006
-		}
5007
-		else
5481
+			if (! $options_only) {
5482
+			    $return.= '</select>';
5483
+			}
5484
+		} else
5008 5485
 		{
5009 5486
 			$return.= $this->error;
5010 5487
 		}
@@ -5078,9 +5555,15 @@  discard block
 block discarded – undo
5078 5555
 
5079 5556
 		$retstring='';
5080 5557
 
5081
-		if ($prefix=='') $prefix='re';
5082
-		if ($h == '') $h=0;
5083
-		if ($m == '') $m=0;
5558
+		if ($prefix=='') {
5559
+		    $prefix='re';
5560
+		}
5561
+		if ($h == '') {
5562
+		    $h=0;
5563
+		}
5564
+		if ($m == '') {
5565
+		    $m=0;
5566
+		}
5084 5567
 		$emptydate=0;
5085 5568
 		$emptyhours=0;
5086 5569
 		if ($empty == 1) { $emptydate=1; $emptyhours=1; }
@@ -5094,16 +5577,17 @@  discard block
 block discarded – undo
5094 5577
 		}
5095 5578
 
5096 5579
 		// Analysis of the pre-selection date
5097
-		if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg))	// deprecated usage
5580
+		if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/',$set_time,$reg)) {
5581
+		    // deprecated usage
5098 5582
 		{
5099 5583
 			// Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS'
5100 5584
 			$syear	= (! empty($reg[1])?$reg[1]:'');
5585
+		}
5101 5586
 			$smonth	= (! empty($reg[2])?$reg[2]:'');
5102 5587
 			$sday	= (! empty($reg[3])?$reg[3]:'');
5103 5588
 			$shour	= (! empty($reg[4])?$reg[4]:'');
5104 5589
 			$smin	= (! empty($reg[5])?$reg[5]:'');
5105
-		}
5106
-		elseif (strval($set_time) != '' && $set_time != -1)
5590
+		} elseif (strval($set_time) != '' && $set_time != -1)
5107 5591
 		{
5108 5592
 			// set_time est un timestamps (0 possible)
5109 5593
 			$syear = dol_print_date($set_time, "%Y");
@@ -5114,15 +5598,13 @@  discard block
 block discarded – undo
5114 5598
 				$shour = dol_print_date($set_time, "%H");
5115 5599
 				$smin = dol_print_date($set_time, "%M");
5116 5600
 				$ssec = dol_print_date($set_time, "%S");
5117
-			}
5118
-			else
5601
+			} else
5119 5602
 			{
5120 5603
 				$shour = '';
5121 5604
 				$smin = '';
5122 5605
 				$ssec = '';
5123 5606
 			}
5124
-		}
5125
-		else
5607
+		} else
5126 5608
 		{
5127 5609
 			// Date est '' ou vaut -1
5128 5610
 			$syear = '';
@@ -5132,8 +5614,12 @@  discard block
 block discarded – undo
5132 5614
 			$smin = !isset($conf->global->MAIN_DEFAULT_DATE_MIN) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_MIN;
5133 5615
 			$ssec = !isset($conf->global->MAIN_DEFAULT_DATE_SEC) ? ($h == -1 ? '59' : '') : $conf->global->MAIN_DEFAULT_DATE_SEC;
5134 5616
 		}
5135
-		if ($h == 3) $shour = '';
5136
-		if ($m == 3) $smin = '';
5617
+		if ($h == 3) {
5618
+		    $shour = '';
5619
+		}
5620
+		if ($m == 3) {
5621
+		    $smin = '';
5622
+		}
5137 5623
 
5138 5624
 		// You can set MAIN_POPUP_CALENDAR to 'eldy' or 'jquery'
5139 5625
 		$usecalendar='combo';
@@ -5170,14 +5656,14 @@  discard block
 block discarded – undo
5170 5656
 						$base=DOL_URL_ROOT.'/core/';
5171 5657
 						$retstring.=' onClick="showDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');"';
5172 5658
 						$retstring.='>'.img_object($langs->trans("SelectDate"),'calendarday','class="datecallink"').'</button>';
5659
+					} else {
5660
+					    $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5173 5661
 					}
5174
-					else $retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5175 5662
 
5176 5663
 					$retstring.='<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5177 5664
 					$retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5178 5665
 					$retstring.='<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5179
-				}
5180
-				elseif ($usecalendar == 'jquery')
5666
+				} elseif ($usecalendar == 'jquery')
5181 5667
 				{
5182 5668
 					if (! $disabled)
5183 5669
 					{
@@ -5230,8 +5716,7 @@  discard block
 block discarded – undo
5230 5716
                 		$retstring.='    });';
5231 5717
                 		$retstring.='});';
5232 5718
                 		$retstring.="</script>";*/
5233
-					}
5234
-					else
5719
+					} else
5235 5720
 					{
5236 5721
 						$retstring.='<button id="'.$prefix.'Button" type="button" class="dpInvisibleButtons">'.img_object($langs->trans("Disabled"),'calendarday','class="datecallink"').'</button>';
5237 5722
 					}
@@ -5240,8 +5725,7 @@  discard block
 block discarded – undo
5240 5725
 					$retstring.='<input type="hidden" id="'.$prefix.'day"   name="'.$prefix.'day"   value="'.$sday.'">'."\n";
5241 5726
 					$retstring.='<input type="hidden" id="'.$prefix.'month" name="'.$prefix.'month" value="'.$smonth.'">'."\n";
5242 5727
 					$retstring.='<input type="hidden" id="'.$prefix.'year"  name="'.$prefix.'year"  value="'.$syear.'">'."\n";
5243
-				}
5244
-				else
5728
+				} else
5245 5729
 				{
5246 5730
 					$retstring.="Bad value of MAIN_POPUP_CALENDAR";
5247 5731
 				}
@@ -5284,8 +5768,7 @@  discard block
 block discarded – undo
5284 5768
 				if ($emptydate || $set_time == -1)
5285 5769
 				{
5286 5770
 					$retstring.='<input'.($disabled?' disabled':'').' placeholder="'.dol_escape_htmltag($langs->trans("Year")).'" class="flat maxwidth50imp valignmiddle" type="number" min="0" max="3000" maxlength="4" id="'.$prefix.'year" name="'.$prefix.'year" value="'.$syear.'">';
5287
-				}
5288
-				else
5771
+				} else
5289 5772
 				{
5290 5773
 					$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth75imp" id="'.$prefix.'year" name="'.$prefix.'year">';
5291 5774
 
@@ -5299,30 +5782,42 @@  discard block
 block discarded – undo
5299 5782
 			}
5300 5783
 		}
5301 5784
 
5302
-		if ($d && $h) $retstring.=($h==2?'<br>':' ');
5785
+		if ($d && $h) {
5786
+		    $retstring.=($h==2?'<br>':' ');
5787
+		}
5303 5788
 
5304 5789
 		if ($h)
5305 5790
 		{
5306 5791
 			// Show hour
5307 5792
 			$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'hour':'').'" id="'.$prefix.'hour" name="'.$prefix.'hour">';
5308
-			if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
5793
+			if ($emptyhours) {
5794
+			    $retstring.='<option value="-1">&nbsp;</option>';
5795
+			}
5309 5796
 			for ($hour = 0; $hour < 24; $hour++)
5310 5797
 			{
5311
-				if (strlen($hour) < 2) $hour = "0" . $hour;
5798
+				if (strlen($hour) < 2) {
5799
+				    $hour = "0" . $hour;
5800
+				}
5312 5801
 				$retstring.='<option value="'.$hour.'"'.(($hour == $shour)?' selected':'').'>'.$hour.(empty($conf->dol_optimize_smallscreen)?'':'H').'</option>';
5313 5802
 			}
5314 5803
 			$retstring.='</select>';
5315
-			if ($m && empty($conf->dol_optimize_smallscreen)) $retstring.=":";
5804
+			if ($m && empty($conf->dol_optimize_smallscreen)) {
5805
+			    $retstring.=":";
5806
+			}
5316 5807
 		}
5317 5808
 
5318 5809
 		if ($m)
5319 5810
 		{
5320 5811
 			// Show minutes
5321 5812
 			$retstring.='<select'.($disabled?' disabled':'').' class="flat valignmiddle maxwidth50 '.($fullday?$fullday.'min':'').'" id="'.$prefix.'min" name="'.$prefix.'min">';
5322
-			if ($emptyhours) $retstring.='<option value="-1">&nbsp;</option>';
5813
+			if ($emptyhours) {
5814
+			    $retstring.='<option value="-1">&nbsp;</option>';
5815
+			}
5323 5816
 			for ($min = 0; $min < 60 ; $min++)
5324 5817
 			{
5325
-				if (strlen($min) < 2) $min = "0" . $min;
5818
+				if (strlen($min) < 2) {
5819
+				    $min = "0" . $min;
5820
+				}
5326 5821
 				$retstring.='<option value="'.$min.'"'.(($min == $smin)?' selected':'').'>'.$min.(empty($conf->dol_optimize_smallscreen)?'':'').'</option>';
5327 5822
 			}
5328 5823
 			$retstring.='</select>';
@@ -5355,18 +5850,26 @@  discard block
 block discarded – undo
5355 5850
 			// Update the hour part
5356 5851
 			if ($h)
5357 5852
 			{
5358
-				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5853
+				if ($fullday) {
5854
+				    $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5855
+				}
5359 5856
 				//$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); ';
5360 5857
 				$reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
5361
-				if ($fullday) $reset_scripts .= ' } ';
5858
+				if ($fullday) {
5859
+				    $reset_scripts .= ' } ';
5860
+				}
5362 5861
 			}
5363 5862
 			// Update the minute part
5364 5863
 			if ($m)
5365 5864
 			{
5366
-				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5865
+				if ($fullday) {
5866
+				    $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5867
+				}
5367 5868
 				//$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); ';
5368 5869
 				$reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
5369
-				if ($fullday) $reset_scripts .= ' } ';
5870
+				if ($fullday) {
5871
+				    $reset_scripts .= ' } ';
5872
+				}
5370 5873
 			}
5371 5874
 			// If reset_scripts is not empty, print the link with the reset_scripts in the onClick
5372 5875
 			if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
@@ -5391,16 +5894,24 @@  discard block
 block discarded – undo
5391 5894
 			// Update the hour part
5392 5895
 			if ($h)
5393 5896
 			{
5394
-				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5897
+				if ($fullday) {
5898
+				    $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5899
+				}
5395 5900
 				$reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date(dol_now(),'%H').'\');';
5396
-				if ($fullday) $reset_scripts .= ' } ';
5901
+				if ($fullday) {
5902
+				    $reset_scripts .= ' } ';
5903
+				}
5397 5904
 			}
5398 5905
 			// Update the minute part
5399 5906
 			if ($m)
5400 5907
 			{
5401
-				if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5908
+				if ($fullday) {
5909
+				    $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {";
5910
+				}
5402 5911
 				$reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date(dol_now(),'%M').'\');';
5403
-				if ($fullday) $reset_scripts .= ' } ';
5912
+				if ($fullday) {
5913
+				    $reset_scripts .= ' } ';
5914
+				}
5404 5915
 			}
5405 5916
 			// If reset_scripts is not empty, print the link with the reset_scripts in the onClick
5406 5917
 			if ($reset_scripts && empty($conf->dol_optimize_smallscreen))
@@ -5456,9 +5967,11 @@  discard block
 block discarded – undo
5456 5967
 		if ($typehour=='select' )
5457 5968
 		{
5458 5969
 			$retstring.='<select class="flat" id="select_'.$prefix.'hour" name="'.$prefix.'hour"'.($disabled?' disabled':'').'>';
5459
-			for ($hour = 0; $hour < 25; $hour++)	// For a duration, we allow 24 hours
5970
+			for ($hour = 0; $hour < 25; $hour++) {
5971
+			    // For a duration, we allow 24 hours
5460 5972
 			{
5461 5973
 				$retstring.='<option value="'.$hour.'"';
5974
+			}
5462 5975
 				if ($hourSelected == $hour)
5463 5976
 				{
5464 5977
 					$retstring.=" selected";
@@ -5466,19 +5979,25 @@  discard block
 block discarded – undo
5466 5979
 				$retstring.=">".$hour."</option>";
5467 5980
 			}
5468 5981
 			$retstring.="</select>";
5469
-		}
5470
-		elseif ($typehour=='text' || $typehour=='textselect')
5982
+		} elseif ($typehour=='text' || $typehour=='textselect')
5471 5983
 		{
5472 5984
 			$retstring.='<input placeholder="'.$langs->trans('HourShort').'" type="number" min="0" size="1" name="'.$prefix.'hour"'.($disabled?' disabled':'').' class="flat maxwidth50 inputhour" value="'.(($hourSelected != '')?((int) $hourSelected):'').'">';
5985
+		} else {
5986
+		    return 'BadValueForParameterTypeHour';
5473 5987
 		}
5474
-		else return 'BadValueForParameterTypeHour';
5475 5988
 
5476
-		if ($typehour!='text') $retstring.=' '.$langs->trans('HourShort');
5477
-		else $retstring.='<span class="hideonsmartphone">:</span>';
5989
+		if ($typehour!='text') {
5990
+		    $retstring.=' '.$langs->trans('HourShort');
5991
+		} else {
5992
+		    $retstring.='<span class="hideonsmartphone">:</span>';
5993
+		}
5478 5994
 
5479 5995
 		// Minutes
5480
-		if ($minunderhours) $retstring.='<br>';
5481
-		else $retstring.='<span class="hideonsmartphone">&nbsp;</span>';
5996
+		if ($minunderhours) {
5997
+		    $retstring.='<br>';
5998
+		} else {
5999
+		    $retstring.='<span class="hideonsmartphone">&nbsp;</span>';
6000
+		}
5482 6001
 
5483 6002
 		if ($typehour=='select' || $typehour=='textselect')
5484 6003
 		{
@@ -5486,21 +6005,26 @@  discard block
 block discarded – undo
5486 6005
 			for ($min = 0; $min <= 55; $min=$min+5)
5487 6006
 			{
5488 6007
 				$retstring.='<option value="'.$min.'"';
5489
-				if ($minSelected == $min) $retstring.=' selected';
6008
+				if ($minSelected == $min) {
6009
+				    $retstring.=' selected';
6010
+				}
5490 6011
 				$retstring.='>'.$min.'</option>';
5491 6012
 			}
5492 6013
 			$retstring.="</select>";
5493
-		}
5494
-		elseif ($typehour=='text' )
6014
+		} elseif ($typehour=='text' )
5495 6015
 		{
5496 6016
 			$retstring.='<input placeholder="'.$langs->trans('MinuteShort').'" type="number" min="0" size="1" name="'.$prefix.'min"'.($disabled?' disabled':'').' class="flat maxwidth50 inputminute" value="'.(($minSelected != '')?((int) $minSelected):'').'">';
5497 6017
 		}
5498 6018
 
5499
-		if ($typehour!='text') $retstring.=' '.$langs->trans('MinuteShort');
6019
+		if ($typehour!='text') {
6020
+		    $retstring.=' '.$langs->trans('MinuteShort');
6021
+		}
5500 6022
 
5501 6023
 		//$retstring.="&nbsp;";
5502 6024
 
5503
-		if (! empty($nooutput)) return $retstring;
6025
+		if (! empty($nooutput)) {
6026
+		    return $retstring;
6027
+		}
5504 6028
 
5505 6029
 		print $retstring;
5506 6030
 		return;
@@ -5547,7 +6071,9 @@  discard block
 block discarded – undo
5547 6071
 		}
5548 6072
 
5549 6073
 		$prefixforautocompletemode=$objecttmp->element;
5550
-		if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
6074
+		if ($prefixforautocompletemode == 'societe') {
6075
+		    $prefixforautocompletemode='company';
6076
+		}
5551 6077
 		$confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';	// For example COMPANY_USE_SEARCH_TO_SELECT
5552 6078
 
5553 6079
 		dol_syslog(get_class($this)."::selectForForms", LOG_DEBUG);
@@ -5564,10 +6090,11 @@  discard block
 block discarded – undo
5564 6090
 			// Activate the auto complete using ajax call.
5565 6091
 			$out.=  ajax_autocompleter($preselectedvalue, $htmlname, $urlforajaxcall, $urloption, $conf->global->$confkeyforautocompletemode, 0, array());
5566 6092
 			$out.= '<style type="text/css">.ui-autocomplete { z-index: 250; }</style>';
5567
-			if ($placeholder) $placeholder=' placeholder="'.$placeholder.'"';
6093
+			if ($placeholder) {
6094
+			    $placeholder=' placeholder="'.$placeholder.'"';
6095
+			}
5568 6096
 			$out.= '<input type="text" class="'.$morecss.'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$preselectedvalue.'"'.$placeholder.' />';
5569
-		}
5570
-		else
6097
+		} else
5571 6098
 		{
5572 6099
 			// Immediate load of all database
5573 6100
 			$out.=$this->selectForFormsList($objecttmp, $htmlname, $preselectedvalue, $showempty, $searchkey, $placeholder, $morecss, $moreparams, $forcecombo);
@@ -5598,18 +6125,26 @@  discard block
 block discarded – undo
5598 6125
 		global $conf, $langs, $user;
5599 6126
 
5600 6127
 		$prefixforautocompletemode=$objecttmp->element;
5601
-		if ($prefixforautocompletemode == 'societe') $prefixforautocompletemode='company';
6128
+		if ($prefixforautocompletemode == 'societe') {
6129
+		    $prefixforautocompletemode='company';
6130
+		}
5602 6131
 		$confkeyforautocompletemode=strtoupper($prefixforautocompletemode).'_USE_SEARCH_TO_SELECT';	// For example COMPANY_USE_SEARCH_TO_SELECT
5603 6132
 
5604 6133
 		$fieldstoshow='t.ref';
5605
-		if (! empty($objecttmp->fields))	// For object that declare it, it is better to use declared fields ( like societe, contact, ...)
6134
+		if (! empty($objecttmp->fields)) {
6135
+		    // For object that declare it, it is better to use declared fields ( like societe, contact, ...)
5606 6136
 		{
5607 6137
 			$tmpfieldstoshow='';
6138
+		}
5608 6139
 			foreach($objecttmp->fields as $key => $val)
5609 6140
 			{
5610
-				if ($val['showoncombobox']) $tmpfieldstoshow.=($tmpfieldstoshow?',':'').'t.'.$key;
6141
+				if ($val['showoncombobox']) {
6142
+				    $tmpfieldstoshow.=($tmpfieldstoshow?',':'').'t.'.$key;
6143
+				}
6144
+			}
6145
+			if ($tmpfieldstoshow) {
6146
+			    $fieldstoshow = $tmpfieldstoshow;
5611 6147
 			}
5612
-			if ($tmpfieldstoshow) $fieldstoshow = $tmpfieldstoshow;
5613 6148
 		}
5614 6149
 
5615 6150
 		$out='';
@@ -5619,18 +6154,27 @@  discard block
 block discarded – undo
5619 6154
 
5620 6155
 		// Search data
5621 6156
 		$sql = "SELECT t.rowid, ".$fieldstoshow." FROM ".MAIN_DB_PREFIX .$objecttmp->table_element." as t";
5622
-		if ($objecttmp->ismultientitymanaged == 2)
5623
-			if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
6157
+		if ($objecttmp->ismultientitymanaged == 2) {
6158
+					if (!$user->rights->societe->client->voir && !$user->societe_id) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
6159
+		}
5624 6160
 		$sql.= " WHERE 1=1";
5625
-		if(! empty($objecttmp->ismultientitymanaged)) $sql.= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
6161
+		if(! empty($objecttmp->ismultientitymanaged)) {
6162
+		    $sql.= " AND t.entity IN (".getEntity($objecttmp->table_element).")";
6163
+		}
5626 6164
 		if ($objecttmp->ismultientitymanaged == 1 && ! empty($user->societe_id))
5627 6165
 		{
5628
-			if ($objecttmp->element == 'societe') $sql.= " AND t.rowid = ".$user->societe_id;
5629
-				else $sql.= " AND t.fk_soc = ".$user->societe_id;
6166
+			if ($objecttmp->element == 'societe') {
6167
+			    $sql.= " AND t.rowid = ".$user->societe_id;
6168
+			} else {
6169
+				    $sql.= " AND t.fk_soc = ".$user->societe_id;
6170
+				}
6171
+		}
6172
+		if ($searchkey != '') {
6173
+		    $sql.=natural_search(explode(',',$fieldstoshow), $searchkey);
6174
+		}
6175
+		if ($objecttmp->ismultientitymanaged == 2) {
6176
+					if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND t.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
5630 6177
 		}
5631
-		if ($searchkey != '') $sql.=natural_search(explode(',',$fieldstoshow), $searchkey);
5632
-		if ($objecttmp->ismultientitymanaged == 2)
5633
-			if (!$user->rights->societe->client->voir && !$user->societe_id) $sql.= " AND t.rowid = sc.fk_soc AND sc.fk_user = " .$user->id;
5634 6178
 		$sql.=$this->db->order($fieldstoshow,"ASC");
5635 6179
 		//$sql.=$this->db->plimit($limit, 0);
5636 6180
 
@@ -5653,10 +6197,15 @@  discard block
 block discarded – undo
5653 6197
 			//if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
5654 6198
 			if (! empty($conf->global->$confkeyforautocompletemode))
5655 6199
 			{
5656
-				if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
5657
-				else $textifempty.=$langs->trans("All");
6200
+				if ($showempty && ! is_numeric($showempty)) {
6201
+				    $textifempty=$langs->trans($showempty);
6202
+				} else {
6203
+				    $textifempty.=$langs->trans("All");
6204
+				}
6205
+			}
6206
+			if ($showempty) {
6207
+			    $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
5658 6208
 			}
5659
-			if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
5660 6209
 
5661 6210
 			$num = $this->db->num_rows($resql);
5662 6211
 			$i = 0;
@@ -5677,32 +6226,33 @@  discard block
 block discarded – undo
5677 6226
 						if ($preselectedvalue > 0 && $preselectedvalue == $obj->rowid)
5678 6227
 						{
5679 6228
 							$out.= '<option value="'.$obj->rowid.'" selected>'.$label.'</option>';
5680
-						}
5681
-						else
6229
+						} else
5682 6230
 						{
5683 6231
 							$out.= '<option value="'.$obj->rowid.'">'.$label.'</option>';
5684 6232
 						}
5685
-					}
5686
-					else
6233
+					} else
5687 6234
 					{
5688 6235
 						array_push($outarray, array('key'=>$obj->rowid, 'value'=>$label, 'label'=>$label));
5689 6236
 					}
5690 6237
 
5691 6238
 					$i++;
5692
-					if (($i % 10) == 0) $out.="\n";
6239
+					if (($i % 10) == 0) {
6240
+					    $out.="\n";
6241
+					}
5693 6242
 				}
5694 6243
 			}
5695 6244
 
5696 6245
 			$out.= '</select>'."\n";
5697
-		}
5698
-		else
6246
+		} else
5699 6247
 		{
5700 6248
 			dol_print_error($this->db);
5701 6249
 		}
5702 6250
 
5703 6251
 		$this->result=array('nbofelement'=>$num);
5704 6252
 
5705
-		if ($outputmode) return $outarray;
6253
+		if ($outputmode) {
6254
+		    return $outarray;
6255
+		}
5706 6256
 		return $out;
5707 6257
 	}
5708 6258
 
@@ -5739,7 +6289,9 @@  discard block
 block discarded – undo
5739 6289
 		//if (preg_match('/^multi/',$htmlname)) $jsbeautify = 1;
5740 6290
 		$jsbeautify = 1;
5741 6291
 
5742
-		if ($value_as_key) $array=array_combine($array, $array);
6292
+		if ($value_as_key) {
6293
+		    $array=array_combine($array, $array);
6294
+		}
5743 6295
 
5744 6296
 		$out='';
5745 6297
 
@@ -5761,8 +6313,13 @@  discard block
 block discarded – undo
5761 6313
 		if ($show_empty)
5762 6314
 		{
5763 6315
 			$textforempty=' ';
5764
-			if (! empty($conf->use_javascript_ajax)) $textforempty='&nbsp;';	// If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
5765
-			if (! is_numeric($show_empty)) $textforempty=$show_empty;
6316
+			if (! empty($conf->use_javascript_ajax)) {
6317
+			    $textforempty='&nbsp;';
6318
+			}
6319
+			// If we use ajaxcombo, we need &nbsp; here to avoid to have an empty element that is too small.
6320
+			if (! is_numeric($show_empty)) {
6321
+			    $textforempty=$show_empty;
6322
+			}
5766 6323
 			$out.='<option class="optiongrey" '.($moreparamonempty?$moreparamonempty.' ':'').'value="'.($show_empty < 0 ? $show_empty : -1).'"'.($id == $show_empty ?' selected':'').'>'.$textforempty.'</option>'."\n";
5767 6324
 		}
5768 6325
 
@@ -5778,8 +6335,11 @@  discard block
 block discarded – undo
5778 6335
 			}
5779 6336
 
5780 6337
 			// Sort
5781
-			if ($sort == 'ASC') asort($array);
5782
-			elseif ($sort == 'DESC') arsort($array);
6338
+			if ($sort == 'ASC') {
6339
+			    asort($array);
6340
+			} elseif ($sort == 'DESC') {
6341
+			    arsort($array);
6342
+			}
5783 6343
 
5784 6344
 			foreach($array as $key => $value)
5785 6345
 			{
@@ -5796,20 +6356,32 @@  discard block
 block discarded – undo
5796 6356
 
5797 6357
 				if ($key_in_label)
5798 6358
 				{
5799
-					if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));
5800
-					else $selectOptionValue = $key.' - '.($maxlen?dol_trunc($value,$maxlen):$value);
5801
-				}
5802
-				else
6359
+					if (empty($nohtmlescape)) {
6360
+					    $selectOptionValue = dol_escape_htmltag($key.' - '.($maxlen?dol_trunc($value,$maxlen):$value));
6361
+					} else {
6362
+					    $selectOptionValue = $key.' - '.($maxlen?dol_trunc($value,$maxlen):$value);
6363
+					}
6364
+				} else
5803 6365
 				{
5804
-					if (empty($nohtmlescape)) $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);
5805
-					else $selectOptionValue = $maxlen?dol_trunc($value,$maxlen):$value;
5806
-					if ($value == '' || $value == '-') $selectOptionValue='&nbsp;';
6366
+					if (empty($nohtmlescape)) {
6367
+					    $selectOptionValue = dol_escape_htmltag($maxlen?dol_trunc($value,$maxlen):$value);
6368
+					} else {
6369
+					    $selectOptionValue = $maxlen?dol_trunc($value,$maxlen):$value;
6370
+					}
6371
+					if ($value == '' || $value == '-') {
6372
+					    $selectOptionValue='&nbsp;';
6373
+					}
5807 6374
 				}
5808 6375
 
5809 6376
 				$out.='<option value="'.$key.'"';
5810 6377
 				$out.=$style.$disabled;
5811
-				if ($id != '' && $id == $key && ! $disabled) $out.=' selected';		// To preselect a value
5812
-				if ($nohtmlescape) $out.=' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
6378
+				if ($id != '' && $id == $key && ! $disabled) {
6379
+				    $out.=' selected';
6380
+				}
6381
+				// To preselect a value
6382
+				if ($nohtmlescape) {
6383
+				    $out.=' data-html="'.dol_escape_htmltag($selectOptionValue).'"';
6384
+				}
5813 6385
 				$out.='>';
5814 6386
 				//var_dump($selectOptionValue);
5815 6387
 				$out.=$selectOptionValue;
@@ -5846,7 +6418,9 @@  discard block
 block discarded – undo
5846 6418
 		global $delayedhtmlcontent;
5847 6419
 
5848 6420
 		// TODO Use an internal dolibarr component instead of select2
5849
-		if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
6421
+		if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) {
6422
+		    return '';
6423
+		}
5850 6424
 
5851 6425
 		$out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"></select>';
5852 6426
 
@@ -5916,8 +6490,7 @@  discard block
 block discarded – undo
5916 6490
 		if ($acceptdelayedhtml)
5917 6491
 		{
5918 6492
 			$delayedhtmlcontent.=$outdelayed;
5919
-		}
5920
-		else
6493
+		} else
5921 6494
 		{
5922 6495
 			$out.=$outdelayed;
5923 6496
 		}
@@ -5948,7 +6521,9 @@  discard block
 block discarded – undo
5948 6521
 		global $delayedhtmlcontent;
5949 6522
 
5950 6523
 		// TODO Use an internal dolibarr component instead of select2
5951
-		if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) return '';
6524
+		if (empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) && ! defined('REQUIRE_JQUERY_MULTISELECT')) {
6525
+		    return '';
6526
+		}
5952 6527
 
5953 6528
 		$out='<select type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'"><option></option></select>';
5954 6529
 
@@ -6034,8 +6609,7 @@  discard block
 block discarded – undo
6034 6609
 		if ($acceptdelayedhtml)
6035 6610
 		{
6036 6611
 			$delayedhtmlcontent.=$outdelayed;
6037
-		}
6038
-		else
6612
+		} else
6039 6613
 		{
6040 6614
 			$out.=$outdelayed;
6041 6615
 		}
@@ -6080,8 +6654,7 @@  discard block
 block discarded – undo
6080 6654
 				{
6081 6655
 					$out.='	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6082 6656
 									  	return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
6083
-				}
6084
-				else
6657
+				} else
6085 6658
 				{
6086 6659
 					$out.='return record.text;';
6087 6660
 				}
@@ -6091,8 +6664,7 @@  discard block
 block discarded – undo
6091 6664
 				{
6092 6665
 					$out.='	//return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> <a href="'.DOL_URL_ROOT.'/categories/viewcat.php?type=0&id=\'+record.id+\'">\'+record.text+\'</a></span>\';
6093 6666
 									  	return \'<span><img src="'.DOL_URL_ROOT.'/theme/eldy/img/object_category.png'.'"> \'+record.text+\'</span>\';';
6094
-				}
6095
-				else
6667
+				} else
6096 6668
 				{
6097 6669
 					$out.='return record.text;';
6098 6670
 				}
@@ -6108,8 +6680,7 @@  discard block
 block discarded – undo
6108 6680
 							 	templateResult: formatSelection		/* For 4.0 */
6109 6681
 							});
6110 6682
 						});'."\n";
6111
-			}
6112
-			elseif ($addjscombo == 2)
6683
+			} elseif ($addjscombo == 2)
6113 6684
 			{
6114 6685
 				// Add other js lib
6115 6686
 				// ...
@@ -6132,7 +6703,9 @@  discard block
 block discarded – undo
6132 6703
 		$out .= '<select id="'.$htmlname.'" class="multiselect'.($morecss?' '.$morecss:'').'" multiple name="'.$htmlname.'[]"'.($moreattrib?' '.$moreattrib:'').($width?' style="width: '.(preg_match('/%/',$width)?$width:$width.'px').'"':'').'>'."\n";
6133 6704
 		if (is_array($array) && ! empty($array))
6134 6705
 		{
6135
-			if ($value_as_key) $array=array_combine($array, $array);
6706
+			if ($value_as_key) {
6707
+			    $array=array_combine($array, $array);
6708
+			}
6136 6709
 
6137 6710
 			if (! empty($array))
6138 6711
 			{
@@ -6171,7 +6744,9 @@  discard block
 block discarded – undo
6171 6744
 	{
6172 6745
 		global $conf,$langs,$user;
6173 6746
 
6174
-		if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) return '';
6747
+		if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
6748
+		    return '';
6749
+		}
6175 6750
 
6176 6751
 		$tmpvar="MAIN_SELECTEDFIELDS_".$varpage;
6177 6752
 		if (! empty($user->conf->$tmpvar))
@@ -6181,8 +6756,11 @@  discard block
 block discarded – undo
6181 6756
 			{
6182 6757
 				//var_dump($key);
6183 6758
 				//var_dump($tmparray);
6184
-				if (in_array($key, $tmparray)) $array[$key]['checked']=1;
6185
-				else $array[$key]['checked']=0;
6759
+				if (in_array($key, $tmparray)) {
6760
+				    $array[$key]['checked']=1;
6761
+				} else {
6762
+				    $array[$key]['checked']=0;
6763
+				}
6186 6764
 			}
6187 6765
 		}
6188 6766
 		//var_dump($array);
@@ -6359,42 +6937,53 @@  discard block
 block discarded – undo
6359 6937
 				// To work with non standard path
6360 6938
 				if ($objecttype == 'facture')          {
6361 6939
 					$tplpath = 'compta/'.$element;
6362
-					if (empty($conf->facture->enabled)) continue;	// Do not show if module disabled
6363
-				}
6364
-				else if ($objecttype == 'facturerec')          {
6940
+					if (empty($conf->facture->enabled)) {
6941
+					    continue;
6942
+					}
6943
+					// Do not show if module disabled
6944
+				} else if ($objecttype == 'facturerec')          {
6365 6945
 					$tplpath = 'compta/facture';
6366 6946
 					$tplname = 'linkedobjectblockForRec';
6367
-					if (empty($conf->facture->enabled)) continue;	// Do not show if module disabled
6368
-				}
6369
-				else if ($objecttype == 'propal')           {
6947
+					if (empty($conf->facture->enabled)) {
6948
+					    continue;
6949
+					}
6950
+					// Do not show if module disabled
6951
+				} else if ($objecttype == 'propal')           {
6370 6952
 					$tplpath = 'comm/'.$element;
6371
-					if (empty($conf->propal->enabled)) continue;	// Do not show if module disabled
6372
-				}
6373
-				else if ($objecttype == 'supplier_proposal')           {
6374
-					if (empty($conf->supplier_proposal->enabled)) continue;	// Do not show if module disabled
6375
-				}
6376
-				else if ($objecttype == 'shipping' || $objecttype == 'shipment') {
6953
+					if (empty($conf->propal->enabled)) {
6954
+					    continue;
6955
+					}
6956
+					// Do not show if module disabled
6957
+				} else if ($objecttype == 'supplier_proposal')           {
6958
+					if (empty($conf->supplier_proposal->enabled)) {
6959
+					    continue;
6960
+					}
6961
+					// Do not show if module disabled
6962
+				} else if ($objecttype == 'shipping' || $objecttype == 'shipment') {
6377 6963
 					$tplpath = 'expedition';
6378
-					if (empty($conf->expedition->enabled)) continue;	// Do not show if module disabled
6379
-				}
6380
-        		else if ($objecttype == 'reception') {
6964
+					if (empty($conf->expedition->enabled)) {
6965
+					    continue;
6966
+					}
6967
+					// Do not show if module disabled
6968
+				} else if ($objecttype == 'reception') {
6381 6969
         			$tplpath = 'reception';
6382
-        			if (empty($conf->reception->enabled)) continue;	// Do not show if module disabled
6383
-        		}
6384
-				else if ($objecttype == 'delivery')         {
6970
+        			if (empty($conf->reception->enabled)) {
6971
+        			    continue;
6972
+        			}
6973
+        			// Do not show if module disabled
6974
+        		} else if ($objecttype == 'delivery')         {
6385 6975
 					$tplpath = 'livraison';
6386
-					if (empty($conf->expedition->enabled)) continue;	// Do not show if module disabled
6387
-				}
6388
-				else if ($objecttype == 'invoice_supplier') {
6976
+					if (empty($conf->expedition->enabled)) {
6977
+					    continue;
6978
+					}
6979
+					// Do not show if module disabled
6980
+				} else if ($objecttype == 'invoice_supplier') {
6389 6981
 					$tplpath = 'fourn/facture';
6390
-				}
6391
-				else if ($objecttype == 'order_supplier')   {
6982
+				} else if ($objecttype == 'order_supplier')   {
6392 6983
 					$tplpath = 'fourn/commande';
6393
-				}
6394
-				else if ($objecttype == 'expensereport')   {
6984
+				} else if ($objecttype == 'expensereport')   {
6395 6985
 					$tplpath = 'expensereport';
6396
-				}
6397
-				else if ($objecttype == 'subscription')   {
6986
+				} else if ($objecttype == 'subscription')   {
6398 6987
 					$tplpath = 'adherents';
6399 6988
 				}
6400 6989
 
@@ -6406,9 +6995,11 @@  discard block
 block discarded – undo
6406 6995
 				$dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));
6407 6996
 				foreach($dirtpls as $reldir)
6408 6997
 				{
6409
-					if ($nboftypesoutput == ($nbofdifferenttypes - 1))    // No more type to show after
6998
+					if ($nboftypesoutput == ($nbofdifferenttypes - 1)) {
6999
+					    // No more type to show after
6410 7000
 					{
6411 7001
 						global $noMoreLinkedObjectBlockAfter;
7002
+					}
6412 7003
 						$noMoreLinkedObjectBlockAfter=1;
6413 7004
 					}
6414 7005
 
@@ -6457,19 +7048,25 @@  discard block
 block discarded – undo
6457 7048
 		$linktoelemlist='';
6458 7049
 		$listofidcompanytoscan='';
6459 7050
 
6460
-		if (! is_object($object->thirdparty)) $object->fetch_thirdparty();
7051
+		if (! is_object($object->thirdparty)) {
7052
+		    $object->fetch_thirdparty();
7053
+		}
6461 7054
 
6462 7055
 		$possiblelinks=array();
6463 7056
 		if (is_object($object->thirdparty) && ! empty($object->thirdparty->id) && $object->thirdparty->id > 0)
6464 7057
 		{
6465 7058
 			$listofidcompanytoscan=$object->thirdparty->id;
6466
-			if (($object->thirdparty->parent > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan.=','.$object->thirdparty->parent;
7059
+			if (($object->thirdparty->parent > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) {
7060
+			    $listofidcompanytoscan.=','.$object->thirdparty->parent;
7061
+			}
6467 7062
 			if (($object->fk_project > 0) && ! empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO))
6468 7063
 			{
6469 7064
 				include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
6470 7065
 				$tmpproject=new Project($this->db);
6471 7066
 				$tmpproject->fetch($object->fk_project);
6472
-				if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan.=','.$tmpproject->socid;
7067
+				if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) {
7068
+				    $listofidcompanytoscan.=','.$tmpproject->socid;
7069
+				}
6473 7070
 				unset($tmpproject);
6474 7071
 			}
6475 7072
 
@@ -6498,8 +7095,7 @@  discard block
 block discarded – undo
6498 7095
 			{
6499 7096
 				$possiblelinks=array_merge($possiblelinks, $hookmanager->resArray);
6500 7097
 			}
6501
-		}
6502
-		else if ($reshook > 0)
7098
+		} else if ($reshook > 0)
6503 7099
 		{
6504 7100
 			if (is_array($hookmanager->resArray) && count($hookmanager->resArray))
6505 7101
 			{
@@ -6511,7 +7107,9 @@  discard block
 block discarded – undo
6511 7107
 		{
6512 7108
 			$num = 0;
6513 7109
 
6514
-			if (empty($possiblelink['enabled'])) continue;
7110
+			if (empty($possiblelink['enabled'])) {
7111
+			    continue;
7112
+			}
6515 7113
 
6516 7114
 			if (! empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || ! in_array($key, $excludelinksto)))
6517 7115
 			{
@@ -6565,9 +7163,13 @@  discard block
 block discarded – undo
6565 7163
 				}
6566 7164
 
6567 7165
 				//$linktoelem.=($linktoelem?' &nbsp; ':'');
6568
-				if ($num > 0) $linktoelemlist.='<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">' . $langs->trans($possiblelink['label']) .' ('.$num.')</a></li>';
7166
+				if ($num > 0) {
7167
+				    $linktoelemlist.='<li><a href="#linkto'.$key.'" class="linkto dropdowncloseonclick" rel="'.$key.'">' . $langs->trans($possiblelink['label']) .' ('.$num.')</a></li>';
7168
+				}
6569 7169
 				//else $linktoelem.=$langs->trans($possiblelink['label']);
6570
-				else $linktoelemlist.='<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
7170
+				else {
7171
+				    $linktoelemlist.='<li><span class="linktodisabled">' . $langs->trans($possiblelink['label']) . ' (0)</span></li>';
7172
+				}
6571 7173
 			}
6572 7174
 		}
6573 7175
 
@@ -6583,8 +7185,7 @@  discard block
 block discarded – undo
6583 7185
     		</div>
6584 7186
     		</dd>
6585 7187
     		</dl>';
6586
-		}
6587
-		else
7188
+		} else
6588 7189
 		{
6589 7190
 			$linktoelem='';
6590 7191
 		}
@@ -6628,13 +7229,14 @@  discard block
 block discarded – undo
6628 7229
 		$disabled = ($disabled ? ' disabled' : '');
6629 7230
 
6630 7231
 		$resultyesno = '<select class="flat width75" id="'.$htmlname.'" name="'.$htmlname.'"'.$disabled.'>'."\n";
6631
-		if ($useempty) $resultyesno .= '<option value="-1"'.(($value < 0)?' selected':'').'>&nbsp;</option>'."\n";
7232
+		if ($useempty) {
7233
+		    $resultyesno .= '<option value="-1"'.(($value < 0)?' selected':'').'>&nbsp;</option>'."\n";
7234
+		}
6632 7235
 		if (("$value" == 'yes') || ($value == 1))
6633 7236
 		{
6634 7237
 			$resultyesno .= '<option value="'.$yes.'" selected>'.$langs->trans("Yes").'</option>'."\n";
6635 7238
 			$resultyesno .= '<option value="'.$no.'">'.$langs->trans("No").'</option>'."\n";
6636
-		}
6637
-		else
7239
+		} else
6638 7240
 	   {
6639 7241
 	   		$selected=(($useempty && $value != '0' && $value != 'no')?'':' selected');
6640 7242
 			$resultyesno .= '<option value="'.$yes.'">'.$langs->trans("Yes").'</option>'."\n";
@@ -6680,8 +7282,7 @@  discard block
 block discarded – undo
6680 7282
 				if ($selected == $obj->rowid)
6681 7283
 				{
6682 7284
 					print '<option value="'.$obj->rowid.'" selected>';
6683
-				}
6684
-				else
7285
+				} else
6685 7286
 				{
6686 7287
 					print '<option value="'.$obj->rowid.'">';
6687 7288
 				}
@@ -6690,8 +7291,7 @@  discard block
 block discarded – undo
6690 7291
 				$i++;
6691 7292
 			}
6692 7293
 			print "</select>";
6693
-		}
6694
-		else {
7294
+		} else {
6695 7295
 			dol_print_error($this->db);
6696 7296
 		}
6697 7297
 	}
@@ -6719,8 +7319,12 @@  discard block
 block discarded – undo
6719 7319
 		global $langs,$conf,$hookmanager;
6720 7320
 
6721 7321
 		$ret='';
6722
-		if (empty($fieldid))  $fieldid='rowid';
6723
-		if (empty($fieldref)) $fieldref='ref';
7322
+		if (empty($fieldid)) {
7323
+		    $fieldid='rowid';
7324
+		}
7325
+		if (empty($fieldref)) {
7326
+		    $fieldref='ref';
7327
+		}
6724 7328
 
6725 7329
 		// Add where from hooks
6726 7330
 		if (is_object($hookmanager))
@@ -6749,12 +7353,10 @@  discard block
 block discarded – undo
6749 7353
 			if ($conf->browser->name == 'chrome')
6750 7354
 			{
6751 7355
 				$stringforfirstkey .= ' ALT +';
6752
-			}
6753
-			elseif ($conf->browser->name == 'firefox')
7356
+			} elseif ($conf->browser->name == 'firefox')
6754 7357
 			{
6755 7358
 				$stringforfirstkey .= ' ALT + SHIFT +';
6756
-			}
6757
-			else
7359
+			} else
6758 7360
 			{
6759 7361
 				$stringforfirstkey .= ' CTL +';
6760 7362
 			}
@@ -6767,7 +7369,9 @@  discard block
 block discarded – undo
6767 7369
 		$ret.='<!-- Start banner content --><div style="vertical-align: middle">';
6768 7370
 
6769 7371
 		// Right part of banner
6770
-		if ($morehtmlright) $ret.='<div class="inline-block floatleft">'.$morehtmlright.'</div>';
7372
+		if ($morehtmlright) {
7373
+		    $ret.='<div class="inline-block floatleft">'.$morehtmlright.'</div>';
7374
+		}
6771 7375
 
6772 7376
 		if ($previous_ref || $next_ref || $morehtml)
6773 7377
 		{
@@ -6789,20 +7393,33 @@  discard block
 block discarded – undo
6789 7393
 
6790 7394
 		$parameters=array();
6791 7395
 		$reshook=$hookmanager->executeHooks('moreHtmlStatus',$parameters, $object);    // Note that $action and $object may have been modified by hook
6792
-		if (empty($reshook)) $morehtmlstatus.=$hookmanager->resPrint;
6793
-		else $morehtmlstatus=$hookmanager->resPrint;
6794
-		if ($morehtmlstatus) $ret.='<div class="statusref">'.$morehtmlstatus.'</div>';
7396
+		if (empty($reshook)) {
7397
+		    $morehtmlstatus.=$hookmanager->resPrint;
7398
+		} else {
7399
+		    $morehtmlstatus=$hookmanager->resPrint;
7400
+		}
7401
+		if ($morehtmlstatus) {
7402
+		    $ret.='<div class="statusref">'.$morehtmlstatus.'</div>';
7403
+		}
6795 7404
 
6796 7405
 		$parameters = array();
6797 7406
 		$reshook = $hookmanager->executeHooks('moreHtmlRef', $parameters, $object); // Note that $action and $object may have been modified by hook
6798
-		if (empty($reshook)) $morehtmlref.=$hookmanager->resPrint;
6799
-		elseif ($reshook > 0) $morehtmlref=$hookmanager->resPrint;
7407
+		if (empty($reshook)) {
7408
+		    $morehtmlref.=$hookmanager->resPrint;
7409
+		} elseif ($reshook > 0) {
7410
+		    $morehtmlref=$hookmanager->resPrint;
7411
+		}
6800 7412
 
6801 7413
 		// Left part of banner
6802 7414
 		if ($morehtmlleft)
6803 7415
 		{
6804
-			if ($conf->browser->layout == 'phone') $ret.='<div class="floatleft">'.$morehtmlleft.'</div>';    // class="center" to have photo in middle
6805
-			else $ret.='<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
7416
+			if ($conf->browser->layout == 'phone') {
7417
+			    $ret.='<div class="floatleft">'.$morehtmlleft.'</div>';
7418
+			}
7419
+			// class="center" to have photo in middle
7420
+			else {
7421
+			    $ret.='<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
7422
+			}
6806 7423
 		}
6807 7424
 
6808 7425
 		//if ($conf->browser->layout == 'phone') $ret.='<div class="clearboth"></div>';
@@ -6812,8 +7429,7 @@  discard block
 block discarded – undo
6812 7429
 		if ($object->element == 'societe')
6813 7430
 		{
6814 7431
 			$ret.=dol_htmlentities($object->name);
6815
-		}
6816
-		else if ($object->element == 'member')
7432
+		} else if ($object->element == 'member')
6817 7433
 		{
6818 7434
 			$ret.=$object->ref.'<br>';
6819 7435
 			$fullname=$object->getFullName($langs);
@@ -6822,24 +7438,21 @@  discard block
 block discarded – undo
6822 7438
 			} else {
6823 7439
 				$ret.= dol_htmlentities($fullname) . ((! empty($object->societe) && $object->societe != $fullname)?' ('.dol_htmlentities($object->societe).')':'');
6824 7440
 			}
6825
-		}
6826
-		else if (in_array($object->element, array('contact', 'user', 'usergroup')))
7441
+		} else if (in_array($object->element, array('contact', 'user', 'usergroup')))
6827 7442
 		{
6828 7443
 			$ret.=dol_htmlentities($object->getFullName($langs));
6829
-		}
6830
-		else if (in_array($object->element, array('action', 'agenda')))
7444
+		} else if (in_array($object->element, array('action', 'agenda')))
6831 7445
 		{
6832 7446
 			$ret.=$object->ref.'<br>'.$object->label;
6833
-		}
6834
-		else if (in_array($object->element, array('adherent_type')))
7447
+		} else if (in_array($object->element, array('adherent_type')))
6835 7448
 		{
6836 7449
 			$ret.=$object->label;
6837
-		}
6838
-		else if ($object->element == 'ecm_directories')
7450
+		} else if ($object->element == 'ecm_directories')
6839 7451
 		{
6840 7452
 			$ret.='';
7453
+		} else if ($fieldref != 'none') {
7454
+		    $ret.=dol_htmlentities($object->$fieldref);
6841 7455
 		}
6842
-		else if ($fieldref != 'none') $ret.=dol_htmlentities($object->$fieldref);
6843 7456
 
6844 7457
 
6845 7458
 		if ($morehtmlref)
@@ -6866,14 +7479,18 @@  discard block
 block discarded – undo
6866 7479
 		global $conf;
6867 7480
 
6868 7481
 		//Check if barcode is filled in the card
6869
-		if (empty($object->barcode)) return '';
7482
+		if (empty($object->barcode)) {
7483
+		    return '';
7484
+		}
6870 7485
 
6871 7486
 		// Complete object if not complete
6872 7487
 		if (empty($object->barcode_type_code) || empty($object->barcode_type_coder))
6873 7488
 		{
6874 7489
 			$result = $object->fetch_barcode();
6875 7490
 			//Check if fetch_barcode() failed
6876
-			if ($result < 1) return '<!-- ErrorFetchBarcode -->';
7491
+			if ($result < 1) {
7492
+			    return '<!-- ErrorFetchBarcode -->';
7493
+			}
6877 7494
 		}
6878 7495
 
6879 7496
 		// Barcode image
@@ -6911,70 +7528,99 @@  discard block
 block discarded – undo
6911 7528
 			$dir=$conf->societe->multidir_output[$entity];
6912 7529
 			if (! empty($object->logo))
6913 7530
 			{
6914
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini');             // getImageFileNameForSize include the thumbs
6915
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
6916
-				else $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
7531
+				if ((string) $imagesize == 'mini') {
7532
+				    $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini');
7533
+				}
7534
+				// getImageFileNameForSize include the thumbs
7535
+				else if ((string) $imagesize == 'small') {
7536
+				    $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
7537
+				} else {
7538
+				    $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
7539
+				}
6917 7540
 				$originalfile=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.$object->logo;
6918 7541
 			}
6919 7542
 			$email=$object->email;
6920
-		}
6921
-		else if ($modulepart=='contact')
7543
+		} else if ($modulepart=='contact')
6922 7544
 		{
6923 7545
 			$dir=$conf->societe->multidir_output[$entity].'/contact';
6924 7546
 			if (! empty($object->photo))
6925 7547
 			{
6926
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
6927
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
6928
-				else $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
7548
+				if ((string) $imagesize == 'mini') {
7549
+				    $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_mini');
7550
+				} else if ((string) $imagesize == 'small') {
7551
+				    $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.getImageFileNameForSize($object->photo, '_small');
7552
+				} else {
7553
+				    $file=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
7554
+				}
6929 7555
 				$originalfile=get_exdir(0, 0, 0, 0, $object, 'contact').'/photos/'.$object->photo;
6930 7556
 			}
6931 7557
 			$email=$object->email;
6932 7558
 			$capture='user';
6933
-		}
6934
-		else if ($modulepart=='userphoto')
7559
+		} else if ($modulepart=='userphoto')
6935 7560
 		{
6936 7561
 			$dir=$conf->user->dir_output;
6937 7562
 			if (! empty($object->photo))
6938 7563
 			{
6939
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_mini');
6940
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_small');
6941
-				else $file=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
7564
+				if ((string) $imagesize == 'mini') {
7565
+				    $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_mini');
7566
+				} else if ((string) $imagesize == 'small') {
7567
+				    $file=get_exdir(0, 0, 0, 0, $object, 'user').$object->id.'/'.getImageFileNameForSize($object->photo, '_small');
7568
+				} else {
7569
+				    $file=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
7570
+				}
6942 7571
 				$originalfile=get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id.'/'.$object->photo;
6943 7572
 			}
6944
-			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
7573
+			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
7574
+			    $altfile=$object->id.".jpg";
7575
+			}
7576
+			// For backward compatibility
6945 7577
 			$email=$object->email;
6946 7578
 			$capture='user';
6947
-		}
6948
-		else if ($modulepart=='memberphoto')
7579
+		} else if ($modulepart=='memberphoto')
6949 7580
 		{
6950 7581
 			$dir=$conf->adherent->dir_output;
6951 7582
 			if (! empty($object->photo))
6952 7583
 			{
6953
-				if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
6954
-				else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
6955
-				else $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
7584
+				if ((string) $imagesize == 'mini') {
7585
+				    $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
7586
+				} else if ((string) $imagesize == 'small') {
7587
+				    $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
7588
+				} else {
7589
+				    $file=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
7590
+				}
6956 7591
 				$originalfile=get_exdir(0, 0, 0, 0, $object, 'member').'photos/'.$object->photo;
6957 7592
 			}
6958
-			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
7593
+			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
7594
+			    $altfile=$object->id.".jpg";
7595
+			}
7596
+			// For backward compatibility
6959 7597
 			$email=$object->email;
6960 7598
 			$capture='user';
6961
-		}
6962
-		else
7599
+		} else
6963 7600
 		{
6964 7601
 			// Generic case to show photos
6965 7602
 			$dir=$conf->$modulepart->dir_output;
6966 7603
 			if (! empty($object->photo))
6967 7604
 			{
6968
-				if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
6969
-				else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
6970
-				else $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
7605
+				if ((string) $imagesize == 'mini') {
7606
+				    $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
7607
+				} else if ((string) $imagesize == 'small') {
7608
+				    $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
7609
+				} else {
7610
+				    $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
7611
+				}
6971 7612
 				$originalfile=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.$object->photo;
6972 7613
 			}
6973
-			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
7614
+			if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) {
7615
+			    $altfile=$object->id.".jpg";
7616
+			}
7617
+			// For backward compatibility
6974 7618
 			$email=$object->email;
6975 7619
 		}
6976 7620
 
6977
-		if ($forcecapture) $capture = $forcecapture;
7621
+		if ($forcecapture) {
7622
+		    $capture = $forcecapture;
7623
+		}
6978 7624
 
6979 7625
 		if ($dir)
6980 7626
 		{
@@ -6983,31 +7629,45 @@  discard block
 block discarded – undo
6983 7629
 				if ($addlinktofullsize)
6984 7630
 				{
6985 7631
 					$urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6986
-					if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
6987
-					else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
7632
+					if ($urladvanced) {
7633
+					    $ret.='<a href="'.$urladvanced.'">';
7634
+					} else {
7635
+					    $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
7636
+					}
6988 7637
 				}
6989 7638
 				$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($file).'&cache='.$cache.'">';
6990
-				if ($addlinktofullsize) $ret.='</a>';
6991
-			}
6992
-			else if ($altfile && file_exists($dir."/".$altfile))
7639
+				if ($addlinktofullsize) {
7640
+				    $ret.='</a>';
7641
+				}
7642
+			} else if ($altfile && file_exists($dir."/".$altfile))
6993 7643
 			{
6994 7644
 				if ($addlinktofullsize)
6995 7645
 				{
6996 7646
 					$urladvanced=getAdvancedPreviewUrl($modulepart, $originalfile, 0, '&entity='.$entity);
6997
-					if ($urladvanced) $ret.='<a href="'.$urladvanced.'">';
6998
-					else $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
7647
+					if ($urladvanced) {
7648
+					    $ret.='<a href="'.$urladvanced.'">';
7649
+					} else {
7650
+					    $ret.='<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($originalfile).'&cache='.$cache.'">';
7651
+					}
6999 7652
 				}
7000 7653
 				$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Photo alt" id="photologo'.(preg_replace('/[^a-z]/i','_',$file)).'" class="'.$cssclass.'" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$entity.'&file='.urlencode($altfile).'&cache='.$cache.'">';
7001
-				if ($addlinktofullsize) $ret.='</a>';
7002
-			}
7003
-			else
7654
+				if ($addlinktofullsize) {
7655
+				    $ret.='</a>';
7656
+				}
7657
+			} else
7004 7658
 			{
7005 7659
 				$nophoto='/public/theme/common/nophoto.png';
7006
-				if (in_array($modulepart,array('userphoto','contact')))	// For module that are "physical" users
7660
+				if (in_array($modulepart,array('userphoto','contact'))) {
7661
+				    // For module that are "physical" users
7007 7662
 				{
7008 7663
 					$nophoto='/public/theme/common/user_anonymous.png';
7009
-					if ($object->gender == 'man') $nophoto='/public/theme/common/user_man.png';
7010
-					if ($object->gender == 'woman') $nophoto='/public/theme/common/user_woman.png';
7664
+				}
7665
+					if ($object->gender == 'man') {
7666
+					    $nophoto='/public/theme/common/user_man.png';
7667
+					}
7668
+					if ($object->gender == 'woman') {
7669
+					    $nophoto='/public/theme/common/user_woman.png';
7670
+					}
7011 7671
 				}
7012 7672
 
7013 7673
 				if (! empty($conf->gravatar->enabled) && $email)
@@ -7020,8 +7680,7 @@  discard block
 block discarded – undo
7020 7680
 					//$defaultimg=urlencode(dol_buildpath($nophoto,3));
7021 7681
 					$defaultimg='mm';
7022 7682
 					$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="Gravatar avatar" title="'.$email.' Gravatar avatar" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="https://www.gravatar.com/avatar/'.dol_hash(strtolower(trim($email)),3).'?s='.$width.'&d='.$defaultimg.'">';	// gravatar need md5 hash
7023
-				}
7024
-				else
7683
+				} else
7025 7684
 				{
7026 7685
 					$ret.='<img class="photo'.$modulepart.($cssclass?' '.$cssclass:'').'" alt="No photo" '.($width?' width="'.$width.'"':'').($height?' height="'.$height.'"':'').' src="'.DOL_URL_ROOT.$nophoto.'">';
7027 7686
 				}
@@ -7029,14 +7688,19 @@  discard block
 block discarded – undo
7029 7688
 
7030 7689
 			if ($caneditfield)
7031 7690
 			{
7032
-				if ($object->photo) $ret.="<br>\n";
7691
+				if ($object->photo) {
7692
+				    $ret.="<br>\n";
7693
+				}
7033 7694
 				$ret.='<table class="nobordernopadding centpercent">';
7034
-				if ($object->photo) $ret.='<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
7695
+				if ($object->photo) {
7696
+				    $ret.='<tr><td><input type="checkbox" class="flat photodelete" name="deletephoto" id="photodelete"> '.$langs->trans("Delete").'<br><br></td></tr>';
7697
+				}
7035 7698
 				$ret.='<tr><td class="tdoverflow"><input type="file" class="flat maxwidth200onsmartphone" name="photo" id="photoinput"'.($capture?' capture="'.$capture.'"':'').'></td></tr>';
7036 7699
 				$ret.='</table>';
7037 7700
 			}
7701
+		} else {
7702
+		    dol_print_error('','Call of showphoto with wrong parameters modulepart='.$modulepart);
7038 7703
 		}
7039
-		else dol_print_error('','Call of showphoto with wrong parameters modulepart='.$modulepart);
7040 7704
 
7041 7705
 		return $ret;
7042 7706
 	}
@@ -7063,11 +7727,17 @@  discard block
 block discarded – undo
7063 7727
 		global $conf,$user,$langs;
7064 7728
 
7065 7729
 		// Permettre l'exclusion de groupes
7066
-		if (is_array($exclude))	$excludeGroups = implode("','",$exclude);
7730
+		if (is_array($exclude)) {
7731
+		    $excludeGroups = implode("','",$exclude);
7732
+		}
7067 7733
 		// Permettre l'inclusion de groupes
7068
-		if (is_array($include))	$includeGroups = implode("','",$include);
7734
+		if (is_array($include)) {
7735
+		    $includeGroups = implode("','",$include);
7736
+		}
7069 7737
 
7070
-		if (!is_array($selected)) $selected = array($selected);
7738
+		if (!is_array($selected)) {
7739
+		    $selected = array($selected);
7740
+		}
7071 7741
 
7072 7742
 		$out='';
7073 7743
 
@@ -7081,15 +7751,21 @@  discard block
 block discarded – undo
7081 7751
 		if (! empty($conf->multicompany->enabled) && $conf->entity == 1 && $user->admin && ! $user->entity)
7082 7752
 		{
7083 7753
 			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."entity as e ON e.rowid=ug.entity";
7084
-			if ($force_entity) $sql.= " WHERE ug.entity IN (0,".$force_entity.")";
7085
-			else $sql.= " WHERE ug.entity IS NOT NULL";
7086
-		}
7087
-		else
7754
+			if ($force_entity) {
7755
+			    $sql.= " WHERE ug.entity IN (0,".$force_entity.")";
7756
+			} else {
7757
+			    $sql.= " WHERE ug.entity IS NOT NULL";
7758
+			}
7759
+		} else
7088 7760
 		{
7089 7761
 			$sql.= " WHERE ug.entity IN (0,".$conf->entity.")";
7090 7762
 		}
7091
-		if (is_array($exclude) && $excludeGroups) $sql.= " AND ug.rowid NOT IN ('".$excludeGroups."')";
7092
-		if (is_array($include) && $includeGroups) $sql.= " AND ug.rowid IN ('".$includeGroups."')";
7763
+		if (is_array($exclude) && $excludeGroups) {
7764
+		    $sql.= " AND ug.rowid NOT IN ('".$excludeGroups."')";
7765
+		}
7766
+		if (is_array($include) && $includeGroups) {
7767
+		    $sql.= " AND ug.rowid IN ('".$includeGroups."')";
7768
+		}
7093 7769
 		$sql.= " ORDER BY ug.nom ASC";
7094 7770
 
7095 7771
 		dol_syslog(get_class($this)."::select_dolgroups", LOG_DEBUG);
@@ -7106,16 +7782,22 @@  discard block
 block discarded – undo
7106 7782
 			$i = 0;
7107 7783
 			if ($num)
7108 7784
 			{
7109
-				if ($show_empty && !$multiple) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'>&nbsp;</option>'."\n";
7785
+				if ($show_empty && !$multiple) {
7786
+				    $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'>&nbsp;</option>'."\n";
7787
+				}
7110 7788
 
7111 7789
 				while ($i < $num)
7112 7790
 				{
7113 7791
 					$obj = $this->db->fetch_object($resql);
7114 7792
 					$disableline=0;
7115
-					if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) $disableline=1;
7793
+					if (is_array($enableonly) && count($enableonly) && ! in_array($obj->rowid,$enableonly)) {
7794
+					    $disableline=1;
7795
+					}
7116 7796
 
7117 7797
 					$out.= '<option value="'.$obj->rowid.'"';
7118
-					if ($disableline) $out.= ' disabled';
7798
+					if ($disableline) {
7799
+					    $out.= ' disabled';
7800
+					}
7119 7801
 					if ((is_object($selected[0]) && $selected[0]->id == $obj->rowid) || (! is_object($selected[0]) && in_array($obj->rowid,$selected) ))
7120 7802
 					{
7121 7803
 						$out.= ' selected';
@@ -7131,15 +7813,15 @@  discard block
 block discarded – undo
7131 7813
 					$out.= '</option>';
7132 7814
 					$i++;
7133 7815
 				}
7134
-			}
7135
-			else
7816
+			} else
7136 7817
 			{
7137
-				if ($show_empty) $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'></option>'."\n";
7818
+				if ($show_empty) {
7819
+				    $out.= '<option value="-1"'.(in_array(-1,$selected)?' selected':'').'></option>'."\n";
7820
+				}
7138 7821
 				$out.= '<option value="" disabled>'.$langs->trans("NoUserGroupDefined").'</option>';
7139 7822
 			}
7140 7823
 			$out.= '</select>';
7141
-		}
7142
-		else
7824
+		} else
7143 7825
 		{
7144 7826
 			dol_print_error($this->db);
7145 7827
 		}
@@ -7177,7 +7859,9 @@  discard block
 block discarded – undo
7177 7859
 		global $conf, $langs;
7178 7860
 
7179 7861
 		$out='';
7180
-		if (! empty($conf->use_javascript_ajax)) $out.='<div class="inline-block checkallactions"><input type="checkbox" id="checkallactions" name="checkallactions" class="checkallactions"></div>';
7862
+		if (! empty($conf->use_javascript_ajax)) {
7863
+		    $out.='<div class="inline-block checkallactions"><input type="checkbox" id="checkallactions" name="checkallactions" class="checkallactions"></div>';
7864
+		}
7181 7865
 		$out.='<script type="text/javascript">
7182 7866
             $(document).ready(function() {
7183 7867
             	$("#checkallactions").click(function() {
@@ -7190,7 +7874,9 @@  discard block
 block discarded – undo
7190 7874
                         console.log("We uncheck all");
7191 7875
                 		$(".'.$cssclass.'").prop(\'checked\', false).trigger(\'change\');
7192 7876
                     }'."\n";
7193
-		if ($calljsfunction) $out.='if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
7877
+		if ($calljsfunction) {
7878
+		    $out.='if (typeof initCheckForSelect == \'function\') { initCheckForSelect(0); } else { console.log("No function initCheckForSelect found. Call won\'t be done."); }';
7879
+		}
7194 7880
 		$out.='         });
7195 7881
 
7196 7882
         	$(".checkforselect").change(function() {
@@ -7239,21 +7925,27 @@  discard block
 block discarded – undo
7239 7925
 
7240 7926
 		$sql = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat WHERE active = 1';
7241 7927
 		$sql.= ' AND entity IN (0,'.getEntity('exp_tax_cat').')';
7242
-		if (!empty($excludeid)) $sql.= ' AND rowid NOT IN ('.implode(',', $excludeid).')';
7928
+		if (!empty($excludeid)) {
7929
+		    $sql.= ' AND rowid NOT IN ('.implode(',', $excludeid).')';
7930
+		}
7243 7931
 		$sql.= ' ORDER BY label';
7244 7932
 
7245 7933
 		$resql = $db->query($sql);
7246 7934
 		if ($resql)
7247 7935
 		{
7248 7936
 			$out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7249
-			if ($useempty) $out.= '<option value="0">&nbsp;</option>';
7937
+			if ($useempty) {
7938
+			    $out.= '<option value="0">&nbsp;</option>';
7939
+			}
7250 7940
 
7251 7941
 			while ($obj = $db->fetch_object($resql))
7252 7942
 			{
7253 7943
 				$out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.$langs->trans($obj->label).'</option>';
7254 7944
 			}
7255 7945
 			$out.= '</select>';
7256
-			if (! empty($htmlname) && $user->admin) $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
7946
+			if (! empty($htmlname) && $user->admin) {
7947
+			    $out .= ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
7948
+			}
7257 7949
 
7258 7950
 			if (!empty($target))
7259 7951
 			{
@@ -7269,7 +7961,9 @@  discard block
 block discarded – undo
7269 7961
 								$("select[name='.$target.']").on("change", function() {
7270 7962
 									var current_val = $(this).val();
7271 7963
 									if (current_val == '.$obj->id.') {';
7272
-						if (!empty($default_selected) || !empty($selected)) $out.= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
7964
+						if (!empty($default_selected) || !empty($selected)) {
7965
+						    $out.= '$("select[name='.$htmlname.']").val("'.($default_selected > 0 ? $default_selected : $selected).'");';
7966
+						}
7273 7967
 
7274 7968
 						$out.= '
7275 7969
 										$("select[name='.$htmlname.']").change();
@@ -7305,8 +7999,7 @@  discard block
 block discarded – undo
7305 7999
 					}
7306 8000
 				}
7307 8001
 			}
7308
-		}
7309
-		else
8002
+		} else
7310 8003
 		{
7311 8004
 			dol_print_error($db);
7312 8005
 		}
@@ -7333,15 +8026,16 @@  discard block
 block discarded – undo
7333 8026
 		if ($resql)
7334 8027
 		{
7335 8028
 			$out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7336
-			if ($useempty) $out.= '<option value="0"></option>';
8029
+			if ($useempty) {
8030
+			    $out.= '<option value="0"></option>';
8031
+			}
7337 8032
 
7338 8033
 			while ($obj = $db->fetch_object($resql))
7339 8034
 			{
7340 8035
 				$out.= '<option '.($selected == $obj->rowid ? 'selected="selected"' : '').' value="'.$obj->rowid.'">'.price($obj->range_ik, 0, $langs, 1, 0).'</option>';
7341 8036
 			}
7342 8037
 			$out.= '</select>';
7343
-		}
7344
-		else
8038
+		} else
7345 8039
 		{
7346 8040
 			dol_print_error($db);
7347 8041
 		}
@@ -7370,11 +8064,17 @@  discard block
 block discarded – undo
7370 8064
 		if ($resql)
7371 8065
 		{
7372 8066
 			$out = '<select id="select_'.$htmlname.'" name="'.$htmlname.'" class="'.$htmlname.' flat minwidth75imp">';
7373
-			if ($useempty) $out.= '<option value="0"></option>';
7374
-			if ($allchoice) $out.= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
8067
+			if ($useempty) {
8068
+			    $out.= '<option value="0"></option>';
8069
+			}
8070
+			if ($allchoice) {
8071
+			    $out.= '<option value="-1">'.$langs->trans('AllExpenseReport').'</option>';
8072
+			}
7375 8073
 
7376 8074
 			$field = 'code';
7377
-			if ($useid) $field = 'id';
8075
+			if ($useid) {
8076
+			    $field = 'id';
8077
+			}
7378 8078
 
7379 8079
 			while ($obj = $db->fetch_object($resql))
7380 8080
 			{
@@ -7382,8 +8082,7 @@  discard block
 block discarded – undo
7382 8082
 				$out.= '<option '.($selected == $obj->{$field} ? 'selected="selected"' : '').' value="'.$obj->{$field}.'">'.($key != $obj->code ? $key : $obj->label).'</option>';
7383 8083
 			}
7384 8084
 			$out.= '</select>';
7385
-		}
7386
-		else
8085
+		} else
7387 8086
 		{
7388 8087
 			dol_print_error($db);
7389 8088
 		}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/comment.class.php 3 patches
Indentation   +334 added lines, -334 removed lines patch added patch discarded remove patch
@@ -21,347 +21,347 @@
 block discarded – undo
21 21
  */
22 22
 class Comment extends CommonObject
23 23
 {
24
-	/**
25
-	 * @var string ID to identify managed object
26
-	 */
27
-	public $element='comment';
24
+    /**
25
+     * @var string ID to identify managed object
26
+     */
27
+    public $element='comment';
28 28
 
29
-	/**
30
-	 * @var string Name of table without prefix where object is stored
31
-	 */
32
-	public $table_element='comment';
29
+    /**
30
+     * @var string Name of table without prefix where object is stored
31
+     */
32
+    public $table_element='comment';
33 33
 
34
-	/**
35
-	 * @var int Field with ID of parent key if this field has a parent
36
-	 */
37
-	public $fk_element ='';
34
+    /**
35
+     * @var int Field with ID of parent key if this field has a parent
36
+     */
37
+    public $fk_element ='';
38 38
 
39
-	public $element_type;
39
+    public $element_type;
40 40
 
41
-	/**
42
-	 * @var string description
43
-	 */
44
-	public $description;
41
+    /**
42
+     * @var string description
43
+     */
44
+    public $description;
45 45
 
46
-	public $tms;
46
+    public $tms;
47 47
 
48
-	public $datec;
48
+    public $datec;
49 49
 
50
-	/**
50
+    /**
51 51
      * @var int ID
52 52
      */
53
-	public $fk_user_author;
54
-
55
-	/**
56
-	 * @var int Entity
57
-	 */
58
-	public $entity;
59
-
60
-	public $import_key;
61
-
62
-	public $comments = array();
63
-
64
-	public $oldcopy;
65
-
66
-
67
-	/**
68
-	 *  Constructor
69
-	 *
70
-	 *  @param      DoliDB		$db      Database handler
71
-	 */
72
-	function __construct($db)
73
-	{
74
-		$this->db = $db;
75
-	}
76
-
77
-
78
-	/**
79
-	 *  Create into database
80
-	 *
81
-	 *  @param	User	$user        	User that create
82
-	 *  @param 	int		$notrigger	    0=launch triggers after, 1=disable triggers
83
-	 *  @return int 		        	<0 if KO, Id of created object if OK
84
-	 */
85
-	function create($user, $notrigger=0)
86
-	{
87
-		global $conf, $langs;
88
-
89
-		$error=0;
90
-
91
-		// Insert request
92
-		$sql = "INSERT INTO ".MAIN_DB_PREFIX."comment (";
93
-		$sql.= "description";
94
-		$sql.= ", datec";
95
-		$sql.= ", fk_element";
96
-		$sql.= ", element_type";
97
-		$sql.= ", fk_user_author";
98
-		$sql.= ", entity";
99
-		$sql.= ", import_key";
100
-		$sql.= ") VALUES (";
101
-		$sql.= "'".$this->db->escape($this->description)."'";
102
-		$sql.= ", ".($this->datec!=''?"'".$this->db->idate($this->datec)."'":'null');
103
-		$sql.= ", '".(isset($this->fk_element)?$this->fk_element:"null")."'";
104
-		$sql.= ", '".$this->db->escape($this->element_type)."'";
105
-		$sql.= ", '".(isset($this->fk_user_author)?$this->fk_user_author:"null")."'";
106
-		$sql.= ", ".(!empty($this->entity)?$this->entity:'1');
107
-		$sql.= ", ".(!empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null");
108
-		$sql.= ")";
109
-
110
-		//var_dump($this->db);
111
-		//echo $sql;
112
-
113
-		$this->db->begin();
114
-
115
-		dol_syslog(get_class($this)."::create", LOG_DEBUG);
116
-		$resql=$this->db->query($sql);
117
-		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
118
-
119
-		if (! $error)
120
-		{
121
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task_comment");
122
-
123
-			if (! $notrigger)
124
-			{
125
-				// Call trigger
126
-				$result=$this->call_trigger('TASK_COMMENT_CREATE',$user);
127
-				if ($result < 0) { $error++; }
128
-				// End call triggers
129
-			}
130
-		}
131
-
132
-		// Commit or rollback
133
-		if ($error)
134
-		{
135
-			foreach($this->errors as $errmsg)
136
-			{
137
-				dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
138
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
139
-			}
140
-			$this->db->rollback();
141
-			return -1*$error;
142
-		}
143
-		else
144
-		{
145
-			$this->db->commit();
146
-			return $this->id;
147
-		}
148
-	}
149
-
150
-
151
-	/**
152
-	 *  Load object in memory from database
153
-	 *
154
-	 *  @param	int		$id			Id object
155
-	 *  @param	int		$ref		ref object
156
-	 *  @return int 		        <0 if KO, 0 if not found, >0 if OK
157
-	 */
158
-	function fetch($id, $ref='')
159
-	{
160
-		global $langs;
161
-
162
-		$sql = "SELECT";
163
-		$sql.= " c.rowid,";
164
-		$sql.= " c.description,";
165
-		$sql.= " c.datec,";
166
-		$sql.= " c.tms,";
167
-		$sql.= " c.fk_element,";
168
-		$sql.= " c.element_type,";
169
-		$sql.= " c.fk_user_author,";
170
-		$sql.= " c.entity,";
171
-		$sql.= " c.import_key";
172
-		$sql.= " FROM ".MAIN_DB_PREFIX."comment as c";
173
-		$sql.= " WHERE c.rowid = ".$id;
174
-
175
-		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
176
-		$resql=$this->db->query($sql);
177
-		if ($resql)
178
-		{
179
-			$num_rows = $this->db->num_rows($resql);
180
-
181
-			if ($num_rows)
182
-			{
183
-				$obj = $this->db->fetch_object($resql);
184
-
185
-				$this->id					= $obj->rowid;
186
-				$this->description			= $obj->description;
187
-				$this->element_type			= $obj->element_type;
188
-				$this->datec				= $this->db->jdate($obj->datec);
189
-				$this->tms					= $obj->tms;
190
-				$this->fk_user_author		= $obj->fk_user_author;
191
-				$this->fk_element			= $obj->fk_element;
192
-				$this->entity				= $obj->entity;
193
-				$this->import_key			= $obj->import_key;
194
-			}
195
-
196
-			$this->db->free($resql);
197
-
198
-			if ($num_rows) return 1;
199
-			else return 0;
200
-		}
201
-		else
202
-		{
203
-			$this->error="Error ".$this->db->lasterror();
204
-			return -1;
205
-		}
206
-	}
207
-
208
-
209
-	/**
210
-	 *  Update database
211
-	 *
212
-	 *  @param	User	$user        	User that modify
213
-	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
214
-	 *  @return int			         	<=0 if KO, >0 if OK
215
-	 */
216
-	function update(User $user, $notrigger=0)
217
-	{
218
-		global $conf, $langs;
219
-		$error=0;
220
-
221
-		// Clean parameters
222
-		if (isset($this->fk_element)) $this->fk_project=(int) trim($this->fk_element);
223
-		if (isset($this->fk_user_author)) $this->fk_user_author=(int) trim($this->fk_user_author);
224
-		if (isset($this->description)) $this->description=trim($this->description);
225
-
226
-
227
-		// Update request
228
-		$sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_comment SET";
229
-		$sql.= " description=".(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").",";
230
-		$sql.= " datec=".($this->datec!=''?"'".$this->db->idate($this->datec)."'":'null').",";
231
-		$sql.= " fk_element=".(isset($this->fk_element)?$this->fk_element:"null").",";
232
-		$sql.= " element_type='".$this->db->escape($this->element_type)."',";
233
-		$sql.= " fk_user_author=".(isset($this->fk_user_author)?$this->fk_user_author:"null").",";
234
-		$sql.= " entity=".(!empty($this->entity)?$this->entity:'1').",";
235
-		$sql.= " import_key=".(!empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null");
236
-		$sql.= " WHERE rowid=".$this->id;
237
-
238
-		$this->db->begin();
239
-
240
-		dol_syslog(get_class($this)."::update", LOG_DEBUG);
241
-		$resql = $this->db->query($sql);
242
-		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
243
-
244
-		if (! $error)
245
-		{
246
-			if (! $notrigger)
247
-			{
248
-				// Call trigger
249
-				$result=$this->call_trigger('TASK_COMMENT_MODIFY',$user);
250
-				if ($result < 0) { $error++; }
251
-				// End call triggers
252
-			}
253
-		}
254
-
255
-		// Commit or rollback
256
-		if ($error)
257
-		{
258
-			foreach($this->errors as $errmsg)
259
-			{
260
-				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
261
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
262
-			}
263
-			$this->db->rollback();
264
-			return -1*$error;
265
-		}
266
-		else
267
-		{
268
-			$this->db->commit();
269
-			return 1;
270
-		}
271
-	}
272
-
273
-
274
-	/**
275
-	 *	Delete task from database
276
-	 *
277
-	 *	@param	User	$user        	User that delete
278
-	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
279
-	 *	@return	int						<0 if KO, >0 if OK
280
-	 */
281
-	function delete($user, $notrigger=0)
282
-	{
283
-		global $conf, $langs;
284
-		require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
285
-
286
-		$error=0;
287
-
288
-		$this->db->begin();
289
-
290
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."comment";
291
-		$sql.= " WHERE rowid=".$this->id;
292
-
293
-		$resql = $this->db->query($sql);
294
-		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
295
-
296
-		if (! $error)
297
-		{
298
-			if (! $notrigger)
299
-			{
300
-				// Call trigger
301
-				$result=$this->call_trigger('TASK_COMMENT_DELETE',$user);
302
-				if ($result < 0) { $error++; }
303
-				// End call triggers
304
-			}
305
-		}
306
-
307
-		// Commit or rollback
308
-		if ($error)
309
-		{
310
-			foreach($this->errors as $errmsg)
311
-			{
312
-				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
313
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
314
-			}
315
-			$this->db->rollback();
316
-			return -1*$error;
317
-		}else{
318
-			$this->db->commit();
319
-			return 1;
320
-		}
321
-	}
322
-
323
-
324
-	/**
325
-	 * Load comments linked with current task
326
-	 *
327
-	 * @param	string		$element_type		Element type
328
-	 * @param	int			$fk_element			Id of element
329
-	 * @return 	array							Comment array
330
-	 */
331
-	public function fetchAllFor($element_type, $fk_element)
332
-	{
333
-		global $db,$conf;
334
-		$this->comments = array();
335
-		if(!empty($element_type) && !empty($fk_element)) {
336
-			$sql = "SELECT";
337
-			$sql.= " c.rowid";
338
-			$sql.= " FROM ".MAIN_DB_PREFIX."comment as c";
339
-			$sql.= " WHERE c.fk_element = ".$fk_element;
340
-			$sql.= " AND c.element_type = '".$db->escape($element_type)."'";
341
-			$sql.= " AND c.entity = ".$conf->entity;
342
-			$sql.= " ORDER BY c.tms DESC";
343
-
344
-			dol_syslog(get_class($this).'::'.__METHOD__, LOG_DEBUG);
345
-			$resql=$db->query($sql);
346
-			if ($resql)
347
-			{
348
-				$num_rows = $db->num_rows($resql);
349
-				if ($num_rows > 0)
350
-				{
351
-					while($obj = $db->fetch_object($resql))
352
-					{
353
-						$comment = new self($db);
354
-						$comment->fetch($obj->rowid);
355
-						$this->comments[] = $comment;
356
-					}
357
-				}
358
-				$db->free($resql);
359
-			} else {
360
-				$this->errors[]="Error ".$this->db->lasterror();
361
-				return -1;
362
-			}
363
-		}
364
-
365
-		return count($this->comments);
366
-	}
53
+    public $fk_user_author;
54
+
55
+    /**
56
+     * @var int Entity
57
+     */
58
+    public $entity;
59
+
60
+    public $import_key;
61
+
62
+    public $comments = array();
63
+
64
+    public $oldcopy;
65
+
66
+
67
+    /**
68
+     *  Constructor
69
+     *
70
+     *  @param      DoliDB		$db      Database handler
71
+     */
72
+    function __construct($db)
73
+    {
74
+        $this->db = $db;
75
+    }
76
+
77
+
78
+    /**
79
+     *  Create into database
80
+     *
81
+     *  @param	User	$user        	User that create
82
+     *  @param 	int		$notrigger	    0=launch triggers after, 1=disable triggers
83
+     *  @return int 		        	<0 if KO, Id of created object if OK
84
+     */
85
+    function create($user, $notrigger=0)
86
+    {
87
+        global $conf, $langs;
88
+
89
+        $error=0;
90
+
91
+        // Insert request
92
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."comment (";
93
+        $sql.= "description";
94
+        $sql.= ", datec";
95
+        $sql.= ", fk_element";
96
+        $sql.= ", element_type";
97
+        $sql.= ", fk_user_author";
98
+        $sql.= ", entity";
99
+        $sql.= ", import_key";
100
+        $sql.= ") VALUES (";
101
+        $sql.= "'".$this->db->escape($this->description)."'";
102
+        $sql.= ", ".($this->datec!=''?"'".$this->db->idate($this->datec)."'":'null');
103
+        $sql.= ", '".(isset($this->fk_element)?$this->fk_element:"null")."'";
104
+        $sql.= ", '".$this->db->escape($this->element_type)."'";
105
+        $sql.= ", '".(isset($this->fk_user_author)?$this->fk_user_author:"null")."'";
106
+        $sql.= ", ".(!empty($this->entity)?$this->entity:'1');
107
+        $sql.= ", ".(!empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null");
108
+        $sql.= ")";
109
+
110
+        //var_dump($this->db);
111
+        //echo $sql;
112
+
113
+        $this->db->begin();
114
+
115
+        dol_syslog(get_class($this)."::create", LOG_DEBUG);
116
+        $resql=$this->db->query($sql);
117
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
118
+
119
+        if (! $error)
120
+        {
121
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task_comment");
122
+
123
+            if (! $notrigger)
124
+            {
125
+                // Call trigger
126
+                $result=$this->call_trigger('TASK_COMMENT_CREATE',$user);
127
+                if ($result < 0) { $error++; }
128
+                // End call triggers
129
+            }
130
+        }
131
+
132
+        // Commit or rollback
133
+        if ($error)
134
+        {
135
+            foreach($this->errors as $errmsg)
136
+            {
137
+                dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
138
+                $this->error.=($this->error?', '.$errmsg:$errmsg);
139
+            }
140
+            $this->db->rollback();
141
+            return -1*$error;
142
+        }
143
+        else
144
+        {
145
+            $this->db->commit();
146
+            return $this->id;
147
+        }
148
+    }
149
+
150
+
151
+    /**
152
+     *  Load object in memory from database
153
+     *
154
+     *  @param	int		$id			Id object
155
+     *  @param	int		$ref		ref object
156
+     *  @return int 		        <0 if KO, 0 if not found, >0 if OK
157
+     */
158
+    function fetch($id, $ref='')
159
+    {
160
+        global $langs;
161
+
162
+        $sql = "SELECT";
163
+        $sql.= " c.rowid,";
164
+        $sql.= " c.description,";
165
+        $sql.= " c.datec,";
166
+        $sql.= " c.tms,";
167
+        $sql.= " c.fk_element,";
168
+        $sql.= " c.element_type,";
169
+        $sql.= " c.fk_user_author,";
170
+        $sql.= " c.entity,";
171
+        $sql.= " c.import_key";
172
+        $sql.= " FROM ".MAIN_DB_PREFIX."comment as c";
173
+        $sql.= " WHERE c.rowid = ".$id;
174
+
175
+        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
176
+        $resql=$this->db->query($sql);
177
+        if ($resql)
178
+        {
179
+            $num_rows = $this->db->num_rows($resql);
180
+
181
+            if ($num_rows)
182
+            {
183
+                $obj = $this->db->fetch_object($resql);
184
+
185
+                $this->id					= $obj->rowid;
186
+                $this->description			= $obj->description;
187
+                $this->element_type			= $obj->element_type;
188
+                $this->datec				= $this->db->jdate($obj->datec);
189
+                $this->tms					= $obj->tms;
190
+                $this->fk_user_author		= $obj->fk_user_author;
191
+                $this->fk_element			= $obj->fk_element;
192
+                $this->entity				= $obj->entity;
193
+                $this->import_key			= $obj->import_key;
194
+            }
195
+
196
+            $this->db->free($resql);
197
+
198
+            if ($num_rows) return 1;
199
+            else return 0;
200
+        }
201
+        else
202
+        {
203
+            $this->error="Error ".$this->db->lasterror();
204
+            return -1;
205
+        }
206
+    }
207
+
208
+
209
+    /**
210
+     *  Update database
211
+     *
212
+     *  @param	User	$user        	User that modify
213
+     *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
214
+     *  @return int			         	<=0 if KO, >0 if OK
215
+     */
216
+    function update(User $user, $notrigger=0)
217
+    {
218
+        global $conf, $langs;
219
+        $error=0;
220
+
221
+        // Clean parameters
222
+        if (isset($this->fk_element)) $this->fk_project=(int) trim($this->fk_element);
223
+        if (isset($this->fk_user_author)) $this->fk_user_author=(int) trim($this->fk_user_author);
224
+        if (isset($this->description)) $this->description=trim($this->description);
225
+
226
+
227
+        // Update request
228
+        $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_comment SET";
229
+        $sql.= " description=".(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").",";
230
+        $sql.= " datec=".($this->datec!=''?"'".$this->db->idate($this->datec)."'":'null').",";
231
+        $sql.= " fk_element=".(isset($this->fk_element)?$this->fk_element:"null").",";
232
+        $sql.= " element_type='".$this->db->escape($this->element_type)."',";
233
+        $sql.= " fk_user_author=".(isset($this->fk_user_author)?$this->fk_user_author:"null").",";
234
+        $sql.= " entity=".(!empty($this->entity)?$this->entity:'1').",";
235
+        $sql.= " import_key=".(!empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null");
236
+        $sql.= " WHERE rowid=".$this->id;
237
+
238
+        $this->db->begin();
239
+
240
+        dol_syslog(get_class($this)."::update", LOG_DEBUG);
241
+        $resql = $this->db->query($sql);
242
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
243
+
244
+        if (! $error)
245
+        {
246
+            if (! $notrigger)
247
+            {
248
+                // Call trigger
249
+                $result=$this->call_trigger('TASK_COMMENT_MODIFY',$user);
250
+                if ($result < 0) { $error++; }
251
+                // End call triggers
252
+            }
253
+        }
254
+
255
+        // Commit or rollback
256
+        if ($error)
257
+        {
258
+            foreach($this->errors as $errmsg)
259
+            {
260
+                dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
261
+                $this->error.=($this->error?', '.$errmsg:$errmsg);
262
+            }
263
+            $this->db->rollback();
264
+            return -1*$error;
265
+        }
266
+        else
267
+        {
268
+            $this->db->commit();
269
+            return 1;
270
+        }
271
+    }
272
+
273
+
274
+    /**
275
+     *	Delete task from database
276
+     *
277
+     *	@param	User	$user        	User that delete
278
+     *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
279
+     *	@return	int						<0 if KO, >0 if OK
280
+     */
281
+    function delete($user, $notrigger=0)
282
+    {
283
+        global $conf, $langs;
284
+        require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
285
+
286
+        $error=0;
287
+
288
+        $this->db->begin();
289
+
290
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."comment";
291
+        $sql.= " WHERE rowid=".$this->id;
292
+
293
+        $resql = $this->db->query($sql);
294
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
295
+
296
+        if (! $error)
297
+        {
298
+            if (! $notrigger)
299
+            {
300
+                // Call trigger
301
+                $result=$this->call_trigger('TASK_COMMENT_DELETE',$user);
302
+                if ($result < 0) { $error++; }
303
+                // End call triggers
304
+            }
305
+        }
306
+
307
+        // Commit or rollback
308
+        if ($error)
309
+        {
310
+            foreach($this->errors as $errmsg)
311
+            {
312
+                dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
313
+                $this->error.=($this->error?', '.$errmsg:$errmsg);
314
+            }
315
+            $this->db->rollback();
316
+            return -1*$error;
317
+        }else{
318
+            $this->db->commit();
319
+            return 1;
320
+        }
321
+    }
322
+
323
+
324
+    /**
325
+     * Load comments linked with current task
326
+     *
327
+     * @param	string		$element_type		Element type
328
+     * @param	int			$fk_element			Id of element
329
+     * @return 	array							Comment array
330
+     */
331
+    public function fetchAllFor($element_type, $fk_element)
332
+    {
333
+        global $db,$conf;
334
+        $this->comments = array();
335
+        if(!empty($element_type) && !empty($fk_element)) {
336
+            $sql = "SELECT";
337
+            $sql.= " c.rowid";
338
+            $sql.= " FROM ".MAIN_DB_PREFIX."comment as c";
339
+            $sql.= " WHERE c.fk_element = ".$fk_element;
340
+            $sql.= " AND c.element_type = '".$db->escape($element_type)."'";
341
+            $sql.= " AND c.entity = ".$conf->entity;
342
+            $sql.= " ORDER BY c.tms DESC";
343
+
344
+            dol_syslog(get_class($this).'::'.__METHOD__, LOG_DEBUG);
345
+            $resql=$db->query($sql);
346
+            if ($resql)
347
+            {
348
+                $num_rows = $db->num_rows($resql);
349
+                if ($num_rows > 0)
350
+                {
351
+                    while($obj = $db->fetch_object($resql))
352
+                    {
353
+                        $comment = new self($db);
354
+                        $comment->fetch($obj->rowid);
355
+                        $this->comments[] = $comment;
356
+                    }
357
+                }
358
+                $db->free($resql);
359
+            } else {
360
+                $this->errors[]="Error ".$this->db->lasterror();
361
+                return -1;
362
+            }
363
+        }
364
+
365
+        return count($this->comments);
366
+    }
367 367
 }
Please login to merge, or discard this patch.
Spacing   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -24,17 +24,17 @@  discard block
 block discarded – undo
24 24
 	/**
25 25
 	 * @var string ID to identify managed object
26 26
 	 */
27
-	public $element='comment';
27
+	public $element = 'comment';
28 28
 
29 29
 	/**
30 30
 	 * @var string Name of table without prefix where object is stored
31 31
 	 */
32
-	public $table_element='comment';
32
+	public $table_element = 'comment';
33 33
 
34 34
 	/**
35 35
 	 * @var int Field with ID of parent key if this field has a parent
36 36
 	 */
37
-	public $fk_element ='';
37
+	public $fk_element = '';
38 38
 
39 39
 	public $element_type;
40 40
 
@@ -82,30 +82,30 @@  discard block
 block discarded – undo
82 82
 	 *  @param 	int		$notrigger	    0=launch triggers after, 1=disable triggers
83 83
 	 *  @return int 		        	<0 if KO, Id of created object if OK
84 84
 	 */
85
-	function create($user, $notrigger=0)
85
+	function create($user, $notrigger = 0)
86 86
 	{
87 87
 		global $conf, $langs;
88 88
 
89
-		$error=0;
89
+		$error = 0;
90 90
 
91 91
 		// Insert request
92 92
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."comment (";
93
-		$sql.= "description";
94
-		$sql.= ", datec";
95
-		$sql.= ", fk_element";
96
-		$sql.= ", element_type";
97
-		$sql.= ", fk_user_author";
98
-		$sql.= ", entity";
99
-		$sql.= ", import_key";
100
-		$sql.= ") VALUES (";
101
-		$sql.= "'".$this->db->escape($this->description)."'";
102
-		$sql.= ", ".($this->datec!=''?"'".$this->db->idate($this->datec)."'":'null');
103
-		$sql.= ", '".(isset($this->fk_element)?$this->fk_element:"null")."'";
104
-		$sql.= ", '".$this->db->escape($this->element_type)."'";
105
-		$sql.= ", '".(isset($this->fk_user_author)?$this->fk_user_author:"null")."'";
106
-		$sql.= ", ".(!empty($this->entity)?$this->entity:'1');
107
-		$sql.= ", ".(!empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null");
108
-		$sql.= ")";
93
+		$sql .= "description";
94
+		$sql .= ", datec";
95
+		$sql .= ", fk_element";
96
+		$sql .= ", element_type";
97
+		$sql .= ", fk_user_author";
98
+		$sql .= ", entity";
99
+		$sql .= ", import_key";
100
+		$sql .= ") VALUES (";
101
+		$sql .= "'".$this->db->escape($this->description)."'";
102
+		$sql .= ", ".($this->datec != '' ? "'".$this->db->idate($this->datec)."'" : 'null');
103
+		$sql .= ", '".(isset($this->fk_element) ? $this->fk_element : "null")."'";
104
+		$sql .= ", '".$this->db->escape($this->element_type)."'";
105
+		$sql .= ", '".(isset($this->fk_user_author) ? $this->fk_user_author : "null")."'";
106
+		$sql .= ", ".(!empty($this->entity) ? $this->entity : '1');
107
+		$sql .= ", ".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
108
+		$sql .= ")";
109 109
 
110 110
 		//var_dump($this->db);
111 111
 		//echo $sql;
@@ -113,17 +113,17 @@  discard block
 block discarded – undo
113 113
 		$this->db->begin();
114 114
 
115 115
 		dol_syslog(get_class($this)."::create", LOG_DEBUG);
116
-		$resql=$this->db->query($sql);
117
-		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
116
+		$resql = $this->db->query($sql);
117
+		if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
118 118
 
119
-		if (! $error)
119
+		if (!$error)
120 120
 		{
121 121
 			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."projet_task_comment");
122 122
 
123
-			if (! $notrigger)
123
+			if (!$notrigger)
124 124
 			{
125 125
 				// Call trigger
126
-				$result=$this->call_trigger('TASK_COMMENT_CREATE',$user);
126
+				$result = $this->call_trigger('TASK_COMMENT_CREATE', $user);
127 127
 				if ($result < 0) { $error++; }
128 128
 				// End call triggers
129 129
 			}
@@ -132,13 +132,13 @@  discard block
 block discarded – undo
132 132
 		// Commit or rollback
133 133
 		if ($error)
134 134
 		{
135
-			foreach($this->errors as $errmsg)
135
+			foreach ($this->errors as $errmsg)
136 136
 			{
137 137
 				dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
138
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
138
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
139 139
 			}
140 140
 			$this->db->rollback();
141
-			return -1*$error;
141
+			return -1 * $error;
142 142
 		}
143 143
 		else
144 144
 		{
@@ -155,25 +155,25 @@  discard block
 block discarded – undo
155 155
 	 *  @param	int		$ref		ref object
156 156
 	 *  @return int 		        <0 if KO, 0 if not found, >0 if OK
157 157
 	 */
158
-	function fetch($id, $ref='')
158
+	function fetch($id, $ref = '')
159 159
 	{
160 160
 		global $langs;
161 161
 
162 162
 		$sql = "SELECT";
163
-		$sql.= " c.rowid,";
164
-		$sql.= " c.description,";
165
-		$sql.= " c.datec,";
166
-		$sql.= " c.tms,";
167
-		$sql.= " c.fk_element,";
168
-		$sql.= " c.element_type,";
169
-		$sql.= " c.fk_user_author,";
170
-		$sql.= " c.entity,";
171
-		$sql.= " c.import_key";
172
-		$sql.= " FROM ".MAIN_DB_PREFIX."comment as c";
173
-		$sql.= " WHERE c.rowid = ".$id;
163
+		$sql .= " c.rowid,";
164
+		$sql .= " c.description,";
165
+		$sql .= " c.datec,";
166
+		$sql .= " c.tms,";
167
+		$sql .= " c.fk_element,";
168
+		$sql .= " c.element_type,";
169
+		$sql .= " c.fk_user_author,";
170
+		$sql .= " c.entity,";
171
+		$sql .= " c.import_key";
172
+		$sql .= " FROM ".MAIN_DB_PREFIX."comment as c";
173
+		$sql .= " WHERE c.rowid = ".$id;
174 174
 
175 175
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
176
-		$resql=$this->db->query($sql);
176
+		$resql = $this->db->query($sql);
177 177
 		if ($resql)
178 178
 		{
179 179
 			$num_rows = $this->db->num_rows($resql);
@@ -182,14 +182,14 @@  discard block
 block discarded – undo
182 182
 			{
183 183
 				$obj = $this->db->fetch_object($resql);
184 184
 
185
-				$this->id					= $obj->rowid;
186
-				$this->description			= $obj->description;
187
-				$this->element_type			= $obj->element_type;
188
-				$this->datec				= $this->db->jdate($obj->datec);
189
-				$this->tms					= $obj->tms;
190
-				$this->fk_user_author		= $obj->fk_user_author;
185
+				$this->id = $obj->rowid;
186
+				$this->description = $obj->description;
187
+				$this->element_type = $obj->element_type;
188
+				$this->datec = $this->db->jdate($obj->datec);
189
+				$this->tms = $obj->tms;
190
+				$this->fk_user_author = $obj->fk_user_author;
191 191
 				$this->fk_element			= $obj->fk_element;
192
-				$this->entity				= $obj->entity;
192
+				$this->entity = $obj->entity;
193 193
 				$this->import_key			= $obj->import_key;
194 194
 			}
195 195
 
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 		}
201 201
 		else
202 202
 		{
203
-			$this->error="Error ".$this->db->lasterror();
203
+			$this->error = "Error ".$this->db->lasterror();
204 204
 			return -1;
205 205
 		}
206 206
 	}
@@ -213,40 +213,40 @@  discard block
 block discarded – undo
213 213
 	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
214 214
 	 *  @return int			         	<=0 if KO, >0 if OK
215 215
 	 */
216
-	function update(User $user, $notrigger=0)
216
+	function update(User $user, $notrigger = 0)
217 217
 	{
218 218
 		global $conf, $langs;
219
-		$error=0;
219
+		$error = 0;
220 220
 
221 221
 		// Clean parameters
222
-		if (isset($this->fk_element)) $this->fk_project=(int) trim($this->fk_element);
223
-		if (isset($this->fk_user_author)) $this->fk_user_author=(int) trim($this->fk_user_author);
224
-		if (isset($this->description)) $this->description=trim($this->description);
222
+		if (isset($this->fk_element)) $this->fk_project = (int) trim($this->fk_element);
223
+		if (isset($this->fk_user_author)) $this->fk_user_author = (int) trim($this->fk_user_author);
224
+		if (isset($this->description)) $this->description = trim($this->description);
225 225
 
226 226
 
227 227
 		// Update request
228 228
 		$sql = "UPDATE ".MAIN_DB_PREFIX."projet_task_comment SET";
229
-		$sql.= " description=".(isset($this->description)?"'".$this->db->escape($this->description)."'":"null").",";
230
-		$sql.= " datec=".($this->datec!=''?"'".$this->db->idate($this->datec)."'":'null').",";
231
-		$sql.= " fk_element=".(isset($this->fk_element)?$this->fk_element:"null").",";
232
-		$sql.= " element_type='".$this->db->escape($this->element_type)."',";
233
-		$sql.= " fk_user_author=".(isset($this->fk_user_author)?$this->fk_user_author:"null").",";
234
-		$sql.= " entity=".(!empty($this->entity)?$this->entity:'1').",";
235
-		$sql.= " import_key=".(!empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":"null");
236
-		$sql.= " WHERE rowid=".$this->id;
229
+		$sql .= " description=".(isset($this->description) ? "'".$this->db->escape($this->description)."'" : "null").",";
230
+		$sql .= " datec=".($this->datec != '' ? "'".$this->db->idate($this->datec)."'" : 'null').",";
231
+		$sql .= " fk_element=".(isset($this->fk_element) ? $this->fk_element : "null").",";
232
+		$sql .= " element_type='".$this->db->escape($this->element_type)."',";
233
+		$sql .= " fk_user_author=".(isset($this->fk_user_author) ? $this->fk_user_author : "null").",";
234
+		$sql .= " entity=".(!empty($this->entity) ? $this->entity : '1').",";
235
+		$sql .= " import_key=".(!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
236
+		$sql .= " WHERE rowid=".$this->id;
237 237
 
238 238
 		$this->db->begin();
239 239
 
240 240
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
241 241
 		$resql = $this->db->query($sql);
242
-		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
242
+		if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
243 243
 
244
-		if (! $error)
244
+		if (!$error)
245 245
 		{
246
-			if (! $notrigger)
246
+			if (!$notrigger)
247 247
 			{
248 248
 				// Call trigger
249
-				$result=$this->call_trigger('TASK_COMMENT_MODIFY',$user);
249
+				$result = $this->call_trigger('TASK_COMMENT_MODIFY', $user);
250 250
 				if ($result < 0) { $error++; }
251 251
 				// End call triggers
252 252
 			}
@@ -255,13 +255,13 @@  discard block
 block discarded – undo
255 255
 		// Commit or rollback
256 256
 		if ($error)
257 257
 		{
258
-			foreach($this->errors as $errmsg)
258
+			foreach ($this->errors as $errmsg)
259 259
 			{
260 260
 				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
261
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
261
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
262 262
 			}
263 263
 			$this->db->rollback();
264
-			return -1*$error;
264
+			return -1 * $error;
265 265
 		}
266 266
 		else
267 267
 		{
@@ -278,27 +278,27 @@  discard block
 block discarded – undo
278 278
 	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
279 279
 	 *	@return	int						<0 if KO, >0 if OK
280 280
 	 */
281
-	function delete($user, $notrigger=0)
281
+	function delete($user, $notrigger = 0)
282 282
 	{
283 283
 		global $conf, $langs;
284
-		require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
284
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
285 285
 
286
-		$error=0;
286
+		$error = 0;
287 287
 
288 288
 		$this->db->begin();
289 289
 
290 290
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."comment";
291
-		$sql.= " WHERE rowid=".$this->id;
291
+		$sql .= " WHERE rowid=".$this->id;
292 292
 
293 293
 		$resql = $this->db->query($sql);
294
-		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
294
+		if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
295 295
 
296
-		if (! $error)
296
+		if (!$error)
297 297
 		{
298
-			if (! $notrigger)
298
+			if (!$notrigger)
299 299
 			{
300 300
 				// Call trigger
301
-				$result=$this->call_trigger('TASK_COMMENT_DELETE',$user);
301
+				$result = $this->call_trigger('TASK_COMMENT_DELETE', $user);
302 302
 				if ($result < 0) { $error++; }
303 303
 				// End call triggers
304 304
 			}
@@ -307,14 +307,14 @@  discard block
 block discarded – undo
307 307
 		// Commit or rollback
308 308
 		if ($error)
309 309
 		{
310
-			foreach($this->errors as $errmsg)
310
+			foreach ($this->errors as $errmsg)
311 311
 			{
312 312
 				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
313
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
313
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
314 314
 			}
315 315
 			$this->db->rollback();
316
-			return -1*$error;
317
-		}else{
316
+			return -1 * $error;
317
+		} else {
318 318
 			$this->db->commit();
319 319
 			return 1;
320 320
 		}
@@ -330,25 +330,25 @@  discard block
 block discarded – undo
330 330
 	 */
331 331
 	public function fetchAllFor($element_type, $fk_element)
332 332
 	{
333
-		global $db,$conf;
333
+		global $db, $conf;
334 334
 		$this->comments = array();
335
-		if(!empty($element_type) && !empty($fk_element)) {
335
+		if (!empty($element_type) && !empty($fk_element)) {
336 336
 			$sql = "SELECT";
337
-			$sql.= " c.rowid";
338
-			$sql.= " FROM ".MAIN_DB_PREFIX."comment as c";
339
-			$sql.= " WHERE c.fk_element = ".$fk_element;
340
-			$sql.= " AND c.element_type = '".$db->escape($element_type)."'";
341
-			$sql.= " AND c.entity = ".$conf->entity;
342
-			$sql.= " ORDER BY c.tms DESC";
337
+			$sql .= " c.rowid";
338
+			$sql .= " FROM ".MAIN_DB_PREFIX."comment as c";
339
+			$sql .= " WHERE c.fk_element = ".$fk_element;
340
+			$sql .= " AND c.element_type = '".$db->escape($element_type)."'";
341
+			$sql .= " AND c.entity = ".$conf->entity;
342
+			$sql .= " ORDER BY c.tms DESC";
343 343
 
344 344
 			dol_syslog(get_class($this).'::'.__METHOD__, LOG_DEBUG);
345
-			$resql=$db->query($sql);
345
+			$resql = $db->query($sql);
346 346
 			if ($resql)
347 347
 			{
348 348
 				$num_rows = $db->num_rows($resql);
349 349
 				if ($num_rows > 0)
350 350
 				{
351
-					while($obj = $db->fetch_object($resql))
351
+					while ($obj = $db->fetch_object($resql))
352 352
 					{
353 353
 						$comment = new self($db);
354 354
 						$comment->fetch($obj->rowid);
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 				}
358 358
 				$db->free($resql);
359 359
 			} else {
360
-				$this->errors[]="Error ".$this->db->lasterror();
360
+				$this->errors[] = "Error ".$this->db->lasterror();
361 361
 				return -1;
362 362
 			}
363 363
 		}
Please login to merge, or discard this patch.
Braces   +18 added lines, -12 removed lines patch added patch discarded remove patch
@@ -139,8 +139,7 @@  discard block
 block discarded – undo
139 139
 			}
140 140
 			$this->db->rollback();
141 141
 			return -1*$error;
142
-		}
143
-		else
142
+		} else
144 143
 		{
145 144
 			$this->db->commit();
146 145
 			return $this->id;
@@ -195,10 +194,12 @@  discard block
 block discarded – undo
195 194
 
196 195
 			$this->db->free($resql);
197 196
 
198
-			if ($num_rows) return 1;
199
-			else return 0;
200
-		}
201
-		else
197
+			if ($num_rows) {
198
+			    return 1;
199
+			} else {
200
+			    return 0;
201
+			}
202
+		} else
202 203
 		{
203 204
 			$this->error="Error ".$this->db->lasterror();
204 205
 			return -1;
@@ -219,9 +220,15 @@  discard block
 block discarded – undo
219 220
 		$error=0;
220 221
 
221 222
 		// Clean parameters
222
-		if (isset($this->fk_element)) $this->fk_project=(int) trim($this->fk_element);
223
-		if (isset($this->fk_user_author)) $this->fk_user_author=(int) trim($this->fk_user_author);
224
-		if (isset($this->description)) $this->description=trim($this->description);
223
+		if (isset($this->fk_element)) {
224
+		    $this->fk_project=(int) trim($this->fk_element);
225
+		}
226
+		if (isset($this->fk_user_author)) {
227
+		    $this->fk_user_author=(int) trim($this->fk_user_author);
228
+		}
229
+		if (isset($this->description)) {
230
+		    $this->description=trim($this->description);
231
+		}
225 232
 
226 233
 
227 234
 		// Update request
@@ -262,8 +269,7 @@  discard block
 block discarded – undo
262 269
 			}
263 270
 			$this->db->rollback();
264 271
 			return -1*$error;
265
-		}
266
-		else
272
+		} else
267 273
 		{
268 274
 			$this->db->commit();
269 275
 			return 1;
@@ -314,7 +320,7 @@  discard block
 block discarded – undo
314 320
 			}
315 321
 			$this->db->rollback();
316 322
 			return -1*$error;
317
-		}else{
323
+		} else{
318 324
 			$this->db->commit();
319 325
 			return 1;
320 326
 		}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formactions.class.php 3 patches
Indentation   +143 added lines, -143 removed lines patch added patch discarded remove patch
@@ -35,15 +35,15 @@  discard block
 block discarded – undo
35 35
     public $db;
36 36
 
37 37
     /**
38
-	 * @var string Error code (or message)
39
-	 */
40
-	public $error='';
38
+     * @var string Error code (or message)
39
+     */
40
+    public $error='';
41 41
 
42 42
 
43 43
     /**
44
-	 *	Constructor
45
-	 *
46
-	 *  @param		DoliDB		$db      Database handler
44
+     *	Constructor
45
+     *
46
+     *  @param		DoliDB		$db      Database handler
47 47
      */
48 48
     function __construct($db)
49 49
     {
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
             '50' => $langs->trans("ActionRunningShort"),
76 76
             '100' => $langs->trans("ActionDoneShort")
77 77
         );
78
-		// +ActionUncomplete
78
+        // +ActionUncomplete
79 79
 
80 80
         if (! empty($conf->use_javascript_ajax))
81 81
         {
@@ -127,8 +127,8 @@  discard block
 block discarded – undo
127 127
         }
128 128
         if (! empty($conf->use_javascript_ajax) || $onlyselect)
129 129
         {
130
-        	//var_dump($selected);
131
-        	if ($selected == 'done') $selected='100';
130
+            //var_dump($selected);
131
+            if ($selected == 'done') $selected='100';
132 132
             print '<select '.($canedit?'':'disabled ').'name="'.$htmlname.'" id="select'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'">';
133 133
             if ($showempty) print '<option value=""'.($selected == ''?' selected':'').'></option>';
134 134
             foreach($listofstatus as $key => $val)
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
                 print '<option value="'.$key.'"'.(($selected == $key && strlen($selected) == strlen($key)) || (($selected > 0 && $selected < 100) && $key == '50') ? ' selected' : '').'>'.$val.'</option>';
137 137
                 if ($key == '50' && $onlyselect == 2)
138 138
                 {
139
-                	print '<option value="todo"'.($selected == 'todo' ? ' selected' : '').'>'.$langs->trans("ActionUncomplete").' ('.$langs->trans("ActionsToDoShort")."+".$langs->trans("ActionRunningShort").')</option>';
139
+                    print '<option value="todo"'.($selected == 'todo' ? ' selected' : '').'>'.$langs->trans("ActionUncomplete").' ('.$langs->trans("ActionsToDoShort")."+".$langs->trans("ActionRunningShort").')</option>';
140 140
                 }
141 141
             }
142 142
             print '</select>';
@@ -144,12 +144,12 @@  discard block
 block discarded – undo
144 144
 
145 145
             if (empty($onlyselect))
146 146
             {
147
-	            print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat hideifna" value="'.($selected>=0?$selected:'').'" size="2"'.($canedit&&($selected>=0)?'':' disabled').'>';
148
-    	        print '<span class="hideonsmartphone hideifna">%</span>';
147
+                print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat hideifna" value="'.($selected>=0?$selected:'').'" size="2"'.($canedit&&($selected>=0)?'':' disabled').'>';
148
+                print '<span class="hideonsmartphone hideifna">%</span>';
149 149
             }
150 150
         }
151 151
         else
152
-		{
152
+        {
153 153
             print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat" value="'.($selected>=0?$selected:'').'" size="2"'.($canedit?'':' disabled').'>%';
154 154
         }
155 155
     }
@@ -179,18 +179,18 @@  discard block
 block discarded – undo
179 179
         $sortorder='DESC,DESC';
180 180
 
181 181
         $listofactions=ActionComm::getActions($this->db, $socid, $object->id, $typeelement, '', $sortfield, $sortorder, ($max?($max+1):0));
182
-		if (! is_array($listofactions)) dol_print_error($this->db,'FailedToGetActions');
182
+        if (! is_array($listofactions)) dol_print_error($this->db,'FailedToGetActions');
183 183
 
184 184
         $num = count($listofactions);
185 185
         if ($num || $forceshowtitle)
186 186
         {
187
-        	if ($typeelement == 'invoice')               $title=$langs->trans('ActionsOnBill');
188
-        	elseif ($typeelement == 'invoice_supplier' || $typeelement == 'supplier_invoice') $title=$langs->trans('ActionsOnBill');
189
-        	elseif ($typeelement == 'propal')            $title=$langs->trans('ActionsOnPropal');
190
-        	elseif ($typeelement == 'supplier_proposal') $title=$langs->trans('ActionsOnSupplierProposal');
191
-        	elseif ($typeelement == 'order')             $title=$langs->trans('ActionsOnOrder');
192
-        	elseif ($typeelement == 'order_supplier' || $typeelement == 'supplier_order')   $title=$langs->trans('ActionsOnOrder');
193
-        	elseif ($typeelement == 'shipping')          $title=$langs->trans('ActionsOnShipping');
187
+            if ($typeelement == 'invoice')               $title=$langs->trans('ActionsOnBill');
188
+            elseif ($typeelement == 'invoice_supplier' || $typeelement == 'supplier_invoice') $title=$langs->trans('ActionsOnBill');
189
+            elseif ($typeelement == 'propal')            $title=$langs->trans('ActionsOnPropal');
190
+            elseif ($typeelement == 'supplier_proposal') $title=$langs->trans('ActionsOnSupplierProposal');
191
+            elseif ($typeelement == 'order')             $title=$langs->trans('ActionsOnOrder');
192
+            elseif ($typeelement == 'order_supplier' || $typeelement == 'supplier_order')   $title=$langs->trans('ActionsOnOrder');
193
+            elseif ($typeelement == 'shipping')          $title=$langs->trans('ActionsOnShipping');
194 194
             elseif ($typeelement == 'fichinter')         $title=$langs->trans('ActionsOnFicheInter');
195 195
             elseif ($typeelement == 'project')           $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
196 196
             elseif ($typeelement == 'task')              $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
@@ -203,111 +203,111 @@  discard block
 block discarded – undo
203 203
             if ($typeelement == 'project') $projectid = $object->id;
204 204
 
205 205
             $newcardbutton='';
206
-			if (! empty($conf->agenda->enabled))
207
-			{
208
-				$newcardbutton = '<a class="butActionNew" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.dol_print_date(dol_now(),'dayhourlog').'&origin='.$typeelement.'&originid='.$object->id.($object->socid>0?'&socid='.$object->socid:($socid>0?'&socid='.$socid:'')).($projectid>0?'&projectid='.$projectid:'').'&backtopage='.urlencode($urlbacktopage).'"><span class="valignmiddle">'.$langs->trans("AddEvent").'</span>';
209
-				$newcardbutton.= '<span class="fa fa-plus-circle valignmiddle"></span>';
210
-				$newcardbutton.= '</a>';
211
-			}
212
-
213
-        	print '<!-- formactions->showactions -->'."\n";
214
-        	print load_fiche_titre($title, $newcardbutton, '', 0, 0, '', $morehtmlright);
215
-
216
-        	$page=0; $param='';
217
-
218
-        	$total = 0;
219
-
220
-        	print '<div class="div-table-responsive-no-min">';
221
-        	print '<table class="noborder'.($morecss?' '.$morecss:'').'" width="100%">';
222
-        	print '<tr class="liste_titre">';
223
-        	print getTitleFieldOfList('Ref',   0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
224
-        	print getTitleFieldOfList('By',    0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
225
-        	print getTitleFieldOfList('Type',  0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
226
-        	print getTitleFieldOfList('Title', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
227
-        	print getTitleFieldOfList('Date',  0, $_SERVER["PHP_SELF"], 'a.datep', $page, $param, 'align="center"', $sortfield, $sortorder, '', 1);
228
-        	print getTitleFieldOfList('',      0, $_SERVER["PHP_SELF"], '', $page, $param, 'align="right"', $sortfield, $sortorder, '', 1);
229
-        	print '</tr>';
230
-        	print "\n";
231
-
232
-        	$userstatic = new User($this->db);
233
-
234
-        	if (count($listofactions))
235
-        	{
236
-	        	$cursorevent = 0;
237
-	        	foreach($listofactions as $action)
238
-	        	{
239
-	        		if ($max && $cursorevent >= $max) break;
240
-
241
-	        		$ref=$action->getNomUrl(1,-1);
242
-	        		$label=$action->getNomUrl(0,38);
243
-
244
-	        		print '<tr class="oddeven">';
245
-	        		// Ref
246
-					print '<td>'.$ref.'</td>';
247
-					// Onwer
248
-	        		print '<td>';
249
-	        		if (! empty($action->userownerid))
250
-	        		{
251
-	        			$userstatic->fetch($action->userownerid);	// TODO Introduce a cache on users fetched
252
-	        			print $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, '', '');
253
-	        		}
254
-	        		print '</td>';
255
-					// Type
256
-	        		print '<td>';
257
-					$imgpicto='';
258
-					if (! empty($conf->global->AGENDA_USE_EVENT_TYPE))
259
-					{
260
-						if ($action->type_picto) $imgpicto=img_picto('', $action->type_picto);
261
-						else {
262
-							if ($action->type_code == 'AC_RDV')       $imgpicto=img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' ';
263
-							elseif ($action->type_code == 'AC_TEL')   $imgpicto=img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' ';
264
-							elseif ($action->type_code == 'AC_FAX')   $imgpicto=img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' ';
265
-							elseif ($action->type_code == 'AC_EMAIL') $imgpicto=img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' ';
266
-							elseif ($action->type_code == 'AC_INT')   $imgpicto=img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' ';
267
-							elseif (! preg_match('/_AUTO/', $action->type_code)) $imgpicto=img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' ';
268
-						}
269
-					}
270
-					print $imgpicto;
271
-	        		print $action->type_short ? $action->type_short : $action->type;
272
-	        		print '</td>';
273
-	        		// Label
274
-	        		print '<td>'.$label.'</td>';
275
-	        		// Date
276
-	        		print '<td align="center">'.dol_print_date($action->datep, 'dayhour', 'tzuserrel');
277
-	        		if ($action->datef)
278
-	        		{
279
-		        		$tmpa=dol_getdate($action->datep);
280
-		        		$tmpb=dol_getdate($action->datef);
281
-		        		if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year'])
282
-		        		{
283
-		        			if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) print '-'.dol_print_date($action->datef, 'hour', 'tzuserrel');
284
-		        		}
285
-		        		else print '-'.dol_print_date($action->datef, 'dayhour', 'tzuserrel');
286
-	        		}
287
-	        		print '</td>';
288
-	        		print '<td align="right">';
289
-	        		if (! empty($action->author->id))
290
-	        		{
291
-	        			print $action->getLibStatut(3);
292
-	        		}
293
-	        		print '</td>';
294
-	        		print '</tr>';
295
-
296
-	        		$cursorevent++;
297
-	        	}
298
-        	}
299
-        	else
300
-        	{
301
-        		print '<tr class="oddeven"><td colspan="6" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
302
-        	}
303
-
304
-        	if ($max && $num > $max)
305
-        	{
306
-        		print '<tr class="oddeven"><td colspan="6" class="opacitymedium">'.$langs->trans("More").'...</td></tr>';
307
-        	}
308
-
309
-        	print '</table>';
310
-        	print '</div>';
206
+            if (! empty($conf->agenda->enabled))
207
+            {
208
+                $newcardbutton = '<a class="butActionNew" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.dol_print_date(dol_now(),'dayhourlog').'&origin='.$typeelement.'&originid='.$object->id.($object->socid>0?'&socid='.$object->socid:($socid>0?'&socid='.$socid:'')).($projectid>0?'&projectid='.$projectid:'').'&backtopage='.urlencode($urlbacktopage).'"><span class="valignmiddle">'.$langs->trans("AddEvent").'</span>';
209
+                $newcardbutton.= '<span class="fa fa-plus-circle valignmiddle"></span>';
210
+                $newcardbutton.= '</a>';
211
+            }
212
+
213
+            print '<!-- formactions->showactions -->'."\n";
214
+            print load_fiche_titre($title, $newcardbutton, '', 0, 0, '', $morehtmlright);
215
+
216
+            $page=0; $param='';
217
+
218
+            $total = 0;
219
+
220
+            print '<div class="div-table-responsive-no-min">';
221
+            print '<table class="noborder'.($morecss?' '.$morecss:'').'" width="100%">';
222
+            print '<tr class="liste_titre">';
223
+            print getTitleFieldOfList('Ref',   0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
224
+            print getTitleFieldOfList('By',    0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
225
+            print getTitleFieldOfList('Type',  0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
226
+            print getTitleFieldOfList('Title', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
227
+            print getTitleFieldOfList('Date',  0, $_SERVER["PHP_SELF"], 'a.datep', $page, $param, 'align="center"', $sortfield, $sortorder, '', 1);
228
+            print getTitleFieldOfList('',      0, $_SERVER["PHP_SELF"], '', $page, $param, 'align="right"', $sortfield, $sortorder, '', 1);
229
+            print '</tr>';
230
+            print "\n";
231
+
232
+            $userstatic = new User($this->db);
233
+
234
+            if (count($listofactions))
235
+            {
236
+                $cursorevent = 0;
237
+                foreach($listofactions as $action)
238
+                {
239
+                    if ($max && $cursorevent >= $max) break;
240
+
241
+                    $ref=$action->getNomUrl(1,-1);
242
+                    $label=$action->getNomUrl(0,38);
243
+
244
+                    print '<tr class="oddeven">';
245
+                    // Ref
246
+                    print '<td>'.$ref.'</td>';
247
+                    // Onwer
248
+                    print '<td>';
249
+                    if (! empty($action->userownerid))
250
+                    {
251
+                        $userstatic->fetch($action->userownerid);	// TODO Introduce a cache on users fetched
252
+                        print $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, '', '');
253
+                    }
254
+                    print '</td>';
255
+                    // Type
256
+                    print '<td>';
257
+                    $imgpicto='';
258
+                    if (! empty($conf->global->AGENDA_USE_EVENT_TYPE))
259
+                    {
260
+                        if ($action->type_picto) $imgpicto=img_picto('', $action->type_picto);
261
+                        else {
262
+                            if ($action->type_code == 'AC_RDV')       $imgpicto=img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' ';
263
+                            elseif ($action->type_code == 'AC_TEL')   $imgpicto=img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' ';
264
+                            elseif ($action->type_code == 'AC_FAX')   $imgpicto=img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' ';
265
+                            elseif ($action->type_code == 'AC_EMAIL') $imgpicto=img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' ';
266
+                            elseif ($action->type_code == 'AC_INT')   $imgpicto=img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' ';
267
+                            elseif (! preg_match('/_AUTO/', $action->type_code)) $imgpicto=img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' ';
268
+                        }
269
+                    }
270
+                    print $imgpicto;
271
+                    print $action->type_short ? $action->type_short : $action->type;
272
+                    print '</td>';
273
+                    // Label
274
+                    print '<td>'.$label.'</td>';
275
+                    // Date
276
+                    print '<td align="center">'.dol_print_date($action->datep, 'dayhour', 'tzuserrel');
277
+                    if ($action->datef)
278
+                    {
279
+                        $tmpa=dol_getdate($action->datep);
280
+                        $tmpb=dol_getdate($action->datef);
281
+                        if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year'])
282
+                        {
283
+                            if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) print '-'.dol_print_date($action->datef, 'hour', 'tzuserrel');
284
+                        }
285
+                        else print '-'.dol_print_date($action->datef, 'dayhour', 'tzuserrel');
286
+                    }
287
+                    print '</td>';
288
+                    print '<td align="right">';
289
+                    if (! empty($action->author->id))
290
+                    {
291
+                        print $action->getLibStatut(3);
292
+                    }
293
+                    print '</td>';
294
+                    print '</tr>';
295
+
296
+                    $cursorevent++;
297
+                }
298
+            }
299
+            else
300
+            {
301
+                print '<tr class="oddeven"><td colspan="6" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
302
+            }
303
+
304
+            if ($max && $num > $max)
305
+            {
306
+                print '<tr class="oddeven"><td colspan="6" class="opacitymedium">'.$langs->trans("More").'...</td></tr>';
307
+            }
308
+
309
+            print '</table>';
310
+            print '</div>';
311 311
         }
312 312
 
313 313
         return $num;
@@ -338,27 +338,27 @@  discard block
 block discarded – undo
338 338
         require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
339 339
         $caction=new CActionComm($this->db);
340 340
 
341
-       	// Suggest a list with manual events or all auto events
342
-       	$arraylist=$caction->liste_array(1, 'code', $excludetype, $onlyautoornot);
343
-       	array_unshift($arraylist,'&nbsp;');     // Add empty line at start
344
-       	//asort($arraylist);
341
+            // Suggest a list with manual events or all auto events
342
+            $arraylist=$caction->liste_array(1, 'code', $excludetype, $onlyautoornot);
343
+            array_unshift($arraylist,'&nbsp;');     // Add empty line at start
344
+            //asort($arraylist);
345 345
 
346
-       	if ($selected == 'manual') $selected='AC_OTH';
347
-       	if ($selected == 'auto')   $selected='AC_OTH_AUTO';
346
+            if ($selected == 'manual') $selected='AC_OTH';
347
+            if ($selected == 'auto')   $selected='AC_OTH_AUTO';
348 348
 
349
-       	if (! empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) unset($arraylist['AC_OTH_AUTO']);
349
+            if (! empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) unset($arraylist['AC_OTH_AUTO']);
350 350
 
351
-       	$out='';
351
+            $out='';
352 352
 
353
-		if (! empty($multiselect))
354
-		{
355
-	        if (!is_array($selected) && !empty($selected)) $selected = explode(',', $selected);
356
-			$out.=$form->multiselectarray($htmlname, $arraylist, $selected, 0, 0, 'centpercent', 0, 0);
357
-		}
358
-		else
359
-		{
360
-			$out.=$form->selectarray($htmlname, $arraylist, $selected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth200', 1);
361
-		}
353
+        if (! empty($multiselect))
354
+        {
355
+            if (!is_array($selected) && !empty($selected)) $selected = explode(',', $selected);
356
+            $out.=$form->multiselectarray($htmlname, $arraylist, $selected, 0, 0, 'centpercent', 0, 0);
357
+        }
358
+        else
359
+        {
360
+            $out.=$form->selectarray($htmlname, $arraylist, $selected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth200', 1);
361
+        }
362 362
 
363 363
         if ($user->admin && empty($onlyautoornot) && $hideinfohelp <= 0)
364 364
         {
Please login to merge, or discard this patch.
Spacing   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
     /**
38 38
 	 * @var string Error code (or message)
39 39
 	 */
40
-	public $error='';
40
+	public $error = '';
41 41
 
42 42
 
43 43
     /**
@@ -64,10 +64,10 @@  discard block
 block discarded – undo
64 64
      *  @param  string  $morecss        More css on select field
65 65
      * 	@return	void
66 66
      */
67
-    function form_select_status_action($formname, $selected, $canedit=1, $htmlname='complete', $showempty=0, $onlyselect=0, $morecss='maxwidth100')
67
+    function form_select_status_action($formname, $selected, $canedit = 1, $htmlname = 'complete', $showempty = 0, $onlyselect = 0, $morecss = 'maxwidth100')
68 68
     {
69 69
         // phpcs:enable
70
-        global $langs,$conf;
70
+        global $langs, $conf;
71 71
 
72 72
         $listofstatus = array(
73 73
             '-1' => $langs->trans("ActionNotApplicable"),
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
         );
78 78
 		// +ActionUncomplete
79 79
 
80
-        if (! empty($conf->use_javascript_ajax))
80
+        if (!empty($conf->use_javascript_ajax))
81 81
         {
82 82
             print "\n";
83 83
             print "<script type=\"text/javascript\">
@@ -98,7 +98,7 @@  discard block
 block discarded – undo
98 98
                 function select_status() {
99 99
                     var defaultvalue = $('#select' + htmlname).val();
100 100
                     var percentage = $('input[name=percentage]');
101
-                    var selected = '".(isset($selected)?$selected:'')."';
101
+                    var selected = '".(isset($selected) ? $selected : '')."';
102 102
                     var value = (selected>0?selected:(defaultvalue>=0?defaultvalue:''));
103 103
 
104 104
                     percentage.val(value);
@@ -125,13 +125,13 @@  discard block
 block discarded – undo
125 125
                 }
126 126
                 </script>\n";
127 127
         }
128
-        if (! empty($conf->use_javascript_ajax) || $onlyselect)
128
+        if (!empty($conf->use_javascript_ajax) || $onlyselect)
129 129
         {
130 130
         	//var_dump($selected);
131
-        	if ($selected == 'done') $selected='100';
132
-            print '<select '.($canedit?'':'disabled ').'name="'.$htmlname.'" id="select'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'">';
133
-            if ($showempty) print '<option value=""'.($selected == ''?' selected':'').'></option>';
134
-            foreach($listofstatus as $key => $val)
131
+        	if ($selected == 'done') $selected = '100';
132
+            print '<select '.($canedit ? '' : 'disabled ').'name="'.$htmlname.'" id="select'.$htmlname.'" class="flat'.($morecss ? ' '.$morecss : '').'">';
133
+            if ($showempty) print '<option value=""'.($selected == '' ? ' selected' : '').'></option>';
134
+            foreach ($listofstatus as $key => $val)
135 135
             {
136 136
                 print '<option value="'.$key.'"'.(($selected == $key && strlen($selected) == strlen($key)) || (($selected > 0 && $selected < 100) && $key == '50') ? ' selected' : '').'>'.$val.'</option>';
137 137
                 if ($key == '50' && $onlyselect == 2)
@@ -140,17 +140,17 @@  discard block
 block discarded – undo
140 140
                 }
141 141
             }
142 142
             print '</select>';
143
-            if ($selected == 0 || $selected == 100) $canedit=0;
143
+            if ($selected == 0 || $selected == 100) $canedit = 0;
144 144
 
145 145
             if (empty($onlyselect))
146 146
             {
147
-	            print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat hideifna" value="'.($selected>=0?$selected:'').'" size="2"'.($canedit&&($selected>=0)?'':' disabled').'>';
147
+	            print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat hideifna" value="'.($selected >= 0 ? $selected : '').'" size="2"'.($canedit && ($selected >= 0) ? '' : ' disabled').'>';
148 148
     	        print '<span class="hideonsmartphone hideifna">%</span>';
149 149
             }
150 150
         }
151 151
         else
152 152
 		{
153
-            print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat" value="'.($selected>=0?$selected:'').'" size="2"'.($canedit?'':' disabled').'>%';
153
+            print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat" value="'.($selected >= 0 ? $selected : '').'" size="2"'.($canedit ? '' : ' disabled').'>%';
154 154
         }
155 155
     }
156 156
 
@@ -168,64 +168,64 @@  discard block
 block discarded – undo
168 168
      *  @param	string	$morehtmlright			More html text on right of title line
169 169
      *	@return	int								<0 if KO, >=0 if OK
170 170
      */
171
-    function showactions($object, $typeelement, $socid=0, $forceshowtitle=0, $morecss='listactions', $max=0, $moreparambacktopage='', $morehtmlright='')
171
+    function showactions($object, $typeelement, $socid = 0, $forceshowtitle = 0, $morecss = 'listactions', $max = 0, $moreparambacktopage = '', $morehtmlright = '')
172 172
     {
173
-        global $langs,$conf,$user;
173
+        global $langs, $conf, $user;
174 174
         global $bc;
175 175
 
176 176
         require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
177 177
 
178
-        $sortfield='a.datep,a.id';
179
-        $sortorder='DESC,DESC';
178
+        $sortfield = 'a.datep,a.id';
179
+        $sortorder = 'DESC,DESC';
180 180
 
181
-        $listofactions=ActionComm::getActions($this->db, $socid, $object->id, $typeelement, '', $sortfield, $sortorder, ($max?($max+1):0));
182
-		if (! is_array($listofactions)) dol_print_error($this->db,'FailedToGetActions');
181
+        $listofactions = ActionComm::getActions($this->db, $socid, $object->id, $typeelement, '', $sortfield, $sortorder, ($max ? ($max + 1) : 0));
182
+		if (!is_array($listofactions)) dol_print_error($this->db, 'FailedToGetActions');
183 183
 
184 184
         $num = count($listofactions);
185 185
         if ($num || $forceshowtitle)
186 186
         {
187
-        	if ($typeelement == 'invoice')               $title=$langs->trans('ActionsOnBill');
188
-        	elseif ($typeelement == 'invoice_supplier' || $typeelement == 'supplier_invoice') $title=$langs->trans('ActionsOnBill');
189
-        	elseif ($typeelement == 'propal')            $title=$langs->trans('ActionsOnPropal');
190
-        	elseif ($typeelement == 'supplier_proposal') $title=$langs->trans('ActionsOnSupplierProposal');
191
-        	elseif ($typeelement == 'order')             $title=$langs->trans('ActionsOnOrder');
192
-        	elseif ($typeelement == 'order_supplier' || $typeelement == 'supplier_order')   $title=$langs->trans('ActionsOnOrder');
193
-        	elseif ($typeelement == 'shipping')          $title=$langs->trans('ActionsOnShipping');
194
-            elseif ($typeelement == 'fichinter')         $title=$langs->trans('ActionsOnFicheInter');
195
-            elseif ($typeelement == 'project')           $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
196
-            elseif ($typeelement == 'task')              $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
197
-            elseif ($typeelement == 'member')            $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
198
-            else $title=$langs->trans("LatestLinkedEvents", $max?$max:'');
199
-
200
-            $urlbacktopage=$_SERVER['PHP_SELF'].'?id='.$object->id.($moreparambacktopage?'&'.$moreparambacktopage:'');
187
+        	if ($typeelement == 'invoice')               $title = $langs->trans('ActionsOnBill');
188
+        	elseif ($typeelement == 'invoice_supplier' || $typeelement == 'supplier_invoice') $title = $langs->trans('ActionsOnBill');
189
+        	elseif ($typeelement == 'propal')            $title = $langs->trans('ActionsOnPropal');
190
+        	elseif ($typeelement == 'supplier_proposal') $title = $langs->trans('ActionsOnSupplierProposal');
191
+        	elseif ($typeelement == 'order')             $title = $langs->trans('ActionsOnOrder');
192
+        	elseif ($typeelement == 'order_supplier' || $typeelement == 'supplier_order')   $title = $langs->trans('ActionsOnOrder');
193
+        	elseif ($typeelement == 'shipping')          $title = $langs->trans('ActionsOnShipping');
194
+            elseif ($typeelement == 'fichinter')         $title = $langs->trans('ActionsOnFicheInter');
195
+            elseif ($typeelement == 'project')           $title = $langs->trans('LatestLinkedEvents', $max ? $max : '');
196
+            elseif ($typeelement == 'task')              $title = $langs->trans('LatestLinkedEvents', $max ? $max : '');
197
+            elseif ($typeelement == 'member')            $title = $langs->trans('LatestLinkedEvents', $max ? $max : '');
198
+            else $title = $langs->trans("LatestLinkedEvents", $max ? $max : '');
199
+
200
+            $urlbacktopage = $_SERVER['PHP_SELF'].'?id='.$object->id.($moreparambacktopage ? '&'.$moreparambacktopage : '');
201 201
 
202 202
             $projectid = $object->fk_project;
203 203
             if ($typeelement == 'project') $projectid = $object->id;
204 204
 
205
-            $newcardbutton='';
206
-			if (! empty($conf->agenda->enabled))
205
+            $newcardbutton = '';
206
+			if (!empty($conf->agenda->enabled))
207 207
 			{
208
-				$newcardbutton = '<a class="butActionNew" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.dol_print_date(dol_now(),'dayhourlog').'&origin='.$typeelement.'&originid='.$object->id.($object->socid>0?'&socid='.$object->socid:($socid>0?'&socid='.$socid:'')).($projectid>0?'&projectid='.$projectid:'').'&backtopage='.urlencode($urlbacktopage).'"><span class="valignmiddle">'.$langs->trans("AddEvent").'</span>';
209
-				$newcardbutton.= '<span class="fa fa-plus-circle valignmiddle"></span>';
210
-				$newcardbutton.= '</a>';
208
+				$newcardbutton = '<a class="butActionNew" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.dol_print_date(dol_now(), 'dayhourlog').'&origin='.$typeelement.'&originid='.$object->id.($object->socid > 0 ? '&socid='.$object->socid : ($socid > 0 ? '&socid='.$socid : '')).($projectid > 0 ? '&projectid='.$projectid : '').'&backtopage='.urlencode($urlbacktopage).'"><span class="valignmiddle">'.$langs->trans("AddEvent").'</span>';
209
+				$newcardbutton .= '<span class="fa fa-plus-circle valignmiddle"></span>';
210
+				$newcardbutton .= '</a>';
211 211
 			}
212 212
 
213 213
         	print '<!-- formactions->showactions -->'."\n";
214 214
         	print load_fiche_titre($title, $newcardbutton, '', 0, 0, '', $morehtmlright);
215 215
 
216
-        	$page=0; $param='';
216
+        	$page = 0; $param = '';
217 217
 
218 218
         	$total = 0;
219 219
 
220 220
         	print '<div class="div-table-responsive-no-min">';
221
-        	print '<table class="noborder'.($morecss?' '.$morecss:'').'" width="100%">';
221
+        	print '<table class="noborder'.($morecss ? ' '.$morecss : '').'" width="100%">';
222 222
         	print '<tr class="liste_titre">';
223
-        	print getTitleFieldOfList('Ref',   0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
224
-        	print getTitleFieldOfList('By',    0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
225
-        	print getTitleFieldOfList('Type',  0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
223
+        	print getTitleFieldOfList('Ref', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
224
+        	print getTitleFieldOfList('By', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
225
+        	print getTitleFieldOfList('Type', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
226 226
         	print getTitleFieldOfList('Title', 0, $_SERVER["PHP_SELF"], '', $page, $param, '', $sortfield, $sortorder, '', 1);
227
-        	print getTitleFieldOfList('Date',  0, $_SERVER["PHP_SELF"], 'a.datep', $page, $param, 'align="center"', $sortfield, $sortorder, '', 1);
228
-        	print getTitleFieldOfList('',      0, $_SERVER["PHP_SELF"], '', $page, $param, 'align="right"', $sortfield, $sortorder, '', 1);
227
+        	print getTitleFieldOfList('Date', 0, $_SERVER["PHP_SELF"], 'a.datep', $page, $param, 'align="center"', $sortfield, $sortorder, '', 1);
228
+        	print getTitleFieldOfList('', 0, $_SERVER["PHP_SELF"], '', $page, $param, 'align="right"', $sortfield, $sortorder, '', 1);
229 229
         	print '</tr>';
230 230
         	print "\n";
231 231
 
@@ -234,37 +234,37 @@  discard block
 block discarded – undo
234 234
         	if (count($listofactions))
235 235
         	{
236 236
 	        	$cursorevent = 0;
237
-	        	foreach($listofactions as $action)
237
+	        	foreach ($listofactions as $action)
238 238
 	        	{
239 239
 	        		if ($max && $cursorevent >= $max) break;
240 240
 
241
-	        		$ref=$action->getNomUrl(1,-1);
242
-	        		$label=$action->getNomUrl(0,38);
241
+	        		$ref = $action->getNomUrl(1, -1);
242
+	        		$label = $action->getNomUrl(0, 38);
243 243
 
244 244
 	        		print '<tr class="oddeven">';
245 245
 	        		// Ref
246 246
 					print '<td>'.$ref.'</td>';
247 247
 					// Onwer
248 248
 	        		print '<td>';
249
-	        		if (! empty($action->userownerid))
249
+	        		if (!empty($action->userownerid))
250 250
 	        		{
251
-	        			$userstatic->fetch($action->userownerid);	// TODO Introduce a cache on users fetched
251
+	        			$userstatic->fetch($action->userownerid); // TODO Introduce a cache on users fetched
252 252
 	        			print $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, '', '');
253 253
 	        		}
254 254
 	        		print '</td>';
255 255
 					// Type
256 256
 	        		print '<td>';
257
-					$imgpicto='';
258
-					if (! empty($conf->global->AGENDA_USE_EVENT_TYPE))
257
+					$imgpicto = '';
258
+					if (!empty($conf->global->AGENDA_USE_EVENT_TYPE))
259 259
 					{
260
-						if ($action->type_picto) $imgpicto=img_picto('', $action->type_picto);
260
+						if ($action->type_picto) $imgpicto = img_picto('', $action->type_picto);
261 261
 						else {
262
-							if ($action->type_code == 'AC_RDV')       $imgpicto=img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' ';
263
-							elseif ($action->type_code == 'AC_TEL')   $imgpicto=img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' ';
264
-							elseif ($action->type_code == 'AC_FAX')   $imgpicto=img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' ';
265
-							elseif ($action->type_code == 'AC_EMAIL') $imgpicto=img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' ';
266
-							elseif ($action->type_code == 'AC_INT')   $imgpicto=img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' ';
267
-							elseif (! preg_match('/_AUTO/', $action->type_code)) $imgpicto=img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' ';
262
+							if ($action->type_code == 'AC_RDV')       $imgpicto = img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' ';
263
+							elseif ($action->type_code == 'AC_TEL')   $imgpicto = img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' ';
264
+							elseif ($action->type_code == 'AC_FAX')   $imgpicto = img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' ';
265
+							elseif ($action->type_code == 'AC_EMAIL') $imgpicto = img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' ';
266
+							elseif ($action->type_code == 'AC_INT')   $imgpicto = img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' ';
267
+							elseif (!preg_match('/_AUTO/', $action->type_code)) $imgpicto = img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' ';
268 268
 						}
269 269
 					}
270 270
 					print $imgpicto;
@@ -276,8 +276,8 @@  discard block
 block discarded – undo
276 276
 	        		print '<td align="center">'.dol_print_date($action->datep, 'dayhour', 'tzuserrel');
277 277
 	        		if ($action->datef)
278 278
 	        		{
279
-		        		$tmpa=dol_getdate($action->datep);
280
-		        		$tmpb=dol_getdate($action->datef);
279
+		        		$tmpa = dol_getdate($action->datep);
280
+		        		$tmpb = dol_getdate($action->datef);
281 281
 		        		if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year'])
282 282
 		        		{
283 283
 		        			if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) print '-'.dol_print_date($action->datef, 'hour', 'tzuserrel');
@@ -286,7 +286,7 @@  discard block
 block discarded – undo
286 286
 	        		}
287 287
 	        		print '</td>';
288 288
 	        		print '<td align="right">';
289
-	        		if (! empty($action->author->id))
289
+	        		if (!empty($action->author->id))
290 290
 	        		{
291 291
 	        			print $action->getLibStatut(3);
292 292
 	        		}
@@ -327,42 +327,42 @@  discard block
 block discarded – undo
327 327
      *  @param  int             $nooutput       1=No output
328 328
      * 	@return	string
329 329
      */
330
-    function select_type_actions($selected='', $htmlname='actioncode', $excludetype='', $onlyautoornot=0, $hideinfohelp=0, $multiselect=0, $nooutput=0)
330
+    function select_type_actions($selected = '', $htmlname = 'actioncode', $excludetype = '', $onlyautoornot = 0, $hideinfohelp = 0, $multiselect = 0, $nooutput = 0)
331 331
     {
332 332
         // phpcs:enable
333
-        global $langs,$user,$form,$conf;
333
+        global $langs, $user, $form, $conf;
334 334
 
335
-        if (! is_object($form)) $form=new Form($this->db);
335
+        if (!is_object($form)) $form = new Form($this->db);
336 336
 
337 337
         require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
338 338
         require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
339
-        $caction=new CActionComm($this->db);
339
+        $caction = new CActionComm($this->db);
340 340
 
341 341
        	// Suggest a list with manual events or all auto events
342
-       	$arraylist=$caction->liste_array(1, 'code', $excludetype, $onlyautoornot);
343
-       	array_unshift($arraylist,'&nbsp;');     // Add empty line at start
342
+       	$arraylist = $caction->liste_array(1, 'code', $excludetype, $onlyautoornot);
343
+       	array_unshift($arraylist, '&nbsp;'); // Add empty line at start
344 344
        	//asort($arraylist);
345 345
 
346
-       	if ($selected == 'manual') $selected='AC_OTH';
347
-       	if ($selected == 'auto')   $selected='AC_OTH_AUTO';
346
+       	if ($selected == 'manual') $selected = 'AC_OTH';
347
+       	if ($selected == 'auto')   $selected = 'AC_OTH_AUTO';
348 348
 
349
-       	if (! empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) unset($arraylist['AC_OTH_AUTO']);
349
+       	if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) unset($arraylist['AC_OTH_AUTO']);
350 350
 
351
-       	$out='';
351
+       	$out = '';
352 352
 
353
-		if (! empty($multiselect))
353
+		if (!empty($multiselect))
354 354
 		{
355 355
 	        if (!is_array($selected) && !empty($selected)) $selected = explode(',', $selected);
356
-			$out.=$form->multiselectarray($htmlname, $arraylist, $selected, 0, 0, 'centpercent', 0, 0);
356
+			$out .= $form->multiselectarray($htmlname, $arraylist, $selected, 0, 0, 'centpercent', 0, 0);
357 357
 		}
358 358
 		else
359 359
 		{
360
-			$out.=$form->selectarray($htmlname, $arraylist, $selected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth200', 1);
360
+			$out .= $form->selectarray($htmlname, $arraylist, $selected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth200', 1);
361 361
 		}
362 362
 
363 363
         if ($user->admin && empty($onlyautoornot) && $hideinfohelp <= 0)
364 364
         {
365
-            $out.=info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup").($hideinfohelp == -1 ? ". ".$langs->trans("YouCanSetDefaultValueInModuleSetup") : ''),1);
365
+            $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup").($hideinfohelp == -1 ? ". ".$langs->trans("YouCanSetDefaultValueInModuleSetup") : ''), 1);
366 366
         }
367 367
 
368 368
         if ($nooutput) return $out;
Please login to merge, or discard this patch.
Braces   +87 added lines, -41 removed lines patch added patch discarded remove patch
@@ -128,9 +128,13 @@  discard block
 block discarded – undo
128 128
         if (! empty($conf->use_javascript_ajax) || $onlyselect)
129 129
         {
130 130
         	//var_dump($selected);
131
-        	if ($selected == 'done') $selected='100';
131
+        	if ($selected == 'done') {
132
+        	    $selected='100';
133
+        	}
132 134
             print '<select '.($canedit?'':'disabled ').'name="'.$htmlname.'" id="select'.$htmlname.'" class="flat'.($morecss?' '.$morecss:'').'">';
133
-            if ($showempty) print '<option value=""'.($selected == ''?' selected':'').'></option>';
135
+            if ($showempty) {
136
+                print '<option value=""'.($selected == ''?' selected':'').'></option>';
137
+            }
134 138
             foreach($listofstatus as $key => $val)
135 139
             {
136 140
                 print '<option value="'.$key.'"'.(($selected == $key && strlen($selected) == strlen($key)) || (($selected > 0 && $selected < 100) && $key == '50') ? ' selected' : '').'>'.$val.'</option>';
@@ -140,15 +144,16 @@  discard block
 block discarded – undo
140 144
                 }
141 145
             }
142 146
             print '</select>';
143
-            if ($selected == 0 || $selected == 100) $canedit=0;
147
+            if ($selected == 0 || $selected == 100) {
148
+                $canedit=0;
149
+            }
144 150
 
145 151
             if (empty($onlyselect))
146 152
             {
147 153
 	            print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat hideifna" value="'.($selected>=0?$selected:'').'" size="2"'.($canedit&&($selected>=0)?'':' disabled').'>';
148 154
     	        print '<span class="hideonsmartphone hideifna">%</span>';
149 155
             }
150
-        }
151
-        else
156
+        } else
152 157
 		{
153 158
             print ' <input type="text" id="val'.$htmlname.'" name="percentage" class="flat" value="'.($selected>=0?$selected:'').'" size="2"'.($canedit?'':' disabled').'>%';
154 159
         }
@@ -179,28 +184,45 @@  discard block
 block discarded – undo
179 184
         $sortorder='DESC,DESC';
180 185
 
181 186
         $listofactions=ActionComm::getActions($this->db, $socid, $object->id, $typeelement, '', $sortfield, $sortorder, ($max?($max+1):0));
182
-		if (! is_array($listofactions)) dol_print_error($this->db,'FailedToGetActions');
187
+		if (! is_array($listofactions)) {
188
+		    dol_print_error($this->db,'FailedToGetActions');
189
+		}
183 190
 
184 191
         $num = count($listofactions);
185 192
         if ($num || $forceshowtitle)
186 193
         {
187
-        	if ($typeelement == 'invoice')               $title=$langs->trans('ActionsOnBill');
188
-        	elseif ($typeelement == 'invoice_supplier' || $typeelement == 'supplier_invoice') $title=$langs->trans('ActionsOnBill');
189
-        	elseif ($typeelement == 'propal')            $title=$langs->trans('ActionsOnPropal');
190
-        	elseif ($typeelement == 'supplier_proposal') $title=$langs->trans('ActionsOnSupplierProposal');
191
-        	elseif ($typeelement == 'order')             $title=$langs->trans('ActionsOnOrder');
192
-        	elseif ($typeelement == 'order_supplier' || $typeelement == 'supplier_order')   $title=$langs->trans('ActionsOnOrder');
193
-        	elseif ($typeelement == 'shipping')          $title=$langs->trans('ActionsOnShipping');
194
-            elseif ($typeelement == 'fichinter')         $title=$langs->trans('ActionsOnFicheInter');
195
-            elseif ($typeelement == 'project')           $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
196
-            elseif ($typeelement == 'task')              $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
197
-            elseif ($typeelement == 'member')            $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
198
-            else $title=$langs->trans("LatestLinkedEvents", $max?$max:'');
194
+        	if ($typeelement == 'invoice') {
195
+        	    $title=$langs->trans('ActionsOnBill');
196
+        	} elseif ($typeelement == 'invoice_supplier' || $typeelement == 'supplier_invoice') {
197
+        	    $title=$langs->trans('ActionsOnBill');
198
+        	} elseif ($typeelement == 'propal') {
199
+        	    $title=$langs->trans('ActionsOnPropal');
200
+        	} elseif ($typeelement == 'supplier_proposal') {
201
+        	    $title=$langs->trans('ActionsOnSupplierProposal');
202
+        	} elseif ($typeelement == 'order') {
203
+        	    $title=$langs->trans('ActionsOnOrder');
204
+        	} elseif ($typeelement == 'order_supplier' || $typeelement == 'supplier_order') {
205
+        	    $title=$langs->trans('ActionsOnOrder');
206
+        	} elseif ($typeelement == 'shipping') {
207
+        	    $title=$langs->trans('ActionsOnShipping');
208
+        	} elseif ($typeelement == 'fichinter') {
209
+                $title=$langs->trans('ActionsOnFicheInter');
210
+            } elseif ($typeelement == 'project') {
211
+                $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
212
+            } elseif ($typeelement == 'task') {
213
+                $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
214
+            } elseif ($typeelement == 'member') {
215
+                $title=$langs->trans('LatestLinkedEvents', $max?$max:'');
216
+            } else {
217
+                $title=$langs->trans("LatestLinkedEvents", $max?$max:'');
218
+            }
199 219
 
200 220
             $urlbacktopage=$_SERVER['PHP_SELF'].'?id='.$object->id.($moreparambacktopage?'&'.$moreparambacktopage:'');
201 221
 
202 222
             $projectid = $object->fk_project;
203
-            if ($typeelement == 'project') $projectid = $object->id;
223
+            if ($typeelement == 'project') {
224
+                $projectid = $object->id;
225
+            }
204 226
 
205 227
             $newcardbutton='';
206 228
 			if (! empty($conf->agenda->enabled))
@@ -236,7 +258,9 @@  discard block
 block discarded – undo
236 258
 	        	$cursorevent = 0;
237 259
 	        	foreach($listofactions as $action)
238 260
 	        	{
239
-	        		if ($max && $cursorevent >= $max) break;
261
+	        		if ($max && $cursorevent >= $max) {
262
+	        		    break;
263
+	        		}
240 264
 
241 265
 	        		$ref=$action->getNomUrl(1,-1);
242 266
 	        		$label=$action->getNomUrl(0,38);
@@ -257,14 +281,22 @@  discard block
 block discarded – undo
257 281
 					$imgpicto='';
258 282
 					if (! empty($conf->global->AGENDA_USE_EVENT_TYPE))
259 283
 					{
260
-						if ($action->type_picto) $imgpicto=img_picto('', $action->type_picto);
261
-						else {
262
-							if ($action->type_code == 'AC_RDV')       $imgpicto=img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' ';
263
-							elseif ($action->type_code == 'AC_TEL')   $imgpicto=img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' ';
264
-							elseif ($action->type_code == 'AC_FAX')   $imgpicto=img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' ';
265
-							elseif ($action->type_code == 'AC_EMAIL') $imgpicto=img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' ';
266
-							elseif ($action->type_code == 'AC_INT')   $imgpicto=img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' ';
267
-							elseif (! preg_match('/_AUTO/', $action->type_code)) $imgpicto=img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' ';
284
+						if ($action->type_picto) {
285
+						    $imgpicto=img_picto('', $action->type_picto);
286
+						} else {
287
+							if ($action->type_code == 'AC_RDV') {
288
+							    $imgpicto=img_picto('', 'object_group', '', false, 0, 0, '', 'paddingright').' ';
289
+							} elseif ($action->type_code == 'AC_TEL') {
290
+							    $imgpicto=img_picto('', 'object_phoning', '', false, 0, 0, '', 'paddingright').' ';
291
+							} elseif ($action->type_code == 'AC_FAX') {
292
+							    $imgpicto=img_picto('', 'object_phoning_fax', '', false, 0, 0, '', 'paddingright').' ';
293
+							} elseif ($action->type_code == 'AC_EMAIL') {
294
+							    $imgpicto=img_picto('', 'object_email', '', false, 0, 0, '', 'paddingright').' ';
295
+							} elseif ($action->type_code == 'AC_INT') {
296
+							    $imgpicto=img_picto('', 'object_intervention', '', false, 0, 0, '', 'paddingright').' ';
297
+							} elseif (! preg_match('/_AUTO/', $action->type_code)) {
298
+							    $imgpicto=img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').' ';
299
+							}
268 300
 						}
269 301
 					}
270 302
 					print $imgpicto;
@@ -280,9 +312,12 @@  discard block
 block discarded – undo
280 312
 		        		$tmpb=dol_getdate($action->datef);
281 313
 		        		if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year'])
282 314
 		        		{
283
-		        			if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) print '-'.dol_print_date($action->datef, 'hour', 'tzuserrel');
315
+		        			if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) {
316
+		        			    print '-'.dol_print_date($action->datef, 'hour', 'tzuserrel');
317
+		        			}
318
+		        		} else {
319
+		        		    print '-'.dol_print_date($action->datef, 'dayhour', 'tzuserrel');
284 320
 		        		}
285
-		        		else print '-'.dol_print_date($action->datef, 'dayhour', 'tzuserrel');
286 321
 	        		}
287 322
 	        		print '</td>';
288 323
 	        		print '<td align="right">';
@@ -295,8 +330,7 @@  discard block
 block discarded – undo
295 330
 
296 331
 	        		$cursorevent++;
297 332
 	        	}
298
-        	}
299
-        	else
333
+        	} else
300 334
         	{
301 335
         		print '<tr class="oddeven"><td colspan="6" class="opacitymedium">'.$langs->trans("None").'</td></tr>';
302 336
         	}
@@ -332,7 +366,9 @@  discard block
 block discarded – undo
332 366
         // phpcs:enable
333 367
         global $langs,$user,$form,$conf;
334 368
 
335
-        if (! is_object($form)) $form=new Form($this->db);
369
+        if (! is_object($form)) {
370
+            $form=new Form($this->db);
371
+        }
336 372
 
337 373
         require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php';
338 374
         require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
@@ -343,19 +379,26 @@  discard block
 block discarded – undo
343 379
        	array_unshift($arraylist,'&nbsp;');     // Add empty line at start
344 380
        	//asort($arraylist);
345 381
 
346
-       	if ($selected == 'manual') $selected='AC_OTH';
347
-       	if ($selected == 'auto')   $selected='AC_OTH_AUTO';
382
+       	if ($selected == 'manual') {
383
+       	    $selected='AC_OTH';
384
+       	}
385
+       	if ($selected == 'auto') {
386
+       	    $selected='AC_OTH_AUTO';
387
+       	}
348 388
 
349
-       	if (! empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) unset($arraylist['AC_OTH_AUTO']);
389
+       	if (! empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) {
390
+       	    unset($arraylist['AC_OTH_AUTO']);
391
+       	}
350 392
 
351 393
        	$out='';
352 394
 
353 395
 		if (! empty($multiselect))
354 396
 		{
355
-	        if (!is_array($selected) && !empty($selected)) $selected = explode(',', $selected);
397
+	        if (!is_array($selected) && !empty($selected)) {
398
+	            $selected = explode(',', $selected);
399
+	        }
356 400
 			$out.=$form->multiselectarray($htmlname, $arraylist, $selected, 0, 0, 'centpercent', 0, 0);
357
-		}
358
-		else
401
+		} else
359 402
 		{
360 403
 			$out.=$form->selectarray($htmlname, $arraylist, $selected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth200', 1);
361 404
 		}
@@ -365,8 +408,11 @@  discard block
 block discarded – undo
365 408
             $out.=info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup").($hideinfohelp == -1 ? ". ".$langs->trans("YouCanSetDefaultValueInModuleSetup") : ''),1);
366 409
         }
367 410
 
368
-        if ($nooutput) return $out;
369
-        else print $out;
411
+        if ($nooutput) {
412
+            return $out;
413
+        } else {
414
+            print $out;
415
+        }
370 416
         return '';
371 417
     }
372 418
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formcron.class.php 3 patches
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -28,75 +28,75 @@
 block discarded – undo
28 28
  */
29 29
 class FormCron extends Form
30 30
 {
31
-	/**
31
+    /**
32 32
      * @var DoliDB Database handler.
33 33
      */
34 34
     public $db;
35 35
 
36
-	/**
37
-	 * @var string Error code (or message)
38
-	 */
39
-	public $error='';
36
+    /**
37
+     * @var string Error code (or message)
38
+     */
39
+    public $error='';
40 40
 
41
-	/**
42
-	 *	Constructor
43
-	 *
44
-	 *  @param		DoliDB		$db      Database handler
45
-	 */
46
-	function __construct($db)
47
-	{
48
-		$this->db = $db;
49
-	}
41
+    /**
42
+     *	Constructor
43
+     *
44
+     *  @param		DoliDB		$db      Database handler
45
+     */
46
+    function __construct($db)
47
+    {
48
+        $this->db = $db;
49
+    }
50 50
 
51 51
 
52 52
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
53
-	/**
54
-	 * Display On Off selector
55
-	 *
56
-	 * @param   string 	$htmlname		Html control name
57
-	 * @param   integer 	$selected		selected value
58
-	 * @param   integer	$readonly		Select is read only or not
59
-	 * @return	string					HTML select field
60
-	 */
61
-	function select_typejob($htmlname,$selected=0,$readonly=0)
62
-	{
53
+    /**
54
+     * Display On Off selector
55
+     *
56
+     * @param   string 	$htmlname		Html control name
57
+     * @param   integer 	$selected		selected value
58
+     * @param   integer	$readonly		Select is read only or not
59
+     * @return	string					HTML select field
60
+     */
61
+    function select_typejob($htmlname,$selected=0,$readonly=0)
62
+    {
63 63
         // phpcs:enable
64
-		global $langs;
64
+        global $langs;
65 65
 
66
-		$langs->load('cron@cron');
67
-		if (!empty($readonly)) {
68
-			if ($selected=='command') {
69
-				$out= $langs->trans('CronType_command');
70
-				$out.='<SELECT name="'.$htmlname.'" id="'.$htmlname.'" style="display:none"/>';
71
-				$out.= '<OPTION value="command" selected>'.$langs->trans('CronType_command').'</OPTION>';
72
-				$out.='</SELECT>';
73
-			} elseif ($selected=='method') {
74
-				$out= $langs->trans('CronType_method');
75
-				$out.='<SELECT name="'.$htmlname.'" id="'.$htmlname.'" style="display:none"/>';
76
-				$out.= '<OPTION value="method" selected>'.$langs->trans('CronType_method').'</OPTION>';
77
-				$out.='</SELECT>';
78
-			}
79
-		}else {
66
+        $langs->load('cron@cron');
67
+        if (!empty($readonly)) {
68
+            if ($selected=='command') {
69
+                $out= $langs->trans('CronType_command');
70
+                $out.='<SELECT name="'.$htmlname.'" id="'.$htmlname.'" style="display:none"/>';
71
+                $out.= '<OPTION value="command" selected>'.$langs->trans('CronType_command').'</OPTION>';
72
+                $out.='</SELECT>';
73
+            } elseif ($selected=='method') {
74
+                $out= $langs->trans('CronType_method');
75
+                $out.='<SELECT name="'.$htmlname.'" id="'.$htmlname.'" style="display:none"/>';
76
+                $out.= '<OPTION value="method" selected>'.$langs->trans('CronType_method').'</OPTION>';
77
+                $out.='</SELECT>';
78
+            }
79
+        }else {
80 80
 
81
-		$out='<SELECT class="flat" name="'.$htmlname.'" id="'.$htmlname.'" />';
81
+        $out='<SELECT class="flat" name="'.$htmlname.'" id="'.$htmlname.'" />';
82 82
 
83
-		if ($selected=='command') {
84
-			$selected_attr=' selected ';
85
-		} else {
86
-			$selected_attr='';
87
-		}
88
-		$out.= '<OPTION value="command" '.$selected_attr.'>'.$langs->trans('CronType_command').'</OPTION>';
83
+        if ($selected=='command') {
84
+            $selected_attr=' selected ';
85
+        } else {
86
+            $selected_attr='';
87
+        }
88
+        $out.= '<OPTION value="command" '.$selected_attr.'>'.$langs->trans('CronType_command').'</OPTION>';
89 89
 
90
-		if ($selected=='method') {
91
-			$selected_attr=' selected ';
92
-		} else {
93
-			$selected_attr='';
94
-		}
95
-		$out.= '<OPTION value="method" '.$selected_attr.'>'.$langs->trans('CronType_method').'</OPTION>';
90
+        if ($selected=='method') {
91
+            $selected_attr=' selected ';
92
+        } else {
93
+            $selected_attr='';
94
+        }
95
+        $out.= '<OPTION value="method" '.$selected_attr.'>'.$langs->trans('CronType_method').'</OPTION>';
96 96
 
97
-		$out.='</SELECT>';
98
-		}
97
+        $out.='</SELECT>';
98
+        }
99 99
 
100
-		return $out;
101
-	}
100
+        return $out;
101
+    }
102 102
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
 	/**
37 37
 	 * @var string Error code (or message)
38 38
 	 */
39
-	public $error='';
39
+	public $error = '';
40 40
 
41 41
 	/**
42 42
 	 *	Constructor
@@ -58,43 +58,43 @@  discard block
 block discarded – undo
58 58
 	 * @param   integer	$readonly		Select is read only or not
59 59
 	 * @return	string					HTML select field
60 60
 	 */
61
-	function select_typejob($htmlname,$selected=0,$readonly=0)
61
+	function select_typejob($htmlname, $selected = 0, $readonly = 0)
62 62
 	{
63 63
         // phpcs:enable
64 64
 		global $langs;
65 65
 
66 66
 		$langs->load('cron@cron');
67 67
 		if (!empty($readonly)) {
68
-			if ($selected=='command') {
69
-				$out= $langs->trans('CronType_command');
70
-				$out.='<SELECT name="'.$htmlname.'" id="'.$htmlname.'" style="display:none"/>';
71
-				$out.= '<OPTION value="command" selected>'.$langs->trans('CronType_command').'</OPTION>';
72
-				$out.='</SELECT>';
73
-			} elseif ($selected=='method') {
74
-				$out= $langs->trans('CronType_method');
75
-				$out.='<SELECT name="'.$htmlname.'" id="'.$htmlname.'" style="display:none"/>';
76
-				$out.= '<OPTION value="method" selected>'.$langs->trans('CronType_method').'</OPTION>';
77
-				$out.='</SELECT>';
68
+			if ($selected == 'command') {
69
+				$out = $langs->trans('CronType_command');
70
+				$out .= '<SELECT name="'.$htmlname.'" id="'.$htmlname.'" style="display:none"/>';
71
+				$out .= '<OPTION value="command" selected>'.$langs->trans('CronType_command').'</OPTION>';
72
+				$out .= '</SELECT>';
73
+			} elseif ($selected == 'method') {
74
+				$out = $langs->trans('CronType_method');
75
+				$out .= '<SELECT name="'.$htmlname.'" id="'.$htmlname.'" style="display:none"/>';
76
+				$out .= '<OPTION value="method" selected>'.$langs->trans('CronType_method').'</OPTION>';
77
+				$out .= '</SELECT>';
78 78
 			}
79
-		}else {
79
+		} else {
80 80
 
81
-		$out='<SELECT class="flat" name="'.$htmlname.'" id="'.$htmlname.'" />';
81
+		$out = '<SELECT class="flat" name="'.$htmlname.'" id="'.$htmlname.'" />';
82 82
 
83
-		if ($selected=='command') {
84
-			$selected_attr=' selected ';
83
+		if ($selected == 'command') {
84
+			$selected_attr = ' selected ';
85 85
 		} else {
86
-			$selected_attr='';
86
+			$selected_attr = '';
87 87
 		}
88
-		$out.= '<OPTION value="command" '.$selected_attr.'>'.$langs->trans('CronType_command').'</OPTION>';
88
+		$out .= '<OPTION value="command" '.$selected_attr.'>'.$langs->trans('CronType_command').'</OPTION>';
89 89
 
90
-		if ($selected=='method') {
91
-			$selected_attr=' selected ';
90
+		if ($selected == 'method') {
91
+			$selected_attr = ' selected ';
92 92
 		} else {
93
-			$selected_attr='';
93
+			$selected_attr = '';
94 94
 		}
95
-		$out.= '<OPTION value="method" '.$selected_attr.'>'.$langs->trans('CronType_method').'</OPTION>';
95
+		$out .= '<OPTION value="method" '.$selected_attr.'>'.$langs->trans('CronType_method').'</OPTION>';
96 96
 
97
-		$out.='</SELECT>';
97
+		$out .= '</SELECT>';
98 98
 		}
99 99
 
100 100
 		return $out;
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -76,7 +76,7 @@
 block discarded – undo
76 76
 				$out.= '<OPTION value="method" selected>'.$langs->trans('CronType_method').'</OPTION>';
77 77
 				$out.='</SELECT>';
78 78
 			}
79
-		}else {
79
+		} else {
80 80
 
81 81
 		$out='<SELECT class="flat" name="'.$htmlname.'" id="'.$htmlname.'" />';
82 82
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formmailing.class.php 2 patches
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -27,33 +27,33 @@
 block discarded – undo
27 27
  */
28 28
 class FormMailing extends Form
29 29
 {
30
-	/**
31
-	 * @var string[] Error codes (or messages)
32
-	 */
33
-	public $errors = array();
34
-
35
-	/**
36
-	 * Output a select with destinaries status
37
-	 *
38
-	 * @param string   $selectedid     The selected id
39
-	 * @param string   $htmlname       Name of controm
40
-	 * @param integer  $show_empty     Show empty option
41
-	 * @return string HTML select
42
-	 */
30
+    /**
31
+     * @var string[] Error codes (or messages)
32
+     */
33
+    public $errors = array();
34
+
35
+    /**
36
+     * Output a select with destinaries status
37
+     *
38
+     * @param string   $selectedid     The selected id
39
+     * @param string   $htmlname       Name of controm
40
+     * @param integer  $show_empty     Show empty option
41
+     * @return string HTML select
42
+     */
43 43
     public function selectDestinariesStatus($selectedid='', $htmlname='dest_status', $show_empty=0)
44 44
     {
45 45
 
46
-		global $langs;
47
-		$langs->load("mails");
46
+        global $langs;
47
+        $langs->load("mails");
48 48
 
49
-		require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/mailing.class.php';
50
-		$mailing = new Mailing($this->db);
49
+        require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/mailing.class.php';
50
+        $mailing = new Mailing($this->db);
51 51
 
52
-		$options = array();
52
+        $options = array();
53 53
 
54
-		if ($show_empty) {
55
-			$options[-2] = '';   // Note -1 is used for error
56
-		}
54
+        if ($show_empty) {
55
+            $options[-2] = '';   // Note -1 is used for error
56
+        }
57 57
 
58 58
         $options = $options + $mailing->statut_dest;
59 59
 
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
  *  \ingroup    core
21 21
  *	\brief      File of predefined functions for HTML forms for mailing module
22 22
  */
23
-require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';
23
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
24 24
 
25 25
 /**
26 26
  *  Class to offer components to list and upload files
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
 	 * @param integer  $show_empty     Show empty option
41 41
 	 * @return string HTML select
42 42
 	 */
43
-    public function selectDestinariesStatus($selectedid='', $htmlname='dest_status', $show_empty=0)
43
+    public function selectDestinariesStatus($selectedid = '', $htmlname = 'dest_status', $show_empty = 0)
44 44
     {
45 45
 
46 46
 		global $langs;
@@ -52,7 +52,7 @@  discard block
 block discarded – undo
52 52
 		$options = array();
53 53
 
54 54
 		if ($show_empty) {
55
-			$options[-2] = '';   // Note -1 is used for error
55
+			$options[-2] = ''; // Note -1 is used for error
56 56
 		}
57 57
 
58 58
         $options = $options + $mailing->statut_dest;
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/doleditor.class.php 3 patches
Indentation   +108 added lines, -108 removed lines patch added patch discarded remove patch
@@ -30,19 +30,19 @@  discard block
 block discarded – undo
30 30
 {
31 31
     var $tool;      // Store the selected tool
32 32
 
33
-	// If using fckeditor
34
-	var $editor;
33
+    // If using fckeditor
34
+    var $editor;
35 35
 
36
-	// If not using fckeditor
37
-	var $content;
38
-	var $htmlname;
39
-	var $toolbarname;
40
-	var $toolbarstartexpanded;
41
-	var $rows;
42
-	var $cols;
43
-	var $height;
44
-	var $width;
45
-	var $readonly;
36
+    // If not using fckeditor
37
+    var $content;
38
+    var $htmlname;
39
+    var $toolbarname;
40
+    var $toolbarstartexpanded;
41
+    var $rows;
42
+    var $cols;
43
+    var $height;
44
+    var $width;
45
+    var $readonly;
46 46
 
47 47
 
48 48
     /**
@@ -57,22 +57,22 @@  discard block
 block discarded – undo
57 57
      *                       		             			'In' each window has its own toolbar
58 58
      *                              		      			'Out:name' share toolbar into the div called 'name'
59 59
      *      @param  boolean	$toolbarstartexpanded  			Bar is visible or not at start
60
-	 *		@param	int		$uselocalbrowser				Enabled to add links to local object with local browser. If false, only external images can be added in content.
61
-	 *      @param  boolean|string	$okforextendededitor    True=Allow usage of extended editor tool if qualified (like ckeditor). If 'textarea', force use of simple textarea. If 'ace', force use of Ace.
62
-	 *      												Warning: If you use 'ace', don't forget to also include ace.js in page header. Also, the button "save" must have class="buttonforacesave".
60
+     *		@param	int		$uselocalbrowser				Enabled to add links to local object with local browser. If false, only external images can be added in content.
61
+     *      @param  boolean|string	$okforextendededitor    True=Allow usage of extended editor tool if qualified (like ckeditor). If 'textarea', force use of simple textarea. If 'ace', force use of Ace.
62
+     *      												Warning: If you use 'ace', don't forget to also include ace.js in page header. Also, the button "save" must have class="buttonforacesave".
63 63
      *      @param  int		$rows                   		Size of rows for textarea tool
64
-	 *      @param  string	$cols                   		Size of cols for textarea tool (textarea number of cols '70' or percent 'x%')
65
-	 *      @param	int		$readonly						0=Read/Edit, 1=Read only
66
-	 */
64
+     *      @param  string	$cols                   		Size of cols for textarea tool (textarea number of cols '70' or percent 'x%')
65
+     *      @param	int		$readonly						0=Read/Edit, 1=Read only
66
+     */
67 67
     function __construct($htmlname, $content, $width='', $height=200, $toolbarname='Basic', $toolbarlocation='In', $toolbarstartexpanded=false, $uselocalbrowser=true, $okforextendededitor=true, $rows=0, $cols=0, $readonly=0)
68 68
     {
69
-    	global $conf,$langs;
69
+        global $conf,$langs;
70 70
 
71
-    	dol_syslog(get_class($this)."::DolEditor htmlname=".$htmlname." width=".$width." height=".$height." toolbarname=".$toolbarname);
71
+        dol_syslog(get_class($this)."::DolEditor htmlname=".$htmlname." width=".$width." height=".$height." toolbarname=".$toolbarname);
72 72
 
73
-    	if (! $rows) $rows=round($height/20);
74
-    	if (! $cols) $cols=($width?round($width/6):80);
75
-		$shorttoolbarname=preg_replace('/_encoded$/','',$toolbarname);
73
+        if (! $rows) $rows=round($height/20);
74
+        if (! $cols) $cols=($width?round($width/6):80);
75
+        $shorttoolbarname=preg_replace('/_encoded$/','',$toolbarname);
76 76
 
77 77
         // Name of extended editor to use (FCKEDITOR_EDITORNAME can be 'ckeditor' or 'fckeditor')
78 78
         $defaulteditor='ckeditor';
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
 
83 83
         // Check if extended editor is ok. If not we force textarea
84 84
         if ((empty($conf->fckeditor->enabled) && $okforextendededitor != 'ace') || empty($okforextendededitor)) $this->tool = 'textarea';
85
-		if ($okforextendededitor === 'ace') $this->tool='ace';
85
+        if ($okforextendededitor === 'ace') $this->tool='ace';
86 86
         //if ($conf->dol_use_jmobile) $this->tool = 'textarea';       // ckeditor and ace seems ok with mobile
87 87
 
88 88
         // Define content and some properties
@@ -91,50 +91,50 @@  discard block
 block discarded – undo
91 91
             $content=dol_htmlentitiesbr($content);  // If content is not HTML, we convert to HTML.
92 92
         }
93 93
         if ($this->tool == 'fckeditor')
94
-    	{
95
-        	require_once DOL_DOCUMENT_ROOT.'/includes/fckeditor/fckeditor.php';
96
-
97
-    		$content=dol_htmlentitiesbr($content);	// If content is not HTML, we convert to HTML.
98
-
99
-        	$this->editor = new FCKeditor($htmlname);
100
-        	$this->editor->BasePath = DOL_URL_ROOT.'/includes/fckeditor/' ;
101
-        	$this->editor->Value	= $content;
102
-        	$this->editor->Height   = $height;
103
-        	if (! empty($width)) $this->editor->Width = $width;
104
-        	$this->editor->ToolbarSet = $shorttoolbarname;         // Profile of this toolbar set is deinfed into theme/mytheme/ckeditor/config.js
105
-        	$this->editor->Config['AutoDetectLanguage'] = 'true';  // Language of user (browser)
106
-        	$this->editor->Config['ToolbarLocation'] = $toolbarlocation ? $toolbarlocation : 'In';
107
-        	$this->editor->Config['ToolbarStartExpanded'] = $toolbarstartexpanded;
108
-
109
-    		// Rem: Le forcage de ces 2 parametres ne semble pas fonctionner.
110
-    		// Dolibarr utilise toujours liens avec modulepart='fckeditor' quelque soit modulepart.
111
-    		// Ou se trouve donc cette valeur /viewimage.php?modulepart=fckeditor&file=' ?
112
-        	$modulepart='fckeditor';
113
-    		$this->editor->Config['UserFilesPath'] = '/viewimage.php?modulepart='.$modulepart.'&entity='.$conf->entity.'&file=';
114
-    		$this->editor->Config['UserFilesAbsolutePath'] = DOL_DATA_ROOT.'/'.$modulepart.'/' ;
115
-
116
-        	$this->editor->Config['LinkBrowser']=($uselocalbrowser?'true':'false');
117
-        	$this->editor->Config['ImageBrowser']=($uselocalbrowser?'true':'false');
118
-
119
-        	if (file_exists(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/fckeditor/fckconfig.js'))
120
-        	{
121
-        		$this->editor->Config['CustomConfigurationsPath'] = DOL_URL_ROOT.'/theme/'.$conf->theme.'/fckeditor/fckconfig.js';
122
-        		$this->editor->Config['SkinPath'] = DOL_URL_ROOT.'/theme/'.$conf->theme.'/fckeditor/';
123
-    		}
124
-    	}
125
-
126
-    	// Define some properties
94
+        {
95
+            require_once DOL_DOCUMENT_ROOT.'/includes/fckeditor/fckeditor.php';
96
+
97
+            $content=dol_htmlentitiesbr($content);	// If content is not HTML, we convert to HTML.
98
+
99
+            $this->editor = new FCKeditor($htmlname);
100
+            $this->editor->BasePath = DOL_URL_ROOT.'/includes/fckeditor/' ;
101
+            $this->editor->Value	= $content;
102
+            $this->editor->Height   = $height;
103
+            if (! empty($width)) $this->editor->Width = $width;
104
+            $this->editor->ToolbarSet = $shorttoolbarname;         // Profile of this toolbar set is deinfed into theme/mytheme/ckeditor/config.js
105
+            $this->editor->Config['AutoDetectLanguage'] = 'true';  // Language of user (browser)
106
+            $this->editor->Config['ToolbarLocation'] = $toolbarlocation ? $toolbarlocation : 'In';
107
+            $this->editor->Config['ToolbarStartExpanded'] = $toolbarstartexpanded;
108
+
109
+            // Rem: Le forcage de ces 2 parametres ne semble pas fonctionner.
110
+            // Dolibarr utilise toujours liens avec modulepart='fckeditor' quelque soit modulepart.
111
+            // Ou se trouve donc cette valeur /viewimage.php?modulepart=fckeditor&file=' ?
112
+            $modulepart='fckeditor';
113
+            $this->editor->Config['UserFilesPath'] = '/viewimage.php?modulepart='.$modulepart.'&entity='.$conf->entity.'&file=';
114
+            $this->editor->Config['UserFilesAbsolutePath'] = DOL_DATA_ROOT.'/'.$modulepart.'/' ;
115
+
116
+            $this->editor->Config['LinkBrowser']=($uselocalbrowser?'true':'false');
117
+            $this->editor->Config['ImageBrowser']=($uselocalbrowser?'true':'false');
118
+
119
+            if (file_exists(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/fckeditor/fckconfig.js'))
120
+            {
121
+                $this->editor->Config['CustomConfigurationsPath'] = DOL_URL_ROOT.'/theme/'.$conf->theme.'/fckeditor/fckconfig.js';
122
+                $this->editor->Config['SkinPath'] = DOL_URL_ROOT.'/theme/'.$conf->theme.'/fckeditor/';
123
+            }
124
+        }
125
+
126
+        // Define some properties
127 127
         if (in_array($this->tool,array('textarea','ckeditor','ace')))
128 128
         {
129
-    	    $this->content				= $content;
130
-    	    $this->htmlname 			= $htmlname;
131
-    	    $this->toolbarname			= $shorttoolbarname;
132
-    	    $this->toolbarstartexpanded = $toolbarstartexpanded;
129
+            $this->content				= $content;
130
+            $this->htmlname 			= $htmlname;
131
+            $this->toolbarname			= $shorttoolbarname;
132
+            $this->toolbarstartexpanded = $toolbarstartexpanded;
133 133
             $this->rows					= max(ROWS_3,$rows);
134 134
             $this->cols					= (preg_match('/%/',$cols)?$cols:max(40,$cols));	// If $cols is a percent, we keep it, otherwise, we take max
135 135
             $this->height				= $height;
136 136
             $this->width				= $width;
137
-    	}
137
+        }
138 138
     }
139 139
 
140 140
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -152,20 +152,20 @@  discard block
 block discarded – undo
152 152
     function Create($noprint=0, $morejs='', $disallowAnyContent=true, $titlecontent='', $option='')
153 153
     {
154 154
         // phpcs:enable
155
-    	global $conf,$langs;
155
+        global $conf,$langs;
156 156
 
157
-    	$fullpage=false;
158
-    	if (isset($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT))
159
-    	{
160
-    	   $disallowAnyContent=empty($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT);      // Only predefined list of html tags are allowed or all
161
-    	}
157
+        $fullpage=false;
158
+        if (isset($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT))
159
+        {
160
+            $disallowAnyContent=empty($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT);      // Only predefined list of html tags are allowed or all
161
+        }
162 162
 
163
-    	$found=0;
164
-		$out='';
163
+        $found=0;
164
+        $out='';
165 165
 
166 166
         if ($this->tool == 'fckeditor') // not used anymore
167 167
         {
168
-			$found=1;
168
+            $found=1;
169 169
             $this->editor->Create();
170 170
         }
171 171
         if (in_array($this->tool,array('textarea','ckeditor')))
@@ -179,18 +179,18 @@  discard block
 block discarded – undo
179 179
 
180 180
             if ($this->tool == 'ckeditor' && ! empty($conf->use_javascript_ajax))
181 181
             {
182
-            	if (! defined('REQUIRE_CKEDITOR')) define('REQUIRE_CKEDITOR','1');
182
+                if (! defined('REQUIRE_CKEDITOR')) define('REQUIRE_CKEDITOR','1');
183 183
 
184
-            	if (! empty($conf->global->FCKEDITOR_SKIN)) {
185
-					$skin = $conf->global->FCKEDITOR_SKIN;
186
-				} else {
187
-					$skin = 'moono-lisa'; // default with ckeditor 4.6 : moono-lisa
188
-				}
184
+                if (! empty($conf->global->FCKEDITOR_SKIN)) {
185
+                    $skin = $conf->global->FCKEDITOR_SKIN;
186
+                } else {
187
+                    $skin = 'moono-lisa'; // default with ckeditor 4.6 : moono-lisa
188
+                }
189 189
 
190
-            	$htmlencode_force=preg_match('/_encoded$/',$this->toolbarname)?'true':'false';
190
+                $htmlencode_force=preg_match('/_encoded$/',$this->toolbarname)?'true':'false';
191 191
 
192
-            	$out.= '<!-- Output ckeditor $disallowAnyContent='.$disallowAnyContent.' toolbarname='.$this->toolbarname.' -->'."\n";
193
-            	$out.= '<script type="text/javascript">
192
+                $out.= '<!-- Output ckeditor $disallowAnyContent='.$disallowAnyContent.' toolbarname='.$this->toolbarname.' -->'."\n";
193
+                $out.= '<script type="text/javascript">
194 194
             			$(document).ready(function () {
195 195
                             /* if (CKEDITOR.loadFullCore) CKEDITOR.loadFullCore(); */
196 196
                             /* should be editor=CKEDITOR.replace but what if serveral editors ? */
@@ -225,8 +225,8 @@  discard block
 block discarded – undo
225 225
                                                         });
226 226
                                                 }
227 227
                                             }';
228
-            	if ($this->uselocalbrowser)
229
-            	{
228
+                if ($this->uselocalbrowser)
229
+                {
230 230
                     $out.= ','."\n";
231 231
                     // To use filemanager with old fckeditor (GPL)
232 232
                     $out.= '    filebrowserBrowseUrl : ckeditorFilebrowserBrowseUrl,';
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
                     //$out.= '    filebrowserImageUploadUrl : \''.DOL_URL_ROOT.'/includes/fckeditor/editor/filemanagerdol/connectors/php/upload.php?Type=Image\',';
236 236
                     $out.= "\n";
237 237
                     // To use filemanager with ckfinder (Non free) and ckfinder directory is inside htdocs/includes
238
-					/* $out.= '    filebrowserBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html\',
238
+                    /* $out.= '    filebrowserBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html\',
239 239
                                filebrowserImageBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html?Type=Images\',
240 240
                                filebrowserFlashBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html?Type=Flash\',
241 241
                                filebrowserUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files\',
@@ -246,10 +246,10 @@  discard block
 block discarded – undo
246 246
                                filebrowserWindowHeight : \'500\',
247 247
                                filebrowserImageWindowWidth : \'900\',
248 248
                                filebrowserImageWindowHeight : \'500\'';
249
-            	}
250
-            	$out.= '	})'.$morejs;
251
-            	$out.= '});'."\n";
252
-            	$out.= '</script>'."\n";
249
+                }
250
+                $out.= '	})'.$morejs;
251
+                $out.= '});'."\n";
252
+                $out.= '</script>'."\n";
253 253
             }
254 254
         }
255 255
 
@@ -257,19 +257,19 @@  discard block
 block discarded – undo
257 257
         // Warning: ace.js and ext-statusbar.js must be loaded by the parent page.
258 258
         if (preg_match('/^ace/', $this->tool))
259 259
         {
260
-        	$found=1;
261
-			$format=$option;
260
+            $found=1;
261
+            $format=$option;
262 262
 
263 263
             $out.= "\n".'<!-- Output Ace editor -->'."\n";
264 264
 
265
-			if ($titlecontent)
266
-			{
267
-	            $out.= '<div class="aceeditorstatusbar" id="statusBar'.$this->htmlname.'">'.$titlecontent;
268
-	            $out.= ' &nbsp; - &nbsp; <a id="morelines" href="#" class="right morelines'.$this->htmlname.'">'.dol_escape_htmltag($langs->trans("ShowMoreLines")).'</a> &nbsp; &nbsp; ';
269
-	            $out.= '</div>';
270
-	            $out.= '<script type="text/javascript" language="javascript">'."\n";
271
-	            $out.= 'jQuery(document).ready(function() {'."\n";
272
-	            $out.= '	var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid");
265
+            if ($titlecontent)
266
+            {
267
+                $out.= '<div class="aceeditorstatusbar" id="statusBar'.$this->htmlname.'">'.$titlecontent;
268
+                $out.= ' &nbsp; - &nbsp; <a id="morelines" href="#" class="right morelines'.$this->htmlname.'">'.dol_escape_htmltag($langs->trans("ShowMoreLines")).'</a> &nbsp; &nbsp; ';
269
+                $out.= '</div>';
270
+                $out.= '<script type="text/javascript" language="javascript">'."\n";
271
+                $out.= 'jQuery(document).ready(function() {'."\n";
272
+                $out.= '	var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid");
273 273
 	    	    		   	var StatusBar = window.ace.require("ace/ext/statusbar").StatusBar;									// Init status bar. Need lib ext-statusbar
274 274
 	        			   	var statusBar = new StatusBar(aceEditor, document.getElementById("statusBar'.$this->htmlname.'"));	// Init status bar. Need lib ext-statusbar
275 275
 	            			var oldNbOfLines = 0
@@ -291,21 +291,21 @@  discard block
 block discarded – undo
291 291
 									}
292 292
 							});
293 293
 						})';
294
-	            $out.= '</script>'."\n";
295
-			}
294
+                $out.= '</script>'."\n";
295
+            }
296 296
 
297 297
             $out.= '<pre id="'.$this->htmlname.'aceeditorid" style="'.($this->width?'width: '.$this->width.'px; ':'');
298 298
             $out.= ($this->height?' height: '.$this->height.'px; ':'');
299 299
             //$out.=" min-height: 100px;";
300 300
             $out.= '">';
301
-        	$out.= htmlspecialchars($this->content);
302
-        	$out.= '</pre>';
303
-        	$out.= '<textarea id="'.$this->htmlname.'" name="'.$this->htmlname.'" style="width:0px; height: 0px; display: none;">';
304
-        	$out.= htmlspecialchars($this->content);
305
-        	$out.= '</textarea>';
301
+            $out.= htmlspecialchars($this->content);
302
+            $out.= '</pre>';
303
+            $out.= '<textarea id="'.$this->htmlname.'" name="'.$this->htmlname.'" style="width:0px; height: 0px; display: none;">';
304
+            $out.= htmlspecialchars($this->content);
305
+            $out.= '</textarea>';
306 306
 
307
-        	$out.= '<script type="text/javascript" language="javascript">'."\n";
308
-        	$out.= 'var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid");
307
+            $out.= '<script type="text/javascript" language="javascript">'."\n";
308
+            $out.= 'var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid");
309 309
 
310 310
 				    aceEditor.session.setMode("ace/mode/'.$format.'");
311 311
 					aceEditor.setOptions({
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 					//aceEditor.getSession().setMode("ace/mode/javascript_expression");
326 326
 					'."\n";
327 327
 
328
-        	$out.= 'jQuery(document).ready(function() {
328
+            $out.= 'jQuery(document).ready(function() {
329 329
 						jQuery(".buttonforacesave").click(function() {
330 330
         					console.log("We click on savefile button for component '.$this->htmlname.'");
331 331
         					var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid")
@@ -335,7 +335,7 @@  discard block
 block discarded – undo
335 335
 							else return false;*/
336 336
 	        			});
337 337
 					})';
338
-        	$out.= '</script>'."\n";
338
+            $out.= '</script>'."\n";
339 339
         }
340 340
 
341 341
         if (empty($found))
Please login to merge, or discard this patch.
Spacing   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
  */
29 29
 class DolEditor
30 30
 {
31
-    var $tool;      // Store the selected tool
31
+    var $tool; // Store the selected tool
32 32
 
33 33
 	// If using fckeditor
34 34
 	var $editor;
@@ -64,57 +64,57 @@  discard block
 block discarded – undo
64 64
 	 *      @param  string	$cols                   		Size of cols for textarea tool (textarea number of cols '70' or percent 'x%')
65 65
 	 *      @param	int		$readonly						0=Read/Edit, 1=Read only
66 66
 	 */
67
-    function __construct($htmlname, $content, $width='', $height=200, $toolbarname='Basic', $toolbarlocation='In', $toolbarstartexpanded=false, $uselocalbrowser=true, $okforextendededitor=true, $rows=0, $cols=0, $readonly=0)
67
+    function __construct($htmlname, $content, $width = '', $height = 200, $toolbarname = 'Basic', $toolbarlocation = 'In', $toolbarstartexpanded = false, $uselocalbrowser = true, $okforextendededitor = true, $rows = 0, $cols = 0, $readonly = 0)
68 68
     {
69
-    	global $conf,$langs;
69
+    	global $conf, $langs;
70 70
 
71 71
     	dol_syslog(get_class($this)."::DolEditor htmlname=".$htmlname." width=".$width." height=".$height." toolbarname=".$toolbarname);
72 72
 
73
-    	if (! $rows) $rows=round($height/20);
74
-    	if (! $cols) $cols=($width?round($width/6):80);
75
-		$shorttoolbarname=preg_replace('/_encoded$/','',$toolbarname);
73
+    	if (!$rows) $rows = round($height / 20);
74
+    	if (!$cols) $cols = ($width ?round($width / 6) : 80);
75
+		$shorttoolbarname = preg_replace('/_encoded$/', '', $toolbarname);
76 76
 
77 77
         // Name of extended editor to use (FCKEDITOR_EDITORNAME can be 'ckeditor' or 'fckeditor')
78
-        $defaulteditor='ckeditor';
79
-        $this->tool=empty($conf->global->FCKEDITOR_EDITORNAME)?$defaulteditor:$conf->global->FCKEDITOR_EDITORNAME;
80
-        $this->uselocalbrowser=$uselocalbrowser;
81
-        $this->readonly=$readonly;
78
+        $defaulteditor = 'ckeditor';
79
+        $this->tool = empty($conf->global->FCKEDITOR_EDITORNAME) ? $defaulteditor : $conf->global->FCKEDITOR_EDITORNAME;
80
+        $this->uselocalbrowser = $uselocalbrowser;
81
+        $this->readonly = $readonly;
82 82
 
83 83
         // Check if extended editor is ok. If not we force textarea
84 84
         if ((empty($conf->fckeditor->enabled) && $okforextendededitor != 'ace') || empty($okforextendededitor)) $this->tool = 'textarea';
85
-		if ($okforextendededitor === 'ace') $this->tool='ace';
85
+		if ($okforextendededitor === 'ace') $this->tool = 'ace';
86 86
         //if ($conf->dol_use_jmobile) $this->tool = 'textarea';       // ckeditor and ace seems ok with mobile
87 87
 
88 88
         // Define content and some properties
89 89
         if ($this->tool == 'ckeditor')
90 90
         {
91
-            $content=dol_htmlentitiesbr($content);  // If content is not HTML, we convert to HTML.
91
+            $content = dol_htmlentitiesbr($content); // If content is not HTML, we convert to HTML.
92 92
         }
93 93
         if ($this->tool == 'fckeditor')
94 94
     	{
95 95
         	require_once DOL_DOCUMENT_ROOT.'/includes/fckeditor/fckeditor.php';
96 96
 
97
-    		$content=dol_htmlentitiesbr($content);	// If content is not HTML, we convert to HTML.
97
+    		$content = dol_htmlentitiesbr($content); // If content is not HTML, we convert to HTML.
98 98
 
99 99
         	$this->editor = new FCKeditor($htmlname);
100
-        	$this->editor->BasePath = DOL_URL_ROOT.'/includes/fckeditor/' ;
101
-        	$this->editor->Value	= $content;
100
+        	$this->editor->BasePath = DOL_URL_ROOT.'/includes/fckeditor/';
101
+        	$this->editor->Value = $content;
102 102
         	$this->editor->Height   = $height;
103
-        	if (! empty($width)) $this->editor->Width = $width;
104
-        	$this->editor->ToolbarSet = $shorttoolbarname;         // Profile of this toolbar set is deinfed into theme/mytheme/ckeditor/config.js
105
-        	$this->editor->Config['AutoDetectLanguage'] = 'true';  // Language of user (browser)
103
+        	if (!empty($width)) $this->editor->Width = $width;
104
+        	$this->editor->ToolbarSet = $shorttoolbarname; // Profile of this toolbar set is deinfed into theme/mytheme/ckeditor/config.js
105
+        	$this->editor->Config['AutoDetectLanguage'] = 'true'; // Language of user (browser)
106 106
         	$this->editor->Config['ToolbarLocation'] = $toolbarlocation ? $toolbarlocation : 'In';
107 107
         	$this->editor->Config['ToolbarStartExpanded'] = $toolbarstartexpanded;
108 108
 
109 109
     		// Rem: Le forcage de ces 2 parametres ne semble pas fonctionner.
110 110
     		// Dolibarr utilise toujours liens avec modulepart='fckeditor' quelque soit modulepart.
111 111
     		// Ou se trouve donc cette valeur /viewimage.php?modulepart=fckeditor&file=' ?
112
-        	$modulepart='fckeditor';
112
+        	$modulepart = 'fckeditor';
113 113
     		$this->editor->Config['UserFilesPath'] = '/viewimage.php?modulepart='.$modulepart.'&entity='.$conf->entity.'&file=';
114
-    		$this->editor->Config['UserFilesAbsolutePath'] = DOL_DATA_ROOT.'/'.$modulepart.'/' ;
114
+    		$this->editor->Config['UserFilesAbsolutePath'] = DOL_DATA_ROOT.'/'.$modulepart.'/';
115 115
 
116
-        	$this->editor->Config['LinkBrowser']=($uselocalbrowser?'true':'false');
117
-        	$this->editor->Config['ImageBrowser']=($uselocalbrowser?'true':'false');
116
+        	$this->editor->Config['LinkBrowser'] = ($uselocalbrowser ? 'true' : 'false');
117
+        	$this->editor->Config['ImageBrowser'] = ($uselocalbrowser ? 'true' : 'false');
118 118
 
119 119
         	if (file_exists(DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/fckeditor/fckconfig.js'))
120 120
         	{
@@ -124,15 +124,15 @@  discard block
 block discarded – undo
124 124
     	}
125 125
 
126 126
     	// Define some properties
127
-        if (in_array($this->tool,array('textarea','ckeditor','ace')))
127
+        if (in_array($this->tool, array('textarea', 'ckeditor', 'ace')))
128 128
         {
129
-    	    $this->content				= $content;
129
+    	    $this->content = $content;
130 130
     	    $this->htmlname 			= $htmlname;
131
-    	    $this->toolbarname			= $shorttoolbarname;
131
+    	    $this->toolbarname = $shorttoolbarname;
132 132
     	    $this->toolbarstartexpanded = $toolbarstartexpanded;
133
-            $this->rows					= max(ROWS_3,$rows);
134
-            $this->cols					= (preg_match('/%/',$cols)?$cols:max(40,$cols));	// If $cols is a percent, we keep it, otherwise, we take max
135
-            $this->height				= $height;
133
+            $this->rows					= max(ROWS_3, $rows);
134
+            $this->cols					= (preg_match('/%/', $cols) ? $cols : max(40, $cols)); // If $cols is a percent, we keep it, otherwise, we take max
135
+            $this->height = $height;
136 136
             $this->width				= $width;
137 137
     	}
138 138
     }
@@ -149,48 +149,48 @@  discard block
 block discarded – undo
149 149
      *  @param	string	$option				 For ACE editor, set the source language ('html', 'php', 'javascript', ...)
150 150
      *  @return	void|string
151 151
      */
152
-    function Create($noprint=0, $morejs='', $disallowAnyContent=true, $titlecontent='', $option='')
152
+    function Create($noprint = 0, $morejs = '', $disallowAnyContent = true, $titlecontent = '', $option = '')
153 153
     {
154 154
         // phpcs:enable
155
-    	global $conf,$langs;
155
+    	global $conf, $langs;
156 156
 
157
-    	$fullpage=false;
157
+    	$fullpage = false;
158 158
     	if (isset($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT))
159 159
     	{
160
-    	   $disallowAnyContent=empty($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT);      // Only predefined list of html tags are allowed or all
160
+    	   $disallowAnyContent = empty($conf->global->FCKEDITOR_ALLOW_ANY_CONTENT); // Only predefined list of html tags are allowed or all
161 161
     	}
162 162
 
163
-    	$found=0;
164
-		$out='';
163
+    	$found = 0;
164
+		$out = '';
165 165
 
166 166
         if ($this->tool == 'fckeditor') // not used anymore
167 167
         {
168
-			$found=1;
168
+			$found = 1;
169 169
             $this->editor->Create();
170 170
         }
171
-        if (in_array($this->tool,array('textarea','ckeditor')))
171
+        if (in_array($this->tool, array('textarea', 'ckeditor')))
172 172
         {
173
-            $found=1;
173
+            $found = 1;
174 174
             //$out.= '<textarea id="'.$this->htmlname.'" name="'.$this->htmlname.'" '.($this->readonly?' disabled':'').' rows="'.$this->rows.'"'.(preg_match('/%/',$this->cols)?' style="margin-top: 5px; width: '.$this->cols.'"':' cols="'.$this->cols.'"').' class="flat">';
175 175
             // TODO We do not put the disabled tag because on a read form, it change style with grey.
176
-            $out.= '<textarea id="'.$this->htmlname.'" name="'.$this->htmlname.'" rows="'.$this->rows.'"'.(preg_match('/%/',$this->cols)?' style="margin-top: 5px; width: '.$this->cols.'"':' cols="'.$this->cols.'"').' class="flat">';
177
-            $out.= $this->content;
178
-            $out.= '</textarea>';
176
+            $out .= '<textarea id="'.$this->htmlname.'" name="'.$this->htmlname.'" rows="'.$this->rows.'"'.(preg_match('/%/', $this->cols) ? ' style="margin-top: 5px; width: '.$this->cols.'"' : ' cols="'.$this->cols.'"').' class="flat">';
177
+            $out .= $this->content;
178
+            $out .= '</textarea>';
179 179
 
180
-            if ($this->tool == 'ckeditor' && ! empty($conf->use_javascript_ajax))
180
+            if ($this->tool == 'ckeditor' && !empty($conf->use_javascript_ajax))
181 181
             {
182
-            	if (! defined('REQUIRE_CKEDITOR')) define('REQUIRE_CKEDITOR','1');
182
+            	if (!defined('REQUIRE_CKEDITOR')) define('REQUIRE_CKEDITOR', '1');
183 183
 
184
-            	if (! empty($conf->global->FCKEDITOR_SKIN)) {
184
+            	if (!empty($conf->global->FCKEDITOR_SKIN)) {
185 185
 					$skin = $conf->global->FCKEDITOR_SKIN;
186 186
 				} else {
187 187
 					$skin = 'moono-lisa'; // default with ckeditor 4.6 : moono-lisa
188 188
 				}
189 189
 
190
-            	$htmlencode_force=preg_match('/_encoded$/',$this->toolbarname)?'true':'false';
190
+            	$htmlencode_force = preg_match('/_encoded$/', $this->toolbarname) ? 'true' : 'false';
191 191
 
192
-            	$out.= '<!-- Output ckeditor $disallowAnyContent='.$disallowAnyContent.' toolbarname='.$this->toolbarname.' -->'."\n";
193
-            	$out.= '<script type="text/javascript">
192
+            	$out .= '<!-- Output ckeditor $disallowAnyContent='.$disallowAnyContent.' toolbarname='.$this->toolbarname.' -->'."\n";
193
+            	$out .= '<script type="text/javascript">
194 194
             			$(document).ready(function () {
195 195
                             /* if (CKEDITOR.loadFullCore) CKEDITOR.loadFullCore(); */
196 196
                             /* should be editor=CKEDITOR.replace but what if serveral editors ? */
@@ -198,11 +198,11 @@  discard block
 block discarded – undo
198 198
             					{
199 199
             						/* property:xxx is same than CKEDITOR.config.property = xxx */
200 200
             						customConfig : ckeditorConfig,
201
-            						readOnly : '.($this->readonly?'true':'false').',
201
+            						readOnly : '.($this->readonly ? 'true' : 'false').',
202 202
                             		htmlEncodeOutput :'.$htmlencode_force.',
203
-            						allowedContent :'.($disallowAnyContent?'false':'true').',
203
+            						allowedContent :'.($disallowAnyContent ? 'false' : 'true').',
204 204
             						extraAllowedContent : \'\',
205
-            						fullPage : '.($fullpage?'true':'false').',
205
+            						fullPage : '.($fullpage ? 'true' : 'false').',
206 206
                             		toolbar: \''.$this->toolbarname.'\',
207 207
             						toolbarStartupExpanded: '.($this->toolbarstartexpanded ? 'true' : 'false').',
208 208
             						width: '.($this->width ? '\''.$this->width.'\'' : '\'\'').',
@@ -227,13 +227,13 @@  discard block
 block discarded – undo
227 227
                                             }';
228 228
             	if ($this->uselocalbrowser)
229 229
             	{
230
-                    $out.= ','."\n";
230
+                    $out .= ','."\n";
231 231
                     // To use filemanager with old fckeditor (GPL)
232
-                    $out.= '    filebrowserBrowseUrl : ckeditorFilebrowserBrowseUrl,';
233
-                    $out.= '    filebrowserImageBrowseUrl : ckeditorFilebrowserImageBrowseUrl,';
232
+                    $out .= '    filebrowserBrowseUrl : ckeditorFilebrowserBrowseUrl,';
233
+                    $out .= '    filebrowserImageBrowseUrl : ckeditorFilebrowserImageBrowseUrl,';
234 234
                     //$out.= '    filebrowserUploadUrl : \''.DOL_URL_ROOT.'/includes/fckeditor/editor/filemanagerdol/connectors/php/upload.php?Type=File\',';
235 235
                     //$out.= '    filebrowserImageUploadUrl : \''.DOL_URL_ROOT.'/includes/fckeditor/editor/filemanagerdol/connectors/php/upload.php?Type=Image\',';
236
-                    $out.= "\n";
236
+                    $out .= "\n";
237 237
                     // To use filemanager with ckfinder (Non free) and ckfinder directory is inside htdocs/includes
238 238
 					/* $out.= '    filebrowserBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html\',
239 239
                                filebrowserImageBrowseUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/ckfinder.html?Type=Images\',
@@ -242,14 +242,14 @@  discard block
 block discarded – undo
242 242
                                filebrowserImageUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images\',
243 243
                                filebrowserFlashUploadUrl : \''.DOL_URL_ROOT.'/includes/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash\','."\n";
244 244
 					*/
245
-                    $out.= '    filebrowserWindowWidth : \'900\',
245
+                    $out .= '    filebrowserWindowWidth : \'900\',
246 246
                                filebrowserWindowHeight : \'500\',
247 247
                                filebrowserImageWindowWidth : \'900\',
248 248
                                filebrowserImageWindowHeight : \'500\'';
249 249
             	}
250
-            	$out.= '	})'.$morejs;
251
-            	$out.= '});'."\n";
252
-            	$out.= '</script>'."\n";
250
+            	$out .= '	})'.$morejs;
251
+            	$out .= '});'."\n";
252
+            	$out .= '</script>'."\n";
253 253
             }
254 254
         }
255 255
 
@@ -257,19 +257,19 @@  discard block
 block discarded – undo
257 257
         // Warning: ace.js and ext-statusbar.js must be loaded by the parent page.
258 258
         if (preg_match('/^ace/', $this->tool))
259 259
         {
260
-        	$found=1;
261
-			$format=$option;
260
+        	$found = 1;
261
+			$format = $option;
262 262
 
263
-            $out.= "\n".'<!-- Output Ace editor -->'."\n";
263
+            $out .= "\n".'<!-- Output Ace editor -->'."\n";
264 264
 
265 265
 			if ($titlecontent)
266 266
 			{
267
-	            $out.= '<div class="aceeditorstatusbar" id="statusBar'.$this->htmlname.'">'.$titlecontent;
268
-	            $out.= ' &nbsp; - &nbsp; <a id="morelines" href="#" class="right morelines'.$this->htmlname.'">'.dol_escape_htmltag($langs->trans("ShowMoreLines")).'</a> &nbsp; &nbsp; ';
269
-	            $out.= '</div>';
270
-	            $out.= '<script type="text/javascript" language="javascript">'."\n";
271
-	            $out.= 'jQuery(document).ready(function() {'."\n";
272
-	            $out.= '	var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid");
267
+	            $out .= '<div class="aceeditorstatusbar" id="statusBar'.$this->htmlname.'">'.$titlecontent;
268
+	            $out .= ' &nbsp; - &nbsp; <a id="morelines" href="#" class="right morelines'.$this->htmlname.'">'.dol_escape_htmltag($langs->trans("ShowMoreLines")).'</a> &nbsp; &nbsp; ';
269
+	            $out .= '</div>';
270
+	            $out .= '<script type="text/javascript" language="javascript">'."\n";
271
+	            $out .= 'jQuery(document).ready(function() {'."\n";
272
+	            $out .= '	var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid");
273 273
 	    	    		   	var StatusBar = window.ace.require("ace/ext/statusbar").StatusBar;									// Init status bar. Need lib ext-statusbar
274 274
 	        			   	var statusBar = new StatusBar(aceEditor, document.getElementById("statusBar'.$this->htmlname.'"));	// Init status bar. Need lib ext-statusbar
275 275
 	            			var oldNbOfLines = 0
@@ -291,21 +291,21 @@  discard block
 block discarded – undo
291 291
 									}
292 292
 							});
293 293
 						})';
294
-	            $out.= '</script>'."\n";
294
+	            $out .= '</script>'."\n";
295 295
 			}
296 296
 
297
-            $out.= '<pre id="'.$this->htmlname.'aceeditorid" style="'.($this->width?'width: '.$this->width.'px; ':'');
298
-            $out.= ($this->height?' height: '.$this->height.'px; ':'');
297
+            $out .= '<pre id="'.$this->htmlname.'aceeditorid" style="'.($this->width ? 'width: '.$this->width.'px; ' : '');
298
+            $out .= ($this->height ? ' height: '.$this->height.'px; ' : '');
299 299
             //$out.=" min-height: 100px;";
300
-            $out.= '">';
301
-        	$out.= htmlspecialchars($this->content);
302
-        	$out.= '</pre>';
303
-        	$out.= '<textarea id="'.$this->htmlname.'" name="'.$this->htmlname.'" style="width:0px; height: 0px; display: none;">';
304
-        	$out.= htmlspecialchars($this->content);
305
-        	$out.= '</textarea>';
300
+            $out .= '">';
301
+        	$out .= htmlspecialchars($this->content);
302
+        	$out .= '</pre>';
303
+        	$out .= '<textarea id="'.$this->htmlname.'" name="'.$this->htmlname.'" style="width:0px; height: 0px; display: none;">';
304
+        	$out .= htmlspecialchars($this->content);
305
+        	$out .= '</textarea>';
306 306
 
307
-        	$out.= '<script type="text/javascript" language="javascript">'."\n";
308
-        	$out.= 'var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid");
307
+        	$out .= '<script type="text/javascript" language="javascript">'."\n";
308
+        	$out .= 'var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid");
309 309
 
310 310
 				    aceEditor.session.setMode("ace/mode/'.$format.'");
311 311
 					aceEditor.setOptions({
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
 					   enableLiveAutocompletion: false, // the editor completes the statement while you are typing. Need lib ext-language_tools.js
314 314
 					   showPrintMargin: false, // hides the vertical limiting strip
315 315
 					   minLines: 10,
316
-					   maxLines: '.(empty($this->height)?'34':(round($this->height/10))).',
316
+					   maxLines: '.(empty($this->height) ? '34' : (round($this->height / 10))).',
317 317
 				       fontSize: "110%" // ensures that the editor fits in the environment
318 318
 					});
319 319
 
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 					//aceEditor.getSession().setMode("ace/mode/javascript_expression");
326 326
 					'."\n";
327 327
 
328
-        	$out.= 'jQuery(document).ready(function() {
328
+        	$out .= 'jQuery(document).ready(function() {
329 329
 						jQuery(".buttonforacesave").click(function() {
330 330
         					console.log("We click on savefile button for component '.$this->htmlname.'");
331 331
         					var aceEditor = window.ace.edit("'.$this->htmlname.'aceeditorid")
@@ -335,12 +335,12 @@  discard block
 block discarded – undo
335 335
 							else return false;*/
336 336
 	        			});
337 337
 					})';
338
-        	$out.= '</script>'."\n";
338
+        	$out .= '</script>'."\n";
339 339
         }
340 340
 
341 341
         if (empty($found))
342 342
         {
343
-            $out.= 'Error, unknown value for tool '.$this->tool.' in DolEditor Create function.';
343
+            $out .= 'Error, unknown value for tool '.$this->tool.' in DolEditor Create function.';
344 344
         }
345 345
 
346 346
         if ($noprint) return $out;
Please login to merge, or discard this patch.
Braces   +26 added lines, -9 removed lines patch added patch discarded remove patch
@@ -70,8 +70,12 @@  discard block
 block discarded – undo
70 70
 
71 71
     	dol_syslog(get_class($this)."::DolEditor htmlname=".$htmlname." width=".$width." height=".$height." toolbarname=".$toolbarname);
72 72
 
73
-    	if (! $rows) $rows=round($height/20);
74
-    	if (! $cols) $cols=($width?round($width/6):80);
73
+    	if (! $rows) {
74
+    	    $rows=round($height/20);
75
+    	}
76
+    	if (! $cols) {
77
+    	    $cols=($width?round($width/6):80);
78
+    	}
75 79
 		$shorttoolbarname=preg_replace('/_encoded$/','',$toolbarname);
76 80
 
77 81
         // Name of extended editor to use (FCKEDITOR_EDITORNAME can be 'ckeditor' or 'fckeditor')
@@ -81,8 +85,12 @@  discard block
 block discarded – undo
81 85
         $this->readonly=$readonly;
82 86
 
83 87
         // Check if extended editor is ok. If not we force textarea
84
-        if ((empty($conf->fckeditor->enabled) && $okforextendededitor != 'ace') || empty($okforextendededitor)) $this->tool = 'textarea';
85
-		if ($okforextendededitor === 'ace') $this->tool='ace';
88
+        if ((empty($conf->fckeditor->enabled) && $okforextendededitor != 'ace') || empty($okforextendededitor)) {
89
+            $this->tool = 'textarea';
90
+        }
91
+		if ($okforextendededitor === 'ace') {
92
+		    $this->tool='ace';
93
+		}
86 94
         //if ($conf->dol_use_jmobile) $this->tool = 'textarea';       // ckeditor and ace seems ok with mobile
87 95
 
88 96
         // Define content and some properties
@@ -100,7 +108,9 @@  discard block
 block discarded – undo
100 108
         	$this->editor->BasePath = DOL_URL_ROOT.'/includes/fckeditor/' ;
101 109
         	$this->editor->Value	= $content;
102 110
         	$this->editor->Height   = $height;
103
-        	if (! empty($width)) $this->editor->Width = $width;
111
+        	if (! empty($width)) {
112
+        	    $this->editor->Width = $width;
113
+        	}
104 114
         	$this->editor->ToolbarSet = $shorttoolbarname;         // Profile of this toolbar set is deinfed into theme/mytheme/ckeditor/config.js
105 115
         	$this->editor->Config['AutoDetectLanguage'] = 'true';  // Language of user (browser)
106 116
         	$this->editor->Config['ToolbarLocation'] = $toolbarlocation ? $toolbarlocation : 'In';
@@ -163,9 +173,11 @@  discard block
 block discarded – undo
163 173
     	$found=0;
164 174
 		$out='';
165 175
 
166
-        if ($this->tool == 'fckeditor') // not used anymore
176
+        if ($this->tool == 'fckeditor') {
177
+            // not used anymore
167 178
         {
168 179
 			$found=1;
180
+        }
169 181
             $this->editor->Create();
170 182
         }
171 183
         if (in_array($this->tool,array('textarea','ckeditor')))
@@ -179,7 +191,9 @@  discard block
 block discarded – undo
179 191
 
180 192
             if ($this->tool == 'ckeditor' && ! empty($conf->use_javascript_ajax))
181 193
             {
182
-            	if (! defined('REQUIRE_CKEDITOR')) define('REQUIRE_CKEDITOR','1');
194
+            	if (! defined('REQUIRE_CKEDITOR')) {
195
+            	    define('REQUIRE_CKEDITOR','1');
196
+            	}
183 197
 
184 198
             	if (! empty($conf->global->FCKEDITOR_SKIN)) {
185 199
 					$skin = $conf->global->FCKEDITOR_SKIN;
@@ -343,7 +357,10 @@  discard block
 block discarded – undo
343 357
             $out.= 'Error, unknown value for tool '.$this->tool.' in DolEditor Create function.';
344 358
         }
345 359
 
346
-        if ($noprint) return $out;
347
-        else print $out;
360
+        if ($noprint) {
361
+            return $out;
362
+        } else {
363
+            print $out;
364
+        }
348 365
     }
349 366
 }
Please login to merge, or discard this patch.